Clear Filters
Clear Filters

How to create a matrices using while loop?

39 views (last 30 days)
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,

Accepted Answer

Stephen23
Stephen23 on 14 Feb 2022
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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!