给出两个向量
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)
。
但为什么其他两个也会产生相同的结果呢?
答案 0 :(得分:2)
由于隐式扩展(introduced in 2016b),它与使用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
根据定义,bsxfun
“将函数handle fun指定的逐元素二进制操作应用于数组A和B,启用单例扩展”。这意味着单个维度(大小为1的维度)按行/列扩展,以匹配提供给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
答案 1 :(得分:1)
您列出的示例都是元素乘法。
a.*b'
会在早期的matlab中出错,而它会执行
bsxfun(@times, a, b')
自R2016b以来在Matlab中的。这应该解释a.*b'
,b'.*a
和b'*a
的相同结果。
a * b'
将是矩阵乘法(内部维度匹配)。