MATLAB: Write program by For loop, how can I stop

for loopMATLAB

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

Best Answer

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
Related Question