Code Optimization, for loop

1 回表示 (過去 30 日間)
Yusuke Kadowaki
Yusuke Kadowaki 2017 年 9 月 28 日
編集済み: Christoph F. 2017 年 9 月 29 日
Is it possible to make this code faster?
%
RevPSD = zeros(size(X));
for m = Tmin + 1:size(X,2)
for i = Tmin:Tmax
if m - i <= 0
break
else
RevPSD(:,m) = RevPSD(:,m) + exp(-2*delta*i*hop/fs)*(Xpsd(:,m-i));
end
end
end
  2 件のコメント
Christoph F.
Christoph F. 2017 年 9 月 28 日
Two suggestions:
The inner loop only loops from Tmin to (m-1). The extra comparison of m and i inside the loop could be removed if the loop condition is changed, e.g.
for i = Tmin:(m-1)
RevPSD(:,m) = RevPSD(:,m) + exp(-2*delta*i*hop/fs)*(Xpsd(:,m-i));
end
The values of the term
exp(-2*delta*i*hop/fs)
only depend on i can could be pre-calculated for every possibly value of i outside the loop. e.g.
exptable = exp(-2*delta*(Tmin:Tmax)*hop/fs);
for m = Tmin + 1:size(X,2)
for i = Tmin:(m-1)
RevPSD(:,m) = RevPSD(:,m) + exptable(i-Tmin+1)*(Xpsd(:,m-i));
end
end
Jan
Jan 2017 年 9 月 28 日
@Christoph F: Please post this in the answer sections.

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

採用された回答

Christoph F.
Christoph F. 2017 年 9 月 28 日
Two suggestions:
The inner loop only loops from Tmin to (m-1). The extra comparison of m and i inside the loop could be removed if the loop condition is changed, e.g.
for i = Tmin:(m-1)
RevPSD(:,m) = RevPSD(:,m) + exp(-2*delta*i*hop/fs)*(Xpsd(:,m-i));
end
The values of the term
exp(-2*delta*i*hop/fs)
only depend on i can could be pre-calculated for every possibly value of i outside the loop. e.g.
exptable = exp(-2*delta*(Tmin:Tmax)*hop/fs);
for m = Tmin + 1:size(X,2)
for i = Tmin:(m-1)
RevPSD(:,m) = RevPSD(:,m) + exptable(i-Tmin+1)*(Xpsd(:,m-i));
end
end
  2 件のコメント
Yusuke Kadowaki
Yusuke Kadowaki 2017 年 9 月 29 日
Thanks a lot Christoph. The second one worked a bit.
Christoph F.
Christoph F. 2017 年 9 月 29 日
編集済み: Christoph F. 2017 年 9 月 29 日
Looking at the expression more closely, the whole term
exp(-2*delta*i*hop/fs)*(Xpsd(:,m-i))
only depends on m and i. I assume that with some creative thinking, the inner loop could be completely removed and replaced with adding a matrix to RevPSD.
The general idea is to use built-in MatLab matrix/vector functions (add, multiply, sum, etc) instead of loops whenever possible, and not to calculate expressions repeatedly that only need to be calculated once.

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

その他の回答 (0 件)

カテゴリ

Help Center および File Exchangeループと条件付きステートメント についてさらに検索

Community Treasure Hunt

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

Start Hunting!