Tips on efficient computation of products of matrix arrays

Hi,

I often run into the need to compute a 2d matrix with a 3d array. That is, assume A is [m x n] , B is [n x o x p] and I need to compute C(:,:,j)=A*B(:,:,j) . Currently, I simply run a for loop (as p is dimension of parameters in a DSGE model and hence not so large), i.e. the minimal matlab code looks like

for j=1:size(B,3)
  C(:,:,j) = A*B(:,:,j);
end

Is there a more efficient way/trick to do so?

Dear @wmutschl,

You can rewrite the loop as a one-liner:

C = reshape(A*reshape(B, n, o*p), m, o, p);

You probably should verify that it is more efficient, this I am not 100% sure (it probably depends on whether each call to reshape allocates a new matrix).

Also note that in the loop version, you should pre-allocate the C matrix before the loop, in order to avoid a costly resize at each iteration:

C = NaN(m, o, p);

Thanks, that’s what I was looking for :slight_smile: