How can I break this while loop and store the data?

1 vue (au cours des 30 derniers jours)
Alicia Cuber Caballero
Alicia Cuber Caballero le 31 Juil 2019
Hi! I'm trying to generate a collatz sequence for any n and to stop when n == 1. I used the following:
n=7
while n>1
if mod(n, 2)==0
n = n/2
end
if mod(n,2)~=0
n = (3.*n)+1
end
end
I thought it would stop generating when n reached 1, given the conditions for the while loop, but it just doesn't. As a result, it keeps running forever and matlab can't handle it and the site closes. I tried adding
if n==1
break
end
right after "while n>1" but it doesn't work either. I also want to store the sequence generated (which will vary in size depending on the value of n) and I don't know how to.
Thanks in advance!!

Réponse acceptée

Alex Mcaulley
Alex Mcaulley le 31 Juil 2019
Try with this:
n = 7;
iter = 1;
seq(1) = n; %where the sequence is stored
while n > 1
if mod(n, 2)==0
n = n/2;
elseif mod(n,2)~=0
n = (3.*n) + 1;
end
iter = iter + 1;
seq(iter) = n;
end
  1 commentaire
Alicia Cuber Caballero
Alicia Cuber Caballero le 31 Juil 2019
Works perfectly! Thank you very much :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by