Effacer les filtres
Effacer les filtres

How to optimize this code for running time?

2 vues (au cours des 30 derniers jours)
MENGZE WU
MENGZE WU le 1 Mar 2023
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 commentaire
Walter Roberson
Walter Roberson le 1 Mar 2023
Step 1:
Remove the clear all .

Connectez-vous pour commenter.

Réponses (1)

Walter Roberson
Walter Roberson le 1 Mar 2023
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 commentaire
Walter Roberson
Walter Roberson le 1 Mar 2023
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.

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by