Multiply 2D Matrix with vector to span third dimension - MATLAB

隐身守侯 提交于 2019-11-30 09:43:17

问题


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:


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])


来源:https://stackoverflow.com/questions/29276924/multiply-2d-matrix-with-vector-to-span-third-dimension-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!