MATLAB: Saving to a vector

MATLABvector

function [ b ] = PrimeF( x )
for i=1:x
if mod(x,i)==0
b=i;
end
end
b=isprime(b)*b;
end
I have built a simple function the return the prime factorization of a number. but I can find a way to save them into a vector I called b (that I do not know his size). Thanks

Best Answer

Doing this in a loop and concatenating new values into a vector is very poor use of MATLAB, and will be very slow. It would be much better to learn how to write fully vectorized code, which will be much faster, neater and less buggy. Rather than learning bad coding habits and trying to change them later, you should learn from the very start how to write vectorized code in MATLAB.
Note for example that mod works perfectly for an entire array as an input, so you could perform this calculation all in one go, without any loops. We can also use some basic logical indexing to pick the values that we want:
function v = primefact(x)
y = 1:x;
z = mod(x,y);
z = y(z==0);
v = z(isprime(z));
end
Which we can then test to check that it find all of the prime factors:
>> primefact(7)
ans =
7
>> primefact(10)
ans =
2 5
>> primefact(30)
ans =
2 3 5
>> primefact(42)
ans =
2 3 7
>> primefact(43)
ans =
43
Note that this code excludes one from the output.