Get while loop answer as a vector

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

 采纳的回答

Stephen23
Stephen23 2016-9-18
编辑:Stephen23 2016-9-18
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 个评论

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.
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
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
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.
Sorry, I am lost (I am very new to this Matlab program). How will it translate into my code? Thank you
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

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by