How do you make a matrix with alternating numbers in a nested loop?
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (1)
Torsten
le 26 Fév 2022
n = 5;
x = zeros(n^2,1);
x(1:2:end) = 2;
x(2:2:end-1) = 3;
x = reshape(x,n,n)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!