How to create a matrices using while loop?
30 次查看(过去 30 天)
显示 更早的评论
Hi,
I am creating a 6x3 matrices using while loop with the variable increments by 1 (increment=1:1:5). My codes seems to work but it shows one row of the result at a time, instead of creating a matrices with 6 rows and 3 columns in the command window.
>> r=0.1;
y=2.5;
i=0;
while i<=5
i=i+1;
dis(i)=r.*sin(y.*i);
tim(i)=dis(i)*2;
a=[i dis(i) tim(i)]
end
a =
1.0000 0.0598 0.1197
a =
2.0000 -0.0959 -0.1918
a =
3.0000 0.0938 0.1876
a =
4.0000 -0.0544 -0.1088
a =
5.0000 -0.0066 -0.0133
a =
6.0000 0.0650 0.1301
Instead of having my answer a=, how do i put them into matrix array (6x3) as the increments increases by 1 until it hits 5 using while loop only?
Thank you,
0 个评论
采纳的回答
Stephen23
2022-2-14
r = 0.1;
y = 2.5;
i = 0;
a = []; % <---
while i<=5
i=i+1;
dis = r.*sin(y.*i);
tim = dis*2;
a = [a;i,dis,tim];
% ^^
end
display(a)
But this is not an efficient use of MATLAB. A much better approach is to use a FOR loop with preallocated array, e.g.:
N = 6;
a = nan(N,3);
for k = 1:N
dis = r.*sin(y.*k);
tim = dis*2;
a(k,:) = [k,dis,tim];
end
display(a)
Note that using a loop is not required, the simpler MATLAB approach would be something like this:
vec = 1:N;
dis = r.*sin(y.*vec);
tim = dis*2;
a = [vec;dis;tim].'
更多回答(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!