How convert for loop to while loop?

조회 수: 11 (최근 30일)
Hasan Berke Bankoglu
Hasan Berke Bankoglu 2020년 5월 23일
댓글: Hasan Berke Bankoglu 2020년 5월 23일
I must convert that for loop to while loop. How can I do that? I tried somethings but I couldn't get right result.
A=zeros(5,8);
[r,c]=size(A);
%for loop
for i=1:r % loops over rows
for j=1:c % loops over columns
if i>j
A(i,j)=4*i-2*j;
elseif i<=j
A(i,j)=i^2-3*j;
end
end
end
A

채택된 답변

KSSV
KSSV 2020년 5월 23일
A=zeros(5,8);
[r,c]=size(A);
%for loop
i = 0 ;
while i<r % loops over rows
i = i+1 ;
j = 0 ;
while j<c % loops over columns
j = j+1 ;
if i>j
A(i,j)=4*i-2*j;
elseif i<=j
A(i,j)=i^2-3*j;
end
end
end
A
  댓글 수: 3
KSSV
KSSV 2020년 5월 23일
Thanks is accepting the answer.....what is another question?
Hasan Berke Bankoglu
Hasan Berke Bankoglu 2020년 5월 23일
Other question is about exponential e. I submit it below. When I write code for while loop, I had to change a3 as 1 instead of 0. Nevertheless, I could get right result.
% a
% for loop k = 5
a3=0;
x=2;
k = 5
for n = 0:k
a3 = a3 + (x^n/factorial(n));
end
display(a3)
exp(2)
%while loop k = 5
a3=1;
x=2;
n=0;
k=5 % k = 5
while n<k
n = n+1;
a3 = a3 + (x^n/factorial(n));
end
display(a3)
exp(2)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by