Reducing the time is takes to calculate a large 3D matrix?
1 次查看(过去 30 天)
显示 更早的评论
I'm trying to populate a 3d matrix with profit and loss values for cells defined ccs, cp and woy which are unique entries of my original data currencyPair, counterpartyAlias and weekofYear cells respectively. Unfortunately, length of ccs is 117, cp is 1380 and woy is 25 so the matrix takes a couple of days to calculate. However, the majority of rows and columns are zeros because most counterparties only deal across selective currency pairs. Is there a way to populate the matrix without calculating the zero entries? I tried concatenating the ccs and cp cells before looking for the unique entries but then I have nothing to use a strcmp against. Any ideas would be greatly appreciated!
PnL_CCSvsCP = zeros(length(ccs),length(cp),length(woy));
for i=1:length(ccs)
for j=1:length(cp)
for k=1:length(woy)
PnL_CCSvsCP(i,j,k) = sum(PnL(strcmp(currencyPair,ccs{i}) & ...
strcmp(counterpartyAlias,cp{j}) & ...
(weekofYear == woy(k))));
end
end
end
0 个评论
采纳的回答
Jan
2013-7-22
编辑:Jan
2013-7-22
PnL_CCSvsCP = zeros(length(ccs), length(cp), length(woy));
for i=1:length(ccs)
m1 = strcmp(currencyPair, ccs{i});
for j=1:length(cp)
m2 = m1 & strcmp(counterpartyAlias,cp{j});
for k=1:length(woy)
PnL_CCSvsCP(i,j,k) = sum(PnL(m2 & (weekofYear == woy(k))));
end
end
end
Resorting the loops might help also, such that the longer loops are moved to inside:
m_cp = false(numel(counterpartyAlias), numel(cp)); % Or transposed?
for j = 1:length(cp)
m_cp(:, j) = strcmp(counterpartyAlias, cp{j});
end
PnL_CCSvsCP = zeros(length(ccs),length(cp),length(woy));
for k=1:length(woy)
m_woy = (weekofYear == woy(k));
for i=1:length(ccs)
m_ccs_woy = strcmp(currencyPair, ccs{i}) & m_woy;
for j = 1:length(cp)
PnL_CCSvsCP(i,j,k) = sum(PnL(m_ccs_woy & m_cp(:, j));
end
end
end
And now you can try to replace the innermost loop by a BSFXUN call.
3 个评论
Jan
2013-7-22
编辑:Jan
2013-7-22
I do not understand your question. Of course the modified code does exactly what your code does. But I tried to reduce the number of repeated calculations. In the 2nd method e.g. the string comparison with cp is done 25 instead of 4036500 times as in your original version. This should reduce the runtime remarkably. Did you test this already?
Without having any test data, improvements are based on some guessing. Further improvements are possible, when you give us a hint, whether the current suggestions are working at all. Notice that I've guessed e.g. the orientation of the cell strings etc.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!