MATLAB Answers

Convert for loop to while loop

1 ビュー (過去 30 日間)
Kathleen Whitmore
Kathleen Whitmore 2020 年 10 月 5 日
編集済み: madhan ravi 2020 年 10 月 5 日
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!

  0 件のコメント

サインインしてコメントする。

回答 (1 件)

madhan ravi
madhan ravi 2020 年 10 月 5 日
編集済み: madhan ravi 2020 年 10 月 5 日
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 件のコメント

madhan ravi
madhan ravi 2020 年 10 月 5 日
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

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by