Saving to a vector
古いコメントを表示
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
採用された回答
その他の回答 (1 件)
You can replace
b = i;
with
b = [b i];
to create an array. You will get a warning about it resizing in a loop, but in this case it isn't easy to presize it and unless you are doing it on large numbers and the time taken is unacceptable it isn't worth worrying about. Even if the time taken is excessive it may not be due to the resizing of the array anyway.
You will also likely have to change your penultimate line to
b = isprime(b) .* b;
to work for a vector using point-wise multiplication (note the extra '.')
3 件のコメント
Harel Harel Shattenstein
2015 年 4 月 2 日
編集済み: Harel Harel Shattenstein
2015 年 4 月 2 日
Michael Haderlein
2015 年 4 月 2 日
While preallocation is not easy in this case (as Adam mentioned), you at least need to define the variable. Just add before starting the loop
b=[];
Adam
2015 年 4 月 2 日
Ah yes sorry, I forgot that. It's what comes of answering off the top of my head rather than checking it in Matlab first!
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!