Increase efficiency on nested loops
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
V
am 30 Apr. 2015
Bearbeitet: James Tursa
am 30 Apr. 2015
I have a loop that looks like:
for t=1:size(datesdaily1,1)
for i=1:size(secids,1)
for j=1:size(secids,1)
if not(isnan(weig1(t,i)*weig1(t,j)*rho(i,j)*sqrt(Rates(t,i)*Rates(t,j))))
numerator=numerator + weig1(t,i)*weig1(t,j)*rho(i,j)*sqrt(Rates(t,i)*Rates(t,j));
denominator=denominator+ weig1(t,i)*weig1(t,j)*(1-rho(i,j))*sqrt(Rates(t,i)*Rates(t,j));
end
end
end
end
It takes a lot of time to run... is there anyway to increase efficiency? (maybe avoiding loops?)
Thanks, V
0 Kommentare
Akzeptierte Antwort
James Tursa
am 30 Apr. 2015
Bearbeitet: James Tursa
am 30 Apr. 2015
This gets the inner loops vectorized (gets about a 100x speed improvement on my machine):
rho1 = 1 - rho;
for t=1:size(datesdaily1,1)
w = weig1(t,:) .* sqrt(Rates(t,:));
x = w.' * w;
y = x .* rho;
z = x .* rho1;
numerator = numerator + sum(y(~isnan(y)));
denominator = denominator + sum(z(~isnan(z)));
end
Could potentially vectorize the outer loop as well, but may run into memory issues if the variable sizes are large. What are your variable sizes?
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!