How do you remove multiples of certain numbers from a row vector?
Show older comments
I am trying to create a for loop that finds all values in the range [1,100] that are also multiple of 3 or 5, but not 3 AND 5, and save these in a row vector labeled M1. It was suggested that I use mod()/rem() functions. I am struggling on how to remove the numbers that are multiples of 3 and 5.
M1=[];
for x = 1:100
if mod(x,3)==0||mod(x,5)==0
M1=[M1,x];
end
if mod(x,3)==0 & mod(x,5)==0
M1(x)=[]
end
end
M1
Accepted Answer
More Answers (1)
You do not need a loop.
n = 100;
x = false(1, n);
x(3:3:n) = true;
x(5:5:n) = true;
x(15:15:n) = false;
Result = find(x)
% Or:
x = 1:100;
Result = x((mod(x, 3) == 0 | mod(x, 5) == 0) & mod(x, 15) ~= 0)
% Shorter:
Result = x(~(mod(x, 3) & mod(x, 5)) & mod(x, 15))
1 Comment
Stephen23
on 16 Mar 2022
+1 very neat
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!