How do you make a matrix with alternating numbers in a nested loop?
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
Accepted Answer
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)
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!