Convert for loop to while loop
14 次查看(过去 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!