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 日

0 投票

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 件のコメント

sergio mario
sergio mario 2016 年 9 月 18 日
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 2016 年 9 月 18 日
編集済み: Stephen23 2016 年 9 月 18 日
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 2016 年 9 月 18 日
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 2016 年 9 月 18 日
編集済み: Stephen23 2016 年 9 月 18 日
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 2016 年 9 月 18 日
Sorry, I am lost (I am very new to this Matlab program). How will it translate into my code? Thank you
Stephen23
Stephen23 2016 年 9 月 19 日
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 についてさらに検索

質問済み:

2016 年 9 月 18 日

コメント済み:

2016 年 9 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by