Elementary multiplication priority 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

      

+3


source to share


1 answer


.*

and *

have the same precedence, so you read expressions from left to right.

The first one creates a matrix of 2 x 2

all ones, scales the elements by 2, and then multiplies the elements by (i.e. .*

) the matrix by another matrix of all ones of the same size, which gives a result of all 2s. Note that doing 2 * ones(2, 2)

and 2 .* ones(2, 2)

gives exactly the same result of creating a size matrix 2 x 2

for all 2s. This is nice syntactic sugar that MATLAB has. Also note that changing the order of the operands gives the same results, ones(2, 2) * 2

and therefore ones(2, 2) .* 2

gives the same result.

The second creates a matrix of 2 x 2

all ones, scales the elements by 2, and then matrix-multiplies (i.e. *

) the matrix with another matrix of all ones, which gives you the result of all 4s.

Elementary multiplication and matrix multiplication are two completely different things. The former ensures that both matrices are the same size, except that either one of the operands is a scalar, and creates a matrix the same size as any operand with each element in the output multiplied by the appropriate positions between both matrices. that C(i, j)

is the output matrix C

in the 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 will not insult your mind and explain what it is that your profile refers to you as a mathematician.



This is not a secret. If you want to convince yourself, enter each part of the expression that reads from left to right, concatenating the previous results together, and you will see that it is 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 recommend 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 .

+6


source







All Articles