How do I make my function take vectors as an input?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Steven Lord
le 12 Mar 2018
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 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!