フィルターのクリア

How do you make a matrix with alternating numbers in a nested loop?

11 ビュー (過去 30 日間)
Caroline F
Caroline F 2022 年 2 月 26 日
回答済み: Voss 2022 年 2 月 26 日
I am trying to make an alternating 5x5 matrixs of 2s and 3s, starting with 2 on the top left corner, in a nested loop. My professor recommended using rem() or mod() functions to make the pattern, but I'm not really sure how to do that. I have been able to get every other column to have alternating numbers, but not all of them and not with the correct numbers. This is my code so far.
Y=ones(5);
for i = 1:2:(length(Y))
for j = 1:2:(length(Y))
Y(i,j) = mod(i,2).*2
end
end

採用された回答

Voss
Voss 2022 年 2 月 26 日
N = 5;
% start with a matrix of all 3's
% (then the code will place 2's at the appropriate places)
Y = 3*ones(N);
% loop over all rows (in general, every row gets
% a 2 somewhere, not just the odd rows):
for i = 1:N
% determine which column the first 2 goes in:
% odd i: start in column 1 (e.g., row 1 has a 2 in column 1)
% even i: start in column 2 (e.g., row 2 has a 2 in column 2)
start_column = 2-mod(i,2);
% place 2's in each alternate column of row i, starting with
% start_column:
for j = start_column:2:N
Y(i,j) = 2;
end
end
disp(Y);
2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2

その他の回答 (1 件)

Torsten
Torsten 2022 年 2 月 26 日
n = 5;
x = zeros(n^2,1);
x(1:2:end) = 2;
x(2:2:end-1) = 3;
x = reshape(x,n,n)

カテゴリ

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