How to create a matrices using while loop?

39 次查看(过去 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,

采纳的回答

Stephen23
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)
a = 6×3
1.0000 0.0598 0.1197 2.0000 -0.0959 -0.1918 3.0000 0.0938 0.1876 4.0000 -0.0544 -0.1088 5.0000 -0.0066 -0.0133 6.0000 0.0650 0.1301
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)
a = 6×3
1.0000 0.0598 0.1197 2.0000 -0.0959 -0.1918 3.0000 0.0938 0.1876 4.0000 -0.0544 -0.1088 5.0000 -0.0066 -0.0133 6.0000 0.0650 0.1301
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].'
a = 6×3
1.0000 0.0598 0.1197 2.0000 -0.0959 -0.1918 3.0000 0.0938 0.1876 4.0000 -0.0544 -0.1088 5.0000 -0.0066 -0.0133 6.0000 0.0650 0.1301

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by