问题
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