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

### Sharif Khalil (view profile)

on 18 May 2018
Latest activity Commented on by Ameer Hamza

on 18 May 2018

### Ameer Hamza (view profile)

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

### Ameer Hamza (view profile)

on 18 May 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
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.

Sharif Khalil

### Sharif Khalil (view profile)

on 18 May 2018
Thank you, I will try that
Ameer Hamza

on 18 May 2018
You are welcome.