Improving the performance of a for loop in Matlab

1 回表示 (過去 30 日間)
Yodish
Yodish 2017 年 7 月 19 日
編集済み: Yodish 2017 年 7 月 20 日
Hello,
I am trying to improve the speed of the following for loop in Matlab. As it is now is incredibly slow. Maybe vectorizing? But one vector slides on the other and constantly changes.
for m = 1:size(phi,1) - (constant)/2
phi(m) = phi(m).*(mean(conj(phi(1+m:(constant)/2+m))));
end
Thanks!
  2 件のコメント
dpb
dpb 2017 年 7 月 19 日
What are phi and constant? Is phi actually complex; and even if so,
mean(conj(x)) --> conj(mean(x))
so can be outside the loop.
Yodish
Yodish 2017 年 7 月 20 日
Hi and thanks for the answer. phi would be a complex vector whereas constant is a constant number (of elements) < than the length of the aforementioned vector phi
Michele

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

採用された回答

David Goodmanson
David Goodmanson 2017 年 7 月 20 日
編集済み: David Goodmanson 2017 年 7 月 20 日
Hello Yodish,
'one vector slides on the other'. This is basically convolution, and since you are finding a mean it is convolution with a vector of ones, of length constant/2. Since the code is not iterative, all the means can be found first.
N = 10000;
constant = 5000;
phi_orig = rand(1,N)+i*rand(1,N);
tic % first way
phi = phi_orig;
for m = 1:length(phi) - (constant)/2
phi(m) = phi(m).*(mean(conj(phi(1+m:(constant)/2+m))));
end
toc
tic % second way
phi2 = phi_orig;
c2 = constant/2;
A = conv(phi2,ones(1,c2),'valid')/c2; % means
A(1) = [];
sA = length(A);
phi2(1:sA) = phi2(1:sA).*conj(A);
toc
d = max(abs(phi2-phi)) % should be zero
In your code I used length(phi) rather than size(phi,1) so that phi could be either a row vector or a column vector.
  1 件のコメント
Yodish
Yodish 2017 年 7 月 20 日
編集済み: Yodish 2017 年 7 月 20 日
Yes thanks, it is indeed a convolution. It would also work with the movmean function. They both improve speed by a factor of 100.
Thanks for your precious help guys

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

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