2

给定两个向量

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)
但是为什么另外两个也会产生相同的结果呢?

4

2 回答 2

3

由于隐式扩展(在 2016b 中引入),它与 using 基本相同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“将函数句柄 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
    

正如您所注意到的,如果您不跟踪矢量方向,这可能会令人困惑!如果您想获得一维输出(没有扩展),那么您可以通过使用冒号运算符来确保您的输入是一维列向量,如下所示

c = a(:).*b(:); % c = [2; 6; 12] always a column vector
于 2017-11-15T09:09:58.913 回答
1

您列出的示例都是逐元素乘法。

a.*b'会在早期的 matlab 中给出错误,而它执行

bsxfun(@times, a, b')

自 R2016b 以来在 Matlab 中。这应该解释 和 的a.*b'相同b'.*a结果b'*a

a * b'将是矩阵乘法(内部维度匹配)。

于 2017-11-15T03:44:35.547 回答