필터 지우기
필터 지우기

for loop and while loop help with Collatz conjecture

조회 수: 4 (최근 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 CenterFile 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