MATLAB Answers

Building vector with for- and if statements

2 views (last 30 days)
Henry Eriksson
Henry Eriksson on 30 Mar 2017
Commented: Henry Eriksson on 2 Apr 2017
My goal is to find all divisors of 30 and put them in a vector. My code right now looks like:
k=[];
c=[1:1:30];
for i=1:30
if mod(30,c(i))==0
v=[c(i)]
end
end
I am successful in finding the divisors of 30, but the output is:
v =
1
v =
2
v =
3
v =
5
and so on...
I want to put all of the divisors in one single vector v, what am I missing? I have tried searching for answers but I could not find any, maybe because I don't understand MATLAB code well enough.
Thank you for your help!

Answers (1)

Roger Stafford
Roger Stafford on 30 Mar 2017
Edited: Stephen Cobeldick on 2 Apr 2017
Make two changes:
k = 0;
c = 1:1:30;
for i=1:30
if mod(30,c(i))==0
k = k+1;
v(k) = c(i);
end
end
However, it is better practice to first allocate memory to v:
k = 0;
c = 1:1:30;
v = zeros(size(c));
for i=1:30
if mod(30,c(i))==0
k = k+1;
v(k) = c(i);
end
end
v = v(1:k);
Also you can probably make it faster:
c = 1:30;
v = c(mod(30,c)==0);
  3 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!