2014-01-31 18 views
7
>> 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. 
+0

作品適合我在八度...除了'p * p1'這是正確的:你不能在兩個3x1向量上做矩陣乘法。 – am304

回答

14

的問題是,運營商.+不存在:

>> 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      .^  
    ... 

請注意,對於multiplica有兩個運營商:.*,這是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的語法的黑幕邊。

3

操作".*"執行兩個數組的elementise乘法。

"*"運營商執行的一個mutrix乘法兩個陣列,在你的情況下,這兩個陣列不能在兩個3x1上完成向量,因此Matlab報告錯誤。

".+"運算符在Matlab中不存在。在這種情況下,Matlab認爲您正在使用"."語法來引用結構或函數的元素,因此會出現錯誤。