Building vector with for- and if statements

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!

답변 (1개)

Roger Stafford
Roger Stafford 2017년 3월 30일
편집: Stephen23 2017년 4월 2일

0 개 추천

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

Thank you for your quick answer! I'm curious about one thing...
What exactly does k=k+1 do? It seems to appear out of nowhere. My guess is that its counting how many entries of c that are divisors of 30 for example, but how does it do that? Is there anywhere I can read about it? Assuming I am right of course.
Stephen23
Stephen23 2017년 4월 2일
편집: Stephen23 2017년 4월 2일
@Henry Erikson: the k value is defined to have to value one; each time there is a valid output its value increments by one, giving 1, 2, 3, etc. This value is used as an index to allocate the output value into the array v.
"but how does it do that? Is there anywhere I can read about it?"
This is not some MATLAB magic, but a very basic usage of loops which could be used in almost any language which has loops. Some introductory courses to programming might explain this: search for "loop variable" or the like.
Very helpful, thank you! :)

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2017년 3월 30일

댓글:

2017년 4월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by