How do I make my function take vectors as an input?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Steven Lord
el 12 de Mzo. de 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 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!