フィルターのクリア

A for loop that finds multiples of certain numbers in a given range

11 ビュー (過去 30 日間)
Caroline F
Caroline F 2022 年 3 月 7 日
コメント済み: Image Analyst 2022 年 3 月 14 日
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 and save these in a row vector labeled M1. It was suggested that I use mod()/rem() functions. I have been able to do this without a for loop, but when I try to use the for loop the answer is not in row vector form and there are a lot of blank answers.
x = [1:100];
i=1;
for k = 1:length(x)
i=k(mod(k,3)==0)
i=k(mod(k,5)==0)
end
M1=i

採用された回答

David Hill
David Hill 2022 年 3 月 7 日
編集済み: Image Analyst 2022 年 3 月 14 日
y=[];
for k = 1:100
if mod(k,3)==0||mod(k,5)==5
y=[y,k];
end
end
y
y = 1×33
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90
  2 件のコメント
Garrett Viton
Garrett Viton 2022 年 3 月 14 日
This is not giving the multiples of 5 like 10, 20, 25, etc. What's the reasoning on this?
Image Analyst
Image Analyst 2022 年 3 月 14 日
@Garrett Viton, it's because there is an error in the code. See my answer below.

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 3 月 14 日
Try this:
% Construct a list of values to check. Call it x.
x = 1 : 100;
% Initialize our output row vector to null. Then we'll fill it up.
M1=[];
% Now check all the values in x to see if they are a multiple of 3 or 5.
for k = 1 : length(x)
% Get this value of x.
this_x = x(k);
% Check the value to see if it's a multiple of 3 or 5.
if (mod(this_x, 3) == 0) || (mod(this_x, 5) == 0)
% If we get here, this_x is a multiple of 3 or 5.
% Store the value in our output vector.
M1 = [M1, this_x];
end
end
M1
M1 = 1×47
3 5 6 9 10 12 15 18 20 21 24 25 27 30 33 35 36 39 40 42 45 48 50 51 54 55 57 60 63 65

カテゴリ

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

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by