vectorize a loop

1 view (last 30 days)
Mate 2u
Mate 2u on 1 May 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 Comment
Walter Roberson
Walter Roberson on 2 May 2012
Is there a difference between this function and the one you were previously asking about vectorizing?

Sign in to comment.

Accepted Answer

Jan
Jan on 2 May 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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!