How to vectorize this nested for loop?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Awanish
le 2 Mar 2024
Réponse apportée : Dyuman Joshi
le 2 Mar 2024
Hi everyone, I want to vectorize this nested for loop with an 'if' condition. Could you please let me know how to get it done?
b=0;
pair = [];
min1 = 1;
max1 = 1;
for n = -min1:max1
for m = -min1:max1
if n+m == b
pair = [pair;n,m];
end
end
end
0 commentaires
Réponse acceptée
Dyuman Joshi
le 2 Mar 2024
%Original Approach
b=0;
min1 = 1;
max1 = 1;
pair = [];
for n = -min1:max1
for m = -min1:max1
if n+m == b
pair = [pair;n,m];
end
end
end
pair
%Vectorized approach
[n,m] = meshgrid(-min1:max1)
idx = n+m==b
out = [n(idx) m(idx)]
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!