vectorize a loop

1 Ansicht (letzte 30 Tage)
Mate 2u
Mate 2u am 1 Mai 2012
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 Kommentar
Walter Roberson
Walter Roberson am 2 Mai 2012
Is there a difference between this function and the one you were previously asking about vectorizing?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 2 Mai 2012
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 Kommentar
Andrei Bobrov
Andrei Bobrov am 2 Mai 2012
s = sign(lead - lag);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by