MATLAB: Vectorize a loop

arrayloopvectorize

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

Best Answer

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