How can I graph all the values of n in the while loop ? Theres my program.

1 次查看(过去 30 天)
n=input('Enter a natural number');
cont=1:1:n;
while n>1
if rem(n,2)==0
n=n/2;
elseif rem(n,2)~=0
n=n*3+1;
end
plot(cont,n,'--rs');
end

回答(1 个)

Mischa Kim
Mischa Kim 2016-10-28
编辑:Mischa Kim 2016-10-28
Something like this? Not quite sure what you want your x-axis to be.
n = input('Enter a natural number');
cont=1:1:n;
ii = 0;
while n>1
ii = ii + 1;
if rem(n(ii),2)==0
n(ii+1) = n(ii)/2;
elseif rem(n(ii),2)~=0
n(ii+1) = n(ii)*3+1;
end
end
plot(ii,n,'--rs');
  4 个评论
jonathan garcia
jonathan garcia 2016-10-28
% i used hold on and in the plot only appears the points because hold on is used to unite different % plots in one, so i guess that im unable to create a line to connect the points.
n=input('Enter a natural number');
cont=1;
while n>=1
plot(cont,n,'rs','LineWidth',2,'MarkerSize',10);
if n==1
n=1;break
elseif rem(n,2)==0
n=n/2;
elseif rem(n,2)~=0
n=n*3+1;
end
hold on cont=cont+1; end
Mischa Kim
Mischa Kim 2016-10-28
jonathan, have you checked out/run the code that I posted above?
My second post contains another way of plotting the data you might want to try.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by