将2D矩阵与向量相乘以跨越三维-MATLAB [英] Multiply 2D Matrix with vector to span third dimension - MATLAB
本文介绍了将2D矩阵与向量相乘以跨越三维-MATLAB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试将m x n
矩阵与p-dimensional
向量相乘时,我遇到了一些困难.
As I am trying to multiply a m x n
Matrix with a p-dimensional
vector, I am stumbling across some difficulties.
尝试避免for循环,这是我要实现的目标
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]
我想获得一个3x3x3
矩阵,其中三维中的切片只是M
的条目乘以p
中的相应条目.
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
.
非常感谢您的帮助
推荐答案
您可以使用 bsxfun
和 permute
表示<像这样的href ="http://in.mathworks.com/help/matlab/matlab_prog/vectorization.html" rel ="noreferrer"> vectorized
(无循环)方法-
You can use bsxfun
with permute
for a vectorized
(no-loop) approach like so -
out = bsxfun(@times,M,permute(p(:),[3 2 1]))
您最终会得到-
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
使用matrix-multiplication
-
out = permute(reshape(reshape(M.',[],1)*p(:).',[size(M) numel(p)]),[2 1 3])
这篇关于将2D矩阵与向量相乘以跨越三维-MATLAB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文