How do you form a while function using a function file and then using the function file to form a sequence by performing this operation?

How do you form a while function using a function file and then using the function file to form a sequence by performing this operation?
I have this function:
function[v]=collatz(n)
%remainder is 0 when even number is divided by 2
if rem(n,2)==0
v=n/2;
else
v=3*n+1;
end
end
and I need to use a while function to find out the values for if n starts at n=9 and ends at n=1. How do I do this?

 채택된 답변

Jan
Jan 2019년 11월 23일
편집: Jan 2019년 11월 23일
Change n directly and collect the output in the vector v by inserting it at the index end+1:
function v = collatz(n)
v = n;
while n ~= 1
if rem(n, 2) == 0
n = n / 2;
else
n = 3 * n + 1;
end
v(end + 1) = n;
end
end

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Argument Definitions에 대해 자세히 알아보기

질문:

2019년 11월 23일

편집:

Jan
2019년 11월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by