vectorize a loop
1 次查看(过去 30 天)
显示 更早的评论
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
2012-5-2
Is there a difference between this function and the one you were previously asking about vectorizing?
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!