Converting a for loop to a while loop

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'

Réponses (2)

madhan ravi
madhan ravi le 1 Oct 2018
Modifié(e) : madhan ravi le 1 Oct 2018
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 commentaires

madhan ravi
madhan ravi le 11 Oct 2018
@Samantha Farmer haven’t heard from you in a while
Samantha Farmer
Samantha Farmer le 11 Oct 2018
I've been understanding my hw for a little bit :)
madhan ravi
madhan ravi le 12 Oct 2018
Ok if it worked make sure to accept the answer as well :)

Connectez-vous pour commenter.

Jan
Jan le 1 Oct 2018

0 votes

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.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by