2

I have a matrix A with dimensions 15NxM. That is, it consists of N different 15xM matrixes stacked on top of each other.

I also have a vector B with dimension 1x15.

What I would really like to do is to perform simple matrix multiplication B*A(Block) on each of the N blocks in A, so that I end up with a NxM matrix.

I need to do this without making any loops, because the main reason I am doing this is to gain some speed.

Thanks.

BLaursen
  • 123
  • 4
  • 1
    Take a look at this stackoverflow [question](http://stackoverflow.com/questions/1745299/multiply-a-3d-matrix-with-a-2d-matrix). – user2482876 Jul 09 '13 at 15:20

2 Answers2

2

You could try

result = reshape( B * reshape(A, 15, []), N, M);

This avoids ever creating the intermediate "repmat" copy of B; but reshape can be slow.

Floris
  • 45,857
  • 6
  • 70
  • 122
0

You could convert your A matrix into a cell array. First you are going to want to create an N-element array of your matrix dimension (15) for specifying the sizes of your cells:

dimArray = repmat(15, 1, N);    % 1xN array of the number 15

Next you will call mat2cell on your matrix A to convert it into a cell array where each cell is a 15xM submatrix of A:

newA = mat2cell(A, dimArray);

Finally, call cellfun on the cell array to do your multiplication:

result = cellfun(@(x) B*x, newA, 'UniformOutput', false);

Which should give you a cell array result containing the result of B*A(block) for each block in your A matrix. You can probably put this all in one line, or at most two:

result = cellfun(@(x) B*x, mat2cell(A, repmat(15, 1, N)), 'UniformOutput', false);

Not the clearest code to read though. This seems like a somewhat round-about way of doing it. If somebody gets it to work with repmat or similar then that might be the better way to go.

Engineero
  • 12,340
  • 5
  • 53
  • 75
  • Since `B` is a row vector, I don't think you need the transpose in your `(x) B.'*x` - I think correct form would start `cellfun(@(x)B*x`. When I tried this, I needed to set `uniformoutput` to `false`, then convert the resulting cell array. Seems unnecessarily complex? – Floris Jul 09 '13 at 15:58
  • Yeah, it does seem a little over-complicated. And I must have read the dimensions wrong for `B`, thanks for pointing that out. Changed now. – Engineero Jul 09 '13 at 16:00
  • In what version of matlab don't you need the `@` before the `(x)`? That is the other error I tried to point out... – Floris Jul 09 '13 at 16:02
  • Oh, sorry, I totally missed the @. Updated accordingly. – Engineero Jul 10 '13 at 00:45