How to optimize this code for running time?

조회 수: 2 (최근 30일)
MENGZE WU
MENGZE WU 2023년 3월 1일
댓글: Walter Roberson 2023년 3월 1일
The first for loop in this code runs really slow, is there a way to optimize it? Thanks for any help.
clear all
M = 500;
fs = 1e6;
f = logspace(0,6,fs);
z = exp(j*2*pi*f/fs);
HcoI3 = 0;
HcoI3_DC = 0;
for l = 1:M
HcoI3 = HcoI3 + (M-l+2)*(M-l+1)/2*z.^(-(l-1));
end
for l = 1:M
HcoI3_DC = HcoI3_DC + (M-l+2)*(M-l+1)/2*1^(-(l-1));
end
HcoI3 = 1/HcoI3_DC * HcoI3;
HcoI3_mag = 20*log10(abs(HcoI3));
plot(f, HcoI3_mag)
xlim([1 10e3])
ylim([-60 0])

답변 (1개)

Walter Roberson
Walter Roberson 2023년 3월 1일
HcoI3_DC = HcoI3_DC + (M-l+2)*(M-l+1)/2*1^(-(l-1));
When l is finite, then 1^(-(l-1)) is going to be 1, even if -(l-1) is negative or positive or fractional or complex or 0. The only time it would not be 1 is if... huh, after testing even 1^-inf is 1, so the only time you would get something other than 1 is if l is nan.
When you have a calculation whose value is fully predictable, you can increase performance by substituting the constant value for the calculation.
  댓글 수: 1
Walter Roberson
Walter Roberson 2023년 3월 1일
If you have more than 4 gigabytes of memory (would probably take 8 gigabytes in practice),
l = (1 : M) .';
HcoI3 = sum((M-l+2) .* (M-l+1)/2 .* z.^(-(l-1)), 1);
without a loop.
Here z is a row vector and l is a column vector, and you take advantage of implicit expansion.
If you do not have enough memory, then you can proceed in batches, such as quarters of l at a time, and add the parts together.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Surrogate Optimization에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by