Write program by For loop, how can I stop

1 次查看(过去 30 天)
Hi guys, I have a program, I use for loop, the answer is right , but I want to stop on the first negative answer. This is my program
A=[40 47 50 60 70 75 80 80 90 55];
B(1)=70;
C(1)=60;
for k=1:9;
C(k+1)= B(k)+C(k)-A(k);
B(k+1)= A(k);
if C(k+1)>=40
B(k+1)=0
k=k+1
end
end
C=C
The answer is 60 90 43 -7 -17 -27 -32 -37 -37 -47
How can I stop the answer on -7
Thank you

采纳的回答

Matt Fig
Matt Fig 2012-10-20
A=[40 47 50 60 70 75 80 80 90 55];
B(1)=70;
C(1)=60;
for k=1:9;
C(k+1)= B(k)+C(k)-A(k);
if C(k+1)<0,break,end % Stops the loop.
B(k+1)= A(k);
if C(k+1)>=40
B(k+1)=0
k=k+1
end
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by