A time killing loop
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Hi,
I have a loop which is taking ages. I am wondering if someone can make it more efficient.
%%x1 is a vector of date rows for which I need to find the price
for k=1:length(x1)
%%x2 finds the rows in the original data file for each specific date (A is a vector of 6320 dates,ID is the unique identifier of a bond issued by a firm. The first column in data is the column of unique bond identifiers and the second column is a column of dates . Finally,the third column of data is the column of prices )
x2=find(data(:,2)==A(x1(k))&data(:,1)==ID);
%%%IssueMatrix is a matrix of prices; the first column is equal to the date vector A , and then each column refers to the prices of a different bond j issued by a firm.
if isnan(IssueMatrix(x1(k),j+1))==1
%%if I don't have any price on a date A(x1(k) for a specific bond issue then assign a price which is the average price of bonds supplied by different bond dealers.
IssueMatrix(x1(k),j+1)=nanmean(data(x2,3));
else
%%%if I have a price assigned for this bond added it to other prices supplied by dealers and then take the average
IssueMatrix(x1(k),j+1)=nanmean([data(x2,3);IssueMatrix(x1(k),j+1)]);
end
2 comentarios
Jan
el 8 de Sept. de 2011
Please format the posted code and provide some test data, such that we can read and run your code.
Respuestas (3)
joseph Frank
el 8 de Sept. de 2011
3 comentarios
Jan
el 8 de Sept. de 2011
Replace:
ID=UI(j,1); ID2=repmat(ID,size(A));
x1=find(ismember(IM(:,1),unique(D(:,2))) & ismember(ID2,D(:,1)));
by:
x1 = find(ismember(IM(:,1),unique(D(:,2))) & (UI(j)==D(:,1)));
Oleg Komarov
el 8 de Sept. de 2011
This a vectorized way to obtain intersected means, then it's up to you to replicate the matrix anc concatenate as you wish:
% Row subs
[idx,rsub] = ismember(D(:,2),A);
Dmemb = D(idx,:);
rsub = rsub(idx);
% Col subs
[idx,csub] = ismember(Dmemb(:,1),I(:,1));
% Accumarray
out = [unique(Dmemb(:,2)) accumarray([rsub-min(rsub)+1, csub],Dmemb(:,3),[],@mean,NaN)]
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!