Speed up nested for loop

2 ビュー (過去 30 日間)
Francesco Lisi
Francesco Lisi 2021 年 5 月 28 日
コメント済み: Jan 2021 年 6 月 1 日
Hi,
I have to speed up the following code.
N is an integer of the order 10^4, l is of the order of (N)^(1/4), c and v are column complex vectors with N elements.
B = 0;
for m = 1:l
for n = m+1 : N
B = B + 2*real(c(n)*conj(v(n))* conj(c(n-m))*v(n-m));
end
end
Thank you for your help.
Francesco
  1 件のコメント
Jan
Jan 2021 年 5 月 28 日
Please provide some inputs values, maybe produced by rand(). It is hard to improve the code without running it. And inveting default inputs might be misleading, if we oversee an important detail.

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

採用された回答

Jan
Jan 2021 年 5 月 28 日
編集済み: Jan 2021 年 5 月 28 日
Maybe:
% [UNTESTED CODE] Please provide inputs for testing
B = 0;
for m = 1:l
B = B + sum(2 * real(c(m+1 : N) .* conj(v(m+1 : N)) .* ...
conj(c(1 : N-m)) .* v(1 : N-m)));
end
Does this work? Then:
B = 0;
c_cv = c .* conj(v);
cc_v = conj(c_cv);
for m = 1:l
B = B + 2 * sum(real(c_cv(m+1 : N) .* cc_v(1 : N-m)));
end
  2 件のコメント
Francesco Lisi
Francesco Lisi 2021 年 6 月 1 日
Thank you Jan for your fast reply!
The code you provided is faster indeed. Here is the updated script
y=c.*conj(v);
yc=conj(y);
B_est = sum(abs(y).^2);
for m = 1:l
B_est = B_est + 2*sum(real(y(m+1:N) .* yc(1:N-m)));
end
Is there a way to speed up this one?
As input you can use complex arrays generated as randn(N,1)+1i*randn(N,1). I use this function in a Monte Carlo simulation with 10^3 iteration and this function is the slowest one.
Thank you again for your help.
Francesco
Jan
Jan 2021 年 6 月 1 日
A further improvement:
c_cv = c .* conj(v);
cc_v = conj(c_cv);
B = 0; % sum(abs(y).^2) did not appear in the original question
for m = 1:l
B = B + real(c_cv(m+1 : N).' * cc_v(1 : N-m));
end
B = B * 2;
Letting the sum() be done by the dot product saves some time, because the optimized BLAS library is used.

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

その他の回答 (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