How to avoid using a loop here?
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
sznailc
le 19 Oct 2021
Réponse apportée : Star Strider
le 19 Oct 2021
Hello. I want to do the same thing without a loop.
A = zeros(N);
for m = 1:N
for n = 1:N
A(m, n) = 2*N + 1 - (m + n);
end
end
0 commentaires
Réponse acceptée
Star Strider
le 19 Oct 2021
One approach —
N = 5;
tic
[m,n] = ndgrid(1:N);
A = 2*N + 1 - (m + n)
toc
Compare —
tic
A = zeros(N);
for m = 1:N
for n = 1:N
A(m, n) = 2*N + 1 - (m + n);
end
end
toc
A
The nested loops are actually faster!
.
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!