MATLAB Answers

Break the for loop

5 views (last 30 days)
Julenissen
Julenissen on 26 Oct 2021
Commented: Mathieu NOE on 27 Oct 2021
Hi! I have a for loop that fills my vector with fibonacci numbers if random number from 0 to 1 is greater than 0,1. In cases when random number is less than 0,1, instead of adding the leading digits, it subtracts. So normally result looks like this:
1
1
2
3
5
8
13
5
18
23
But in some cases random number from 0 to 1 gives value less than 0,1 twice in a row and i get a table with fibonacci number <= 0 that looks like this:
1
1
2
3
1
-2
-1
-3
-4
-7
So i have two questions that i have not managed to solve.
  1. How to stop the loop when i get first negative value (in this case -2) and write a message about that?
  2. How to make this for loop automaticly go over and over again (implement it in while loop?) until i get a negative value and than stop it and then write this message? Is it possible to count how many times (while?) loop had to start before negative value was found?
n = 10;
limitf = 0.1;
F = zeros(n,1);
F(1) = 1;
F(2) = 1;
for k = 3:n
r = rand(1);
if r > limitf
F(k) = F(k-1) + F(k-2);
else
F(k) = F(k-1) - F(k-2);
end
end
disp(F)

Accepted Answer

Mathieu NOE
Mathieu NOE on 26 Oct 2021
hello
I modified a bit your code so the condition were the two successive identical random r :
n = 10;
limitf = 0.1;
F = zeros(n,1);
F(1) = 1;
F(2) = 1;
r_old = -1;
for k = 3:n
r_old = r;
r = rand(1);
if r > limitf
F(k) = F(k-1) + F(k-2);
else
if abs(r-r_old)>eps
F(k) = F(k-1) - F(k-2);
end
end
end
disp(F)
  6 Comments
Mathieu NOE
Mathieu NOE on 27 Oct 2021
My pleasure !

Sign in to comment.

More Answers (1)

Alan Stevens
Alan Stevens on 26 Oct 2021
Something like this perhaps:
fib = [1; 1];
its = 0;
keepgoing = true;
while keepgoing
its = its+1;
r = rand;
if r>0.1
fib(its+2) = fib(its+1) + fib(its);
else
fib(its+2) = fib(its+1) - fib(its);
end
if fib(its+2)<0
keepgoing = false;
end
end
disp(['number of iterations ' num2str(its)])
  4 Comments
Julenissen
Julenissen on 26 Oct 2021
The next loop have to start from 1 and 1 again :)

Sign in to comment.

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by