create vector in for loop and then need to store vector in a matrix one after another
2 次查看(过去 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!