1

I attempted to use the solution from this post: Multiply a 3D matrix with a 2D matrix, to vectorize the multiplication of a one dimensional with a three dimensional, but to no avail. Any help would be greatly appreciated!

for s = 1: s_length
   for a = 1: a_length
      for g = g_length
         two_dim(s,a) = two_dim(s,a) + one_dim(g) * three_dim(s,a,g); 
      end
   end
end
Community
  • 1
  • 1
NumenorForLife
  • 1,736
  • 8
  • 27
  • 55

2 Answers2

2

I think this does what you want.

two_dim = reshape(three_dim, [], size(three_dim,3))*one_dim(:);
two_dim = reshape(two_dim, size(three_dim,1), size(three_dim,2));

This works as follows:

  • First line reshapes your 3D array into a matrix, collapsing the first two dimensions into one. That way the operation you want is standard multiplication of the resulting matrix times a column vector.
  • Second line reshapes the result into matrix shape.
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • This could be a simpler way to put it - `reshape(reshape(three_dim,[],g_length)*one_dim,s_length,[])`? Maybe not that easy to explain though. – Divakar Nov 26 '14 at 13:51
  • @Divakar Yes... it's just that I wanted to get rid of those variables, to show they are not needed. But yes, if the OP needs those variables anyway, your version is easier to read – Luis Mendo Nov 26 '14 at 13:52
1

mtimes does not work with inputs with dimension larger than 2, so you have to find a way to do the multiplication by yourself. The solution of Luis Mendo is a nice solution; here is another one using bsxfun:

two_dim = two_dim + squeeze(sum(bsxfun(@times, three_dim, reshape(one_dim,[1 1 g_length])),3));

Here is how it works:

  • reshape makes the vector one_dim looking like a 3D array. This must be done because the multiplication between the vector and the 3D array is performed along the 3rd dimension, so Matlab need a hint on sizes.
  • bsxfun perfoms the element-wise multiplcation, so the result must be sumed up along the 3rd dimension (and squeezed to be compliant with a 2D matrix format)
Bentoy13
  • 4,886
  • 1
  • 20
  • 33