MATLAB Answers


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

Asked by Sharif Khalil on 18 May 2018 at 15:57
Latest activity Commented on by Ameer Hamza
on 18 May 2018 at 20:19
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))+...
            AFn(m) = wmn*sum(AFe);
        AF(ii,jj) = abs(sum(AFn));


Sign in to comment.

1 Answer

Answer by Ameer Hamza
on 18 May 2018 at 18:59
 Accepted Answer

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_)+...
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.


Thank you, I will try that

You are welcome.

Sign in to comment.

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today