Convert for loop to while loop

5 visualizaciones (últimos 30 días)
Kathleen Whitmore
Kathleen Whitmore el 5 de Oct. de 2020
Editada: madhan ravi el 5 de Oct. de 2020
Hi!
I am trying to convert a for loop to a while loop that will produce the same result. Although I understand the concept, I keep running into an error that I'm not sure how to fix. Any help would be appreciated!
The for loop:
x=0;
y=randi(100,1,5);
for i = 1:5 x=x+y(i);
end disp(x);
And I came up with the while loop:
x=0;
y=randi(100,1,5);
i=1;
while i <= 5
i=i+1;
x=x+y(i);
end
disp(x);
However, it keeps giving me the error "Index exceeds the number of array elements (5).
Error in Example (line 6)
x=x+y(i);"
I don't understand why this is happening, since the while loop should run 5 times, increasing the i value by 1 each time, and the vector y has 5 elements.
Like I said, any help would be appreciated! Thank you!

Respuestas (1)

madhan ravi
madhan ravi el 5 de Oct. de 2020
Editada: madhan ravi el 5 de Oct. de 2020
Initialise ii with 0 instead of 1. Otherwise you start it as 2 therefore when you reach 5 it gets incremented to 6 exceeding the number of elements in y which has 5 elements.
  1 comentario
madhan ravi
madhan ravi el 5 de Oct. de 2020
Editada: madhan ravi el 5 de Oct. de 2020
y = randi(100, 1, 5);
x = zeros(size(y)); % preallocate x properly
ii = 0;
while ii <= 5
ii = ii + 1;
x(ii) = x(ii) + y(ii);
end
x

Iniciar sesión para comentar.

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by