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

1 回表示 (過去 30 日間)
Sharif Khalil
Sharif Khalil 2018 年 5 月 18 日
コメント済み: Ameer Hamza 2018 年 5 月 18 日
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
Ameer Hamza 2018 年 5 月 18 日
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 件のコメント
Sharif Khalil
Sharif Khalil 2018 年 5 月 18 日
Thank you, I will try that
Ameer Hamza
Ameer Hamza 2018 年 5 月 18 日
You are welcome.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by