how can i add as x(1) multiple numbers instead of one at a time?
Show older comments
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
Azzi Abdelmalek
on 5 Jun 2013
What is the problem?
Kye Taylor
on 5 Jun 2013
Your code works... Can you be more clear on how you wish to modify it?
tom
on 5 Jun 2013
Answers (2)
Roger Stafford
on 5 Jun 2013
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.
tom
on 5 Jun 2013
0 votes
Categories
Find more on Signal Processing Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!