Vectorize nested loop to increase efficiency

2 次查看(过去 30 天)
Hi, I have a 3 for loops and I would like if possible to vectorize the two inner loops.
for t=1:size(datesdaily1)
for i=1:size(secids,1)
sum=0;
if inc(t,i)==1
for j=1:size(secids,1)
if inc(t,j)==1
sum=sum+weig1(t,j)*sqrt(Rates(t,j))*rhoneutral(i,j);
end
end
b(t,i)=sqrt(Rates(t,i))*sum/MRates(t,1);
end
end
end
Any idea on how to accomplish that? Here 'weig', 'inc' and 'Rates' are (size(datesdaily1) by size(secids,1)) matrixes, rhoneutral is a (size(secids,1) by size(secids,1)) matrix.
Thanks
  1 个评论
Chad Greene
Chad Greene 2015-4-30
A few notes:
1. Make a habit of not using i or j as variables. They are the built-in imaginary unit. Overwriting them works, but can occasionally errors that are tough to debug.
2. Don't use sum as the name of a variable for a similar reason. It's a built-in function.
At the top of your example can you create some dummy variables that we can use to run your code? For example, this could be accomplished by
Rates = rand(10,30);
if Rates is a 10x30 matrix.
What's the goal of the code above? Can you describe the calculation you're trying to perform?

请先登录,再进行评论。

回答(1 个)

James Tursa
James Tursa 2015-5-1
编辑:James Tursa 2015-5-1
I am guessing a bit on some of the dimensions, but try this as a vectorized alternative. Speed improvement is going to depend on the actual sizes involved and how many of those inc values are 1, but I am getting 1000x or so improvement on my machine with large sizes and a large percentage of 1's in inc. For a small percentage of 1's in inc the speed improvement will be somewhat less than that.
sr = (inc == 1) .* sqrt(Rates);
wr = weig1 .* sr;
mr = bsxfun(@rdivide,sr,MRates(:,1));
wrt = wr * rhoneutral.';
b = mr .* wrt;

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by