Why .+ arithmetic operations fails on vector of same size

>> p=[1;2;3]

p =

     1
     2
     3

>> p1 = [2;3;4]

p1 =

     2
     3
     4

>> p + p1

ans =

     3
     5
     7

But

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

Also

>> p .* p1

ans =

     2
     6
    12

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

Answers


The problem is that the operator .+ does not exist:

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

Note that for multiplications, there are two operators: .*, which is element-wise multiplication, and *, which is matrix multiplication. There is no such thing as matrix addition, so there is only one operator +, which is element-wise addition.

When you type p .+ p1, the Matlab parser does not recognize a valid operator, so it probably assumes you are using the command syntax and tries to make the function call with string literals p('.+', 'p1'). Since p is not a function, you get the error message you see.

This 'command syntax' is convenient in that it can save you typing a few characters (i.e. load data.mat instead of load('data.mat'). The problem is that this leads to ambiguity in interpreting statements, see the page that was linked directly by your error message. This can give surprising results, as your question shows. This is one of the shady sides of Matlab's syntax.


The operator ".*" performs an elementise multiplication of the two arrays.

The "*" operator performs a mutrix multiplication of the two arrays, which in your case cannot be done on two 3x1 vectors, hence Matlab reports an error.

The ".+" operator does not exist in Matlab. In this case, Matlab thinks you are using the "." syntax to reference an element of a structure or function, hence the error you are getting.


Need Your Help

Capturing key event for backspace

javascript jquery android

I am having difficulty capturing the backspace key as a keyboard Event in javascript/jQuery. In Firefox, Safari, Opera, Chrome, and on the iPhone/iPad, I capture a keyup event on a text input box l...

jQuery, PHP, AJAX, "tu" variable beeing posted for no reason, shows in var_dump()

php post jquery var-dump jquery-post

A jQuery AJAX request .post()s data to page.php, which creates $res and var_dump()s it.