フィルターのクリア

vectorize a loop

1 回表示 (過去 30 日間)
Mate 2u
Mate 2u 2012 年 5 月 1 日
Hi there I have the following loop, is there a way to vectorize it?
for i=1:10000
for j=i:10000
s = zeros(size(P));
[lead,lag] = movavg(P,i,j,'e');
s(lead>lag) = 1;
s(lag>lead) = -1;
r = [0; s(1:end-1).*diff(P)-abs(diff(s))*cost];
sh(i,j) = scaling*sharpe(r,0);
end
end
  1 件のコメント
Walter Roberson
Walter Roberson 2012 年 5 月 2 日
Is there a difference between this function and the one you were previously asking about vectorizing?

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

採用された回答

Jan
Jan 2012 年 5 月 2 日
When movavg() is the bottleneck, a vectorization will not be remarkably faster. So please use either the profiler and some tic/toc measurements to find out, where the most time is spent.
Of course the repeated calculation of "diff(P)" should be avoided by using a temporary variable created before the loops. So at first I'd start with a cleaned loop:
s = zeros(size(P));
sh = zeros(10000, 10000); % pre-allocate!!!
diffP = diff(P);
for i=1:10000
for j=i:10000
s(:) = 0; % Faster than zeros()
[lead,lag] = movavg(P,i,j,'e');
s(lead>lag) = 1;
s(lag>lead) = -1;
r = [0; s(1:end-1) .* diffP - abs(diff(s))*cost];
sh(i,j) = scaling*sharpe(r,0);
end
end
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2012 年 5 月 2 日
s = sign(lead - lag);

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

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