While loop code is below. The answer I get for n=6 is n=6, n=3, n=10, etc. However, I want those answers to be listed as a vector so I can get its length. Thank you
while n>1
if mod(n,2)==0
n=n/2
else
n=3*n+1
end
end

 Respuesta aceptada

Stephen23
Stephen23 el 18 de Sept. de 2016
Editada: Stephen23 el 18 de Sept. de 2016
n = 12;
while n>1
if mod(n(end),2)==0
n(end+1)=n(end)/2;
else
n(end+1)=3*n(end)+1;
end
end
creates this vector:
>> n
n =
12 6 3 10 5 16 8 4 2 1
Note that this is not a very good way to write MATLAB code, because it expands the array in each loop iteration (clearly highlighted with a warning in the MATLAB editor!):

6 comentarios

sergio mario
sergio mario el 18 de Sept. de 2016
the only problem is that if I do length(n), it will give me an index error. And if I write n(1) to find first value of n, it gives me nothing.
Stephen23
Stephen23 el 18 de Sept. de 2016
Editada: Stephen23 el 18 de Sept. de 2016
It sounds like you have defined a variable named length, which thus makes the inbuilt length function inaccessible: this is known as shadowing the inbuilt function. clear all to remove the variables that you have defined, and make sure that you never name any variable length, or size, cell, i, j, etc, etc. You should use which to check if a name is already used.
If you want to know how many elements n has, use numel:
>> numel(n)
ans =
10
sergio mario
sergio mario el 18 de Sept. de 2016
Thank you very much! But now with that sequence that I've created above in the initial question, how do I find which value of "n" gives the maximum number of "numel(n)" from integers of 1 to 1000? Thank you
Stephen23
Stephen23 el 18 de Sept. de 2016
Editada: Stephen23 el 18 de Sept. de 2016
Initialize two variables (value=zero): one for the length, and one for the number. Put your code inside a for loop, iterate over the range of numbers that you want to check. If the length is greater than the stored length then store the current length and the number in those variables. Done.
If my answer solved your original question, please accept it by clicking the Accept button. This is a very easy way for you to say thank you to the volunteers who help you.
sergio mario
sergio mario el 18 de Sept. de 2016
Sorry, I am lost (I am very new to this Matlab program). How will it translate into my code? Thank you
Stephen23
Stephen23 el 19 de Sept. de 2016
mxl = 0;
vec = 0;
for n = 1:1000
while n>1
if mod(n(end),2)==0
n(end+1)=n(end)/2;
else
n(end+1)=3*n(end)+1;
end
end
if numel(n)>mxl
mxl = numel(n);
vec = n;
end
end

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 18 de Sept. de 2016

Comentada:

el 19 de Sept. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by