MATLAB: How would i make the for loop stop calculating when it calculates F <= 0? I want the for loop to stop writing. values in F when it hits 0 or less. I have tried "break", but can not seem to get it to work.

for looploop

n = 10;
terskelverdi = 0.1;
F = zeros(n,1);
F(1) = 1;
F(2) = 1;
for k = 3:n
r = rand(1);
if r > terskelverdi
F(k) = F(k-1) + F(k-2);
else
F(k) = F(k-1) - F(k-2);
end
end
if F > 0
disp(F)
figure, plot(F), grid
title('Fibonaccitall med tilfeldigheter opp til "n"')
else
disp('Kaninbestanden er utryddet')
end

Best Answer

You should simply check F(k), inside your loop,
for k = 3:n
r = rand(1);
if r > terskelverdi
F(k) = F(k-1) + F(k-2);
else
F(k) = F(k-1) - F(k-2);
end
if F(k)<=0
F(k) = 0; %if you want to set the last found value to 0
break
end
end
or, after you calculate F, you could set all the negative to 0 (but I don't know if you'd like it this way for your actual problem)
F(F<=0)=0;
Related Question