A time killing loop
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Jan
2011-9-8
Please format the posted code and provide some test data, such that we can read and run your code.
回答(3 个)
joseph Frank
2011-9-8
3 个评论
Jan
2011-9-8
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
2011-9-8
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!