Clear Filters
Clear Filters

Vectorize nested loop to increase efficiency

2 views (last 30 days)
V
V on 30 Apr 2015
Edited: James Tursa on 1 May 2015
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 Comment
Chad Greene
Chad Greene on 30 Apr 2015
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?

Sign in to comment.

Answers (1)

James Tursa
James Tursa on 1 May 2015
Edited: James Tursa on 1 May 2015
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;

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!