I need to display the max value in this function.

4 ビュー (過去 30 日間)
Kevin Smith
Kevin Smith 2017 年 9 月 25 日
コメント済み: Stephen23 2017 年 10 月 23 日
I have been working on a script for a function 'collatz' and I originally made it way more complex than it needed to be. I've managed to simplify it down to this:
function [s,m]=collatz(num)
cnt=0;
m=-inf;
while num>1
cnt=cnt+1;
if mod(num,2);
num=num*3+1;
else
num=num/2;
end
end
The only problem I have is getting 'm' to represent the maximum value. The 's' displays the number of steps it takes to complete the while loop. That part of the script works fine. Example of what I would need: >>[s,m]=collatz(3) %which would take 7 steps in my function with a max value of 16. s= 7 m= 16
  1 件のコメント
Stephen23
Stephen23 2017 年 10 月 23 日
See my answer for a simpler solution.

サインインしてコメントする。

採用された回答

KSSV
KSSV 2017 年 9 月 25 日
function [s,m]=collatz(num)
cnt=0;
X = zeros([],1) ;
while num>1
cnt=cnt+1;
if mod(num,2)
num=num*3+1;
X(cnt) = num ;
else
num=num/2;
X(cnt) = num ;
end
end
m = max(X) ;
fprintf('Maximum values is:%f\n',m)
  1 件のコメント
Kevin Smith
Kevin Smith 2017 年 9 月 25 日
Thanks for your help!

サインインしてコメントする。

その他の回答 (1 件)

Stephen23
Stephen23 2017 年 9 月 25 日
編集済み: Stephen23 2017 年 9 月 25 日
Rather than enlarging the array on each iteration as KSSV showed (and in general is a bad practice that should be avoided), you should simply call max on each iteration, which makes the code simpler too:
function [cnt,mxv] = collatz(num)
cnt = 0;
mxv = 0;
while num>1
cnt = cnt+1;
if mod(num,2) % odd
num = num*3+1;
else % even
num = num/2;
end
mxv = max(mxv,num);
end
end
And tested:
>> [s,m] = collatz(3)
s =
7
m =
16

カテゴリ

Help Center および File ExchangeStatics and Dynamics についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by