Convert for loop to while loop

4 views (last 30 days)
Kathleen Whitmore
Kathleen Whitmore on 5 Oct 2020
Edited: madhan ravi on 5 Oct 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!

Answers (1)

madhan ravi
madhan ravi on 5 Oct 2020
Edited: madhan ravi on 5 Oct 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 Comment
madhan ravi
madhan ravi on 5 Oct 2020
Edited: madhan ravi on 5 Oct 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

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by