How to find multiples of 3 in a vector using a for loop?

Hello all, I am trying to use a for loop to find the multiples of 3 in a random vector of size (20,1) and then assign these values to a new column vector. I am new to using for loops and am searching for guidance. I currently have this
X = rand(20,1);
i = 1;
for t = 1:length(X)
i = t(mod(t,3)==0)
end
T4 = i
I am not sure if this is even close, but any feedback would be greatly appreciated!
Thank you

2 Comments

rand() returns floating point numbers in the range 0 to 1 (excluding 0 and excluding 1), and those will never be multiples of 3. Consider using randi() instead.
You are correct! thank you very much

Sign in to comment.

Answers (2)

You can use the general outline:
initialize output to be empty
loop over individual members of the input
test if the individual member meets some condition
if it does, add the individual member to the end of the output
end of loop
Hi,
there is no need to use a for loop to achieve what you want. If you want to understand for loops use them, but here is a smarter way:
x = randi(15,20,1)
y = x(mod(x,3)==0)
Best regards
Stephan

2 Comments

Looks like it is a homework assignment to me, in which case using a "for" loop is probably mandatory.
Yes, a for loop is surely indicated. Nevertheless, it is always good to see the other side, to learn where you want to go in the future as MATLAB skills grow.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 14 Oct 2018

Commented:

on 14 Oct 2018

Community Treasure Hunt

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

Start Hunting!