While loop into vector

12 ビュー (過去 30 日間)
St.John Rowell
St.John Rowell 2020 年 4 月 11 日
コメント済み: St.John Rowell 2020 年 4 月 14 日
I'm trying to make this function output into a vector on every loop so it stores the variable numbers into the vector but i'm struggling to do so.
function f = primefactors(m)
p=[]
for x = 2;
while m > 1
if mod (m,x) == 0
m=m/x
fprintf('The Prime factors are: %d\n', x)
else
x = x+1;
fprintf(' ')
end
end
end
  1 件のコメント
Stephen23
Stephen23 2020 年 4 月 11 日
Storing the output is easy, just use indexing to store the values in the output variable, e.g.:
function p = ...
p = []
...
p(end+1) = x;
...
Note that
  • m=m/x is unlikely to be useful.
  • the for loop as you have written it is superfluous and can be replaced with x=2;
  • you need to think about the while loop condition (e.g. consider what happens if m is any prime number), or use a for loop.

サインインしてコメントする。

採用された回答

madhan ravi
madhan ravi 2020 年 4 月 11 日
Example for storing values in a loop:
N = 10;
X = zeros(1,N);
k = 1;
while k <= N
X(k) = k;
k = k + 1;
end
  1 件のコメント
St.John Rowell
St.John Rowell 2020 年 4 月 14 日
I've tried moving my code around thank you. Does this mean k = the vector of outputs?
function f = primefactors(m)
k=zeros(1,m);
x = 1;
while x <= m
if mod (m,x) == 0
m=m/x;
k(x) = x;
x=x+1;
fprintf('The Prime factors are: %d\n', x)
end
end
end

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by