How do I make my function take vectors as an input?
조회 수: 1 (최근 30일)
이전 댓글 표시
I was trying to make a function which finds the amount of iterations it will take for any given number to get to 1 in the collatz conjecture. I found that my code works for scalar inputs, but when I use a vector as an input it only gives me the output for the last element of the vector. Any help would be greatly appreciated.
function [count]=updown(numbers)
for i=1:numel(numbers)
count=0;
x(i)=numbers(i);
while x>1
if rem(x,2)==0
x=x./2;
else
x=3*x+1;
end
count=count+1;
end
end
count
end
댓글 수: 0
답변 (1개)
Steven Lord
2018년 3월 12일
You want an array of counts, one per element of the array that you pass in as input? Preallocate that array using the zeros and size functions then assign into and add to the appropriate element of that array while you're operating on each element of the input array.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!