Borrar filtros
Borrar filtros

How to vectorize this nested for loop?

4 visualizaciones (últimos 30 días)
Awanish
Awanish el 2 de Mzo. de 2024
Respondida: Dyuman Joshi el 2 de Mzo. de 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

Respuesta aceptada

Dyuman Joshi
Dyuman Joshi el 2 de Mzo. de 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
pair = 3×2
-1 1 0 0 1 -1
%Vectorized approach
[n,m] = meshgrid(-min1:max1)
n = 3×3
-1 0 1 -1 0 1 -1 0 1
m = 3×3
-1 -1 -1 0 0 0 1 1 1
idx = n+m==b
idx = 3×3 logical array
0 0 1 0 1 0 1 0 0
out = [n(idx) m(idx)]
out = 3×2
-1 1 0 0 1 -1

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by