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!