Convert for loop to while loop
5 ビュー (過去 30 日間)
古いコメントを表示
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
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
2020 年 10 月 5 日
編集済み: 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
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!