Search code examples
matlaboperator-precedence

Precedence of elementwise multiplication in Matlab


Matlab

ones(2,2)*2.*ones(2,2)

ans =

     2     2
     2     2

ones(2,2).*2*ones(2,2)

ans =

     4     4
     4     4

Solution

  • .* and * are the same precedence, so you are reading the expressions from left to right.

    The first one creates a 2 x 2 matrix of all ones, scales the elements by 2 then element-wise multiplies (i.e. .*) the matrix by another matrix of all ones of the same size, thus giving a result of all 2s. Note that performing 2 * ones(2, 2) and 2 .* ones(2, 2) gives exactly the same result of creating a matrix of size 2 x 2 of all 2s. It's some nice syntactic sugar that MATLAB has. Also note that reversing the order of the operands gives the same results, so ones(2, 2) * 2 and ones(2, 2) .* 2 gives the same result.

    The second one creates a 2 x 2 matrix of all ones, scales the elements by 2 then matrix-multiplies (i.e. *) the matrix with another matrix of all ones, thus giving you a result of all 4s.

    Element-wise multiplication and matrix multiplication are two completely different things. The former ensures that both matrices are the same size, with the exception that either one of the operands is a scalar, and creates a matrix of the same size as either operand with each element in the output being multiplied by the corresponding positions between both matrices. Concretely, given that C(i, j) is the output matrix C at location (i, j), C(i, j) = A(i, j) * B(i, j). Matrix multiplication is the multiplication of two matrices using the laws of linear algebra. I won't insult your intelligence and explain what those are as your profile alludes to you being a mathematician.

    It's no mystery. If you want to convince yourself, enter each part of the expression reading from the left to the right, chaining the previous results together and you'll see that it's correct:

    >> A = ones(2, 2)
    
    A =
    
              1.00          1.00
              1.00          1.00
    
    >> A = A * 2
    
    A =
    
              2.00          2.00
              2.00          2.00
    
    >> A = A .* ones(2, 2)
    
    A =
    
              2.00          2.00
              2.00          2.00
    
    >> B = ones(2, 2)
    
    B =
    
              1.00          1.00
              1.00          1.00
    
    >> B = B .* 2
    
    B =
    
              2.00          2.00
              2.00          2.00
    
    >> B = B * ones(2, 2)
    
    B =
    
              4.00          4.00
              4.00          4.00
    

    I also encourage reading the documentation on the differences between the two: https://www.mathworks.com/help/matlab/ref/times.html, https://www.mathworks.com/help/matlab/ref/mtimes.html.