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

11 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Voss
Voss il 26 Feb 2022
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

Più risposte (1)

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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by