How to optimize this code for running time?

1 次查看(过去 30 天)
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 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by