フィルターのクリア

for loop and while loop help with Collatz conjecture

8 ビュー (過去 30 日間)
Luke Radcliff
Luke Radcliff 2016 年 6 月 15 日
回答済み: Geoff Hayes 2016 年 6 月 15 日
Below is code for Collatz conjecture, that given an x value will print out the max number(mx) during the run for that x value and number of iterations(N) it takes to get to 1.
function [N, mx] = prob3_6(x)
% function [N, mx] = prob3_6(x)
% takes a positive integer x and finds number of iterations and maximum
% value along the way
X = x;
N = 0; % initialize interations to zero
mx = x; % initialize maximum value
while X ~= 1
if mod(X,2) % X is odd
X = 3*X+1;
else
X = X/2;
end
N = N+1;
%disp(X)
if X > mx
mx = X;
end
end
I need to run a whole array of x through here like 2:1:100 and get how many iterations(N) it took for each value of x, and the max number of each value of x. I figured for loop around the while loop, like this
function [N, mx] = prob3_6(x)
X = x;
N = 0; % initialize interations to zero
mx = x; % initialize maximum value
for k = 1:length(x)
while X ~= 1
if mod(X,2) % X is odd
X = 3*X+1;
else
X = X/2;
end
N = N+1;
%disp(X)
if X > mx
mx = X;
end
end
end
now where would I have to put k or maybe N or mx to get what I need, been trying different combos not sure how it should go.

回答 (1 件)

Geoff Hayes
Geoff Hayes 2016 年 6 月 15 日
Luke - if x is now an array of elements, then wouldn't you do something like
function [N, mx] = prob3_6(x)
for k=1:length(x)
X = x(k);
N = 0; % initialize interations to zero
mx = x; % initialize maximum value
while X ~= 1
% etc.
end
end
It is really no different than what you had originally when x was a scalar. You just need to realize that it is an array and iterate over each element of it.
What I have omitted (since this is homework) is how you store the mx for each element in x. You will want to create an mx array which is the same dimension as x and then update the kth element of it.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by