how can i add as x(1) multiple numbers instead of one at a time?

I am working on a list of exercises for my Matlab course at university.I would like some advice on how to achieve what was stated in the question.I am kinda stuck with this part cause matlab pops "In an assignment A(I) = B, the number of elements in B and I must be the same." when i try to add a matrix with a list of numbers.Any suggestions would be welcomed.Here is my current code:
clc;
clear;
x(1)=10;
k=1;
while x(k)~=1
if mod(x(k),2)==0
x(k+1)=x(k)/2;
else
x(k+1)=3*x(k)+1;
end
k=k+1;
disp(x(k));
end

3 Comments

Your code works... Can you be more clear on how you wish to modify it?
my exercise asks for the result using different numbers as x(1).In this example i use number '10' as x(1).Is there a way to add more numbers and generate the result at once?without having to change the x(1) value manually each time?

Sign in to comment.

Answers (2)

This is what is involved in the Collatz conjecture. The conjecture states that no matter what positive integer is used to begin the iteration, it will always end in the number one if carried out sufficiently many times. According to Wikipedia this conjecture has never been proved or disproved.
http://en.wikipedia.org/wiki/Collatz_conjecture
One way you could "test" it would be to create an n-by-2 array in which the first numbers are 1:n and second number gives the number of iterations required to end with 1 for each of these numbers. This code essentially encloses your iteration in a for-loop.
n = 10^6;
M = zeros(n,2);
for m = 1:n
t = m;
k = 1;
while t~=1
if mod(t,2)==0
t = t/2;
else
t = 3*t+1;
end
k = k+1;
end
M(m,:) = [m,k];
end
display(max(M(:,2)))
If your program doesn't hang up, it means you haven't found a counterexample in the first million positive integers.
ty for the feedback.yes the result must always be 1.my problem is that i want to do the same procedure for different x(1).part of the exercise is to collect each of the x(2),x(3),x(4),.... and so on until 1 in a plot.but i need to do this for multiple different x(1),all at the same time without having to re-run the code with different x(1)

Categories

Find more on Signal Processing Toolbox in Help Center and File Exchange

Products

Asked:

tom
on 5 Jun 2013

Community Treasure Hunt

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

Start Hunting!