Converting a for loop to a while loop

조회 수: 13 (최근 30일)
Samantha Farmer
Samantha Farmer 2018년 10월 1일
댓글: madhan ravi 2018년 10월 12일

I'm trying to convert this for loop into a while loop but keep getting the x value of the while loop as zero when it should be random values.

    % code
x=0; 
y=randi(100,1,5); 
for i = 1:5     
    x=x+y(i); 
end 

This is what I have:

    % code
 x=0;
 y=randi(100,1,5);
 while i<6 && i>0
     x=x+y(i);
    i=i+1;
 end

Not sure how to get the x value to 'work'

답변 (2개)

madhan ravi
madhan ravi 2018년 10월 1일
편집: madhan ravi 2018년 10월 1일
x=zeros(1,5);
y=randi(100,1,5);
i=1
while i<6
x(i)=x(i)+y(i)
i=i+1;
end
  댓글 수: 3
Samantha Farmer
Samantha Farmer 2018년 10월 11일
I've been understanding my hw for a little bit :)
madhan ravi
madhan ravi 2018년 10월 12일
Ok if it worked make sure to accept the answer as well :)

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


Jan
Jan 2018년 10월 1일
The problem is, that i has not been initialized before the while loop. Then i is defined as sqrt(-1). See madhan ravi's answer, where i=1 is defined before the loop.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by