Is there a way to minimize the number of for loops?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!