Loop that I am trying to get rid off
Afficher commentaires plus anciens
To follow up on my previous thread regarding a very time consuming routine, the main source of slowness I believe is the following: Rating agencies such as Moody and Standard and Poors report ratings for bonds outstanding. This rating changes from time to time. So I have in a matrix X0: column 1 is a bond ID Column 2 is the rating beginning date Column 3 is the rating Column 4 is the rating ending date for example for Bond ID 1 I have the following inputs: Ratings=[1 726834 3 728000;1 728000 2 729500;1 729500 3 731000]; then I have a vector date of 20 year daily data so I am running a loop that looks like this for a single bond (I have 15000 bonds):
for i=1:length(date)
x1=find(X0(:,2)<=date(i) & X0(:,4)>date(i));
if isempty(x1)
R(i)=nan;%Rating
else R(i)=X0(x1,3);
end
end
Is there a way to get rid of this loop ?
Réponse acceptée
Plus de réponses (2)
Fangjun Jiang
le 6 Août 2011
I wonder if you can use interp1(). Basically, it is a look up operation, right? It will fill NaNs for dates outside of Ratings. But there should be no gap of dates in Ratings.
Use your own discretion. BTW, don't use 'date' as the variable name. It's a function.
Ratings=[1 726834 3 728000;1 728000 2 729500;1 729500 3 731000];
X=[Ratings(:,2),Ratings(:,4)-1]';
X=X(:);
Y=[Ratings(:,3),Ratings(:,3)]';
Y=Y(:);
Dates=726830:731005;
R=interp1(X,Y,Dates,'nearest');
1 commentaire
Oleg Komarov
le 6 Août 2011
I like your approach, more comprehensible.
Daniel Shub
le 6 Août 2011
0 votes
Loops in MATLAB are much faster nowadays then they used to be. Without timing solutions, it is not always obvious what way is fastest. Sometimes you just want to get to fast enough.
It looks to me like you could loop over the rows of X0 instead of the dates.
Catégories
En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!