필터 지우기
필터 지우기

Vectorize nested loop to increase efficiency

조회 수: 2 (최근 30일)
V
V 2015년 4월 30일
편집: James Tursa 2015년 5월 1일
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