How do you make a matrix with alternating numbers in a nested loop?
8 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Voss
on 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);
0 Comments
More Answers (1)
Torsten
on 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)
0 Comments
See Also
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!