MATLAB: Reducing the time is takes to calculate a large 3D matrix

cell arraysmatrix

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

Best Answer

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.