How to extract all the values from a while loop into a vector
1 次查看(过去 30 天)
显示 更早的评论
I have the following function
function c = nice(n)
c = n
while c ~= 1
if rem(c,2) == 0
c = c/2
else c = 3*c+1
end
end
and I am trying to insert all the c values into one vector. Any hints on how can I do it?
0 个评论
采纳的回答
Mischa Kim
2014-4-28
编辑:Mischa Kim
2014-4-28
AC, use something like
function c = nice(n)
ii = 1;
c(ii) = n;
while c(ii) ~= 1
ii = ii + 1;
if rem(c(ii-1),2) == 0
c(ii) = c(ii-1)/2;
else
c(ii) = 3*c(ii-1) + 1;
end
end
end
0 个评论
更多回答(1 个)
Andrei Bobrov
2014-4-28
编辑:Andrei Bobrov
2014-4-28
function c = nice(n)
c = n;
jj = 0;
while c(end) ~= 1
if rem(c(end),2) == 0
h = c(end)/2;
else
h = 3*c(end)+1;
end
c = [c;h];
jj = jj + 1;
if jj >= 30, break; end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!