필터 지우기
필터 지우기

How to create a matrices using while loop?

조회 수: 39 (최근 30일)
Teb Keb
Teb Keb 2022년 2월 14일
댓글: Teb Keb 2022년 2월 15일
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
  댓글 수: 1
Teb Keb
Teb Keb 2022년 2월 15일
thank you, so much. It clarified lot of stuff.

댓글을 달려면 로그인하십시오.

추가 답변 (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