Multiply 2D Matrix with vector to span third dimen

2019-01-28 13:23发布

As I am trying to multiply a m x n Matrix with a p-dimensional vector, I am stumbling across some difficulties.

Trying to avoid for loops, here is what I am looking to achieve

enter code here
M = [1 2 3;                   p = [1;2;3]
     4 5 6;
     7 8 9]

I want to obtain a 3x3x3 matrix, where the slices in third dimension are simply the entries of M multiplied by the respective entry in p.

Help is much appreciated

1条回答
小情绪 Triste *
2楼-- · 2019-01-28 13:56

You can use bsxfun with permute for a vectorized (no-loop) approach like so -

out = bsxfun(@times,M,permute(p(:),[3 2 1]))

You would end up with -

out(:,:,1) =
     1     2     3
     4     5     6
     7     8     9
out(:,:,2) =
     2     4     6
     8    10    12
    14    16    18
out(:,:,3) =
     3     6     9
    12    15    18
    21    24    27

With matrix-multiplication -

out = permute(reshape(reshape(M.',[],1)*p(:).',[size(M) numel(p)]),[2 1 3])
查看更多
登录 后发表回答