Stop for loop if F <= 0

13 ビュー (過去 30 日間)
Malcolm Taylor Hansen
Malcolm Taylor Hansen 2015 年 10 月 7 日
回答済み: Walter Roberson 2015 年 10 月 7 日
I wonder how it is possible to stop a for loop without using break. I have tried to expand the code with a while loop, but I do not manage to get it to work. Appreciate hints.
n = 20;
terskelverdi = 0.1;
F = zeros(1,n);
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
disp(F)
figure, plot(F,'g-'), grid
title('Fibonaccitall med tilfeldigheter opp til "n"')
  1 件のコメント
Mohammad Abouali
Mohammad Abouali 2015 年 10 月 7 日
just curious, Why you don't want to use break?

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2015 年 10 月 7 日
To stop a "for" loop without using "break", you can do one of:
  • reach the natural end of iterations for the loop
  • "return" to a calling routine
  • "error" out to an enclosing try/catch (or the command line)
  • quit or exit MATLAB

その他の回答 (1 件)

Jon
Jon 2015 年 10 月 7 日
編集済み: Jon 2015 年 10 月 7 日
Why are you opposed to using break? If you mean that you want to redraw a random number if F <=0, you could do something like this:
count = 3;
while 1
r = rand(1);
if r > terskelverdi
F(count) = F(count-1) + F(count-2);
else
F(count) = F(count-1) - F(count-2);
end
if F(k) > 0
count = count + 1;
end
if count == n
break
end
end
but this could cause an infinite loop. Not sure what your objective is, so I can't help more.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by