Borrar filtros
Borrar filtros

for loop and while loop help with Collatz conjecture

4 visualizaciones (últimos 30 días)
Luke Radcliff
Luke Radcliff el 15 de Jun. de 2016
Respondida: Geoff Hayes el 15 de Jun. de 2016
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.

Respuestas (1)

Geoff Hayes
Geoff Hayes el 15 de Jun. de 2016
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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by