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

8 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops 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