Borrar filtros
Borrar filtros

How to create a matrices using while loop?

39 visualizaciones (últimos 30 días)
Teb Keb
Teb Keb el 14 de Feb. de 2022
Comentada: Teb Keb el 15 de Feb. de 2022
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,

Respuesta aceptada

Stephen23
Stephen23 el 14 de Feb. de 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
  1 comentario
Teb Keb
Teb Keb el 15 de Feb. de 2022
thank you, so much. It clarified lot of stuff.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by