Converting a for loop to a while loop
13 次查看(过去 30 天)
显示 更早的评论
I'm trying to convert this for loop into a while loop but keep getting the x value of the while loop as zero when it should be random values.
% code
x=0;
y=randi(100,1,5);
for i = 1:5
x=x+y(i);
end This is what I have:
% code
x=0;
y=randi(100,1,5);
while i<6 && i>0
x=x+y(i);
i=i+1;
endNot sure how to get the x value to 'work'
0 个评论
回答(2 个)
madhan ravi
2018-10-1
编辑:madhan ravi
2018-10-1
x=zeros(1,5);
y=randi(100,1,5);
i=1
while i<6
x(i)=x(i)+y(i)
i=i+1;
end
3 个评论
Jan
2018-10-1
The problem is, that i has not been initialized before the while loop. Then i is defined as sqrt(-1). See madhan ravi's answer, where i=1 is defined before the loop.
0 个评论
另请参阅
类别
在 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!