Is there a way to minimize the number of for loops?

1 visualización (últimos 30 días)
Sharif Khalil
Sharif Khalil el 18 de Mayo de 2018
Comentada: Ameer Hamza el 18 de Mayo de 2018
f = 3e10; % Operating Frequency
c = 3e8; % Speed of Light
Nx = 10; % Number of Elements x-direction
Ny = 9; % Number of Elements y-direction
wmn = 1; % Weight Vector
thta = -90:90; % Elevation Angle
phi = -180:180; % Azimuth Angle
fi = 1; % Normalized to unity electric field pattern (Directivity)
wi = 1; % Weights (Directivity)
lmda = c/f; % Wavelength
k = 2*pi/lmda;% Wave Number
dx = lmda/2; % Element Spacing x-direction
dy = dx; % Element Spacing y-direction
for ii = 1:length(phi)
for jj = 1:length(thta)
for m = 1:Nx
for n = 1:Ny
AFe(n) = exp(1i*((m-1)*k*dx*sin(thta(jj))*cos(phi(ii))+...
(n-1)*k*dy*sin(thta(jj))*sin(phi(ii))));
end
AFn(m) = wmn*sum(AFe);
end
AF(ii,jj) = abs(sum(AFn));
end
end

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 18 de Mayo de 2018
You can avoid the for loop altogether by vectorization of your code. MATLAB has a very efficient implementation for vector operations. Your speed will increase several times. Here is the vector version of your code, replace all the for loops with this.
[phi_, thta_, nx_, ny_] = ndgrid(phi, thta, 1:Nx, 1:Ny);
step1 = exp(1i*((nx_-1).*k.*dx.*sin(thta_).*cos(phi_)+...
(ny_-1).*k.*dy.*sin(thta_).*sin(phi_)));
step2 = wmn*sum(step1,4);
final = abs(sum(step2, 3));
Speed Comparison: On my machine, it got almost 5x speed gain
Your code:
Elapsed time is 1.840009 seconds.
The vectorized version:
Elapsed time is 0.362373 seconds.
However, this approach will require more memory because of the creation of 4D vectors. This is a trade-off between speed and memory.
  2 comentarios
Sharif Khalil
Sharif Khalil el 18 de Mayo de 2018
Thank you, I will try that
Ameer Hamza
Ameer Hamza el 18 de Mayo de 2018
You are welcome.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by