Matlab中矢量的元素级乘法*给出矩阵
给定两个向量Matlab中矢量的元素级乘法*给出矩阵,matlab,matrix-multiplication,elementwise-operations,Matlab,Matrix Multiplication,Elementwise Operations,给定两个向量 a = 1:3; b = 2:4; 众所周知,元素级的多重复制a.*b会产生 [ 2 6 12 ] 把这个结果称为c,我们得到了c(i)=a(i)*b(i) 但是我不明白a.*b',b.*a和b'*a是如何产生的 [ 2 4 6 3 6 9 4 8 12 ] 对于矩阵乘法b'*a,我们知道c(i,j)=b(i)*a(j)。 但是为什么其他两个也会产生相同的结果呢 您列出的示例都是元素乘法 a.*b'将在早期的matla
a = 1:3;
b = 2:4;
众所周知,元素级的多重复制a.*b
会产生
[ 2 6 12 ]
把这个结果称为c
,我们得到了c(i)=a(i)*b(i)
但是我不明白a.*b'
,b.*a
和b'*a
是如何产生的
[ 2 4 6
3 6 9
4 8 12 ]
对于矩阵乘法b'*a
,我们知道c(i,j)=b(i)*a(j)
。
但是为什么其他两个也会产生相同的结果呢 您列出的示例都是元素乘法
a.*b'
将在早期的matlab中给出错误,而它执行
bsxfun(@times, a, b')
从R2016b开始在Matlab中使用。这应该可以解释a.*b'
,b'.*a
和b'*a
的相同结果
a*b'
将是矩阵乘法(内部尺寸匹配) 由于隐式扩展(),它本质上与使用bsxfun
相同。
那是什么意思? 设置:
a = 1:3;
b = 2:4;
- 所有MATLAB版本:
根据定义,c = a.*b; % c = [2 6 12], element-wise multiplication c(j) = a(j)*b(j) c = b'*a; % c = [2 4 5; 3 6 9; 4 8 12] % standard matrix multiplication of vectors % c(i,j) = a(i) + b(j) c = bsxfun(@times, b', a) % c = [2 4 5; 3 6 9; 4 8 12] % bsxfun applies the function (in this case @times) to b' and a
“将函数handle fun指定的逐元素二进制操作应用于数组A和B,,并启用单例扩展。这意味着单例维度(大小为1的维度)将按行/列进行扩展,以匹配提供给bsxfun
的其他参数的大小 因此,bsxfun
相当于bsxfun(@times,b',a)
% b' in singleton in the 2nd dimension, a is singleton in the 1st dimension % Use repmat to perform the expansion to the correct size repmat(b', 1, size(a,2)) .* repmat(a, size(b',1), 1) % Equivalent to... repmat(b', 1, 3) .* repmat(a, 3, 1) % Equivalent to... [2 2 2; 3 3 3; 4 4 4] .* [1 2 3; 1 2 3; 1 2 3] % = [2 4 5; 3 6 9; 4 8 12] the same as b'*a
- R2016b之前
c = a.*b'; % Error: Matrix dimensions must agree. c = b'.*a; % Error: Matrix dimensions must agree.
- 自R2016b以来
较新的MATLAB版本使用隐式扩展,这基本上意味着如果有效操作需要,
等价物被称为“引擎盖下”bsxfun
c = a.*b'; % [2 4 5; 3 6 9; 4 8 12] the same as bsxfun(@times, a, b') c = b'.*a; % [2 4 5; 3 6 9; 4 8 12] the same as bsxfun(@times, b', a) % These two are equivalent also because order of operations is irrelevant % We can see this by thinking about the expansion discussed above
正如您所注意到的,如果您不跟踪向量方向,这可能会令人困惑!如果您想要获得1D输出(无需展开),则可以使用冒号运算符确保输入是1D列向量,如下所示
c = a(:).*b(:); % c = [2; 6; 12] always a column vector
我猜你的意思是
R2016b
。我仍然不清楚为什么a.*b'
和b'.*a
的结果不是相互转换的。