[英]Multiply 2D Matrix with vector to span third dimension - MATLAB
As I am trying to multiply a mxn
Matrix with a p-dimensional
vector, I am stumbling across some difficulties. 当我尝试将mxn
矩阵与p-dimensional
向量相乘时,我遇到了一些困难。
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
. 我想获得一个3x3x3
矩阵,其中三维中的切片只是M
的项乘以p
的相应项。
Help is much appreciated 非常感谢帮助
You can use bsxfun
with permute
for a vectorized
(no-loop) approach like so - 您可以使用bsxfun
与permute
为vectorized
(无环)的方式,像这样-
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
- 使用matrix-multiplication
-
out = permute(reshape(reshape(M.',[],1)*p(:).',[size(M) numel(p)]),[2 1 3])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.