create vector in for loop and then need to store vector in a matrix one after another
조회 수: 4 (최근 30일)
이전 댓글 표시
I want to create a code in double for loop shown below. When vector "v" creates in first run then its store values but when internal "for loop" increaed the value of b by 0.1 then previous values in vector v replaced. I need both values and i don,t understand how i get?
Every time value changed i need. I want to store values in a matrix means first run stores in first row, then value increment in internal for loop then this valus agiain stored ina matrix and so on. at the end i need all combinations in a matrix.
Can anyone give me a suitable suggestion? thanks in advance
clear all
for a=1:0.1:2
k1=a
for b=1:0.1:2
k2=b;
v=[k1 k2]
newtable=array2table(v)
end
end
댓글 수: 1
Rik
2022년 4월 22일
You aren't using any indexing. I suggest you have a look at the relevant chapter of the Onramp tutorial.
채택된 답변
Voss
2022년 4월 22일
Is this what you mean?
clear all
v = [];
for a=1:0.1:2
k1=a;
for b=1:0.1:2
k2=b;
v(end+1,:)=[k1 k2];
end
end
disp(v);
댓글 수: 5
Voss
2022년 4월 22일
The end keyword in an indexing expression refers to the last index of the dimension it's used. So v(end,:) refers to the last row of v, and v(end+1,:) would refer to the row one beyond the last row. In this expression:
v(end+1,:)=[k1 k2 k3]
[k1 k2 k3] is assigned to the row one beyond the last row of v, so the effect is to add a new row to the end of v containing [k1 k2 k3].
About the Simulink block question, I don't know. I've never used Simulink. Maybe ask a new question about it and post the latest version of your code in the new question.
Rik
2022년 4월 23일
Some comments:
You should avoid clear all. You never actually need it. Using clear or clearvars instead is almost always enough for a debugging script. For actual use, you should be using a function, which will always start out with a clean workspace.
You should try to determine the size of your array based on your variables. That way you can pre-allocate the entire array, which avoids data copying when extending the array, and will also give you an early warning if there are memory issues.
I strongly suggest to do the Onramp tutorial. It is really worth the investment to learn the tool you're using.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!