>> p=[1;2;3]

p =

     1
     2
     3

>> p1 = [2;3;4]

p1 =

     2
     3
     4

>> p + p1

ans =

     3
     5
     7


>> p .+ p1
Error: "p" was previously used as a variable, conflicting with
its use here as the name of a function or command.
See "How MATLAB Recognizes Command Syntax" in the MATLAB
documentation for details.


>> p .* p1

ans =

     2
     6
    12

>> p * p1
Error using  *
Inner matrix dimensions must agree.

最佳答案

问题是运算符.+不存在:

>> help ops
  Operators and special characters.

  Arithmetic operators.
    plus       - Plus                               +
    uplus      - Unary plus                         +
    minus      - Minus                              -
    uminus     - Unary minus                        -
    mtimes     - Matrix multiply                    *
    times      - Array multiply                    .*
    mpower     - Matrix power                       ^
    power      - Array power                       .^
    ...

请注意,对于乘法,有两个运算符:.*(即element-wise multiplication)和*(即matrix multiplication)。没有矩阵加法这样的事情,因此只有一个运算符+,即element-wise addition

当您键入p .+ p1时,Matlab解析器无法识别有效的运算符,因此它可能假定您正在使用command syntax并尝试使用字符串文字p('.+', 'p1')进行函数调用。由于p不是函数,因此您会看到错误消息。

这种“命令语法”很方便,因为它可以节省您键入几个字符(即load data.mat而不是load('data.mat')的问题。问题是,这导致解释语句的歧义,请通过错误消息查看that was linked directly页。这可能会产生令人惊讶的结果,如您的问题所示,这是Matlab语法的阴暗面之一。

关于matlab - 为什么。+算术运算在相同大小的向量上失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21477421/

10-12 19:40
查看更多