How do I make my function take vectors as an input?

1 回表示 (過去 30 日間)
Bobby Bowes
Bobby Bowes 2018 年 3 月 12 日
回答済み: Steven Lord 2018 年 3 月 12 日
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

回答 (1 件)

Steven Lord
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.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by