How to Perform Element-wise Operations on Two Matrices in MATLAB
Multiplication
times()
,.*
: Returns the result of multiplying each element of two matrices.
The operation can only proceed if the two matrices are of the exact same size, or one of them is a scalar, or if one is a row vector with the same row size, or a column vector with the same column size. If the sizes are different, the smaller matrix is treated as if it were the same size as the larger matrix, filling the empty spaces with the same values. For example, a scalar becomes a matrix where all elements are the same, and a row vector transforms into a matrix where all rows are identical. If this is confusing, refer to the formula below. .*
can be understood as element-wise multiplication since it combines a dot and a multiplication symbol. The symbols for other element-wise operations are created in the same manner.
$$ A = \begin{pmatrix} a_{1} & a_2 & a_{3} \end{pmatrix}, \quad B = \begin{pmatrix} b_{1} \\ b_{2} \\ b_{3} \\ b_{4} \end{pmatrix} $$
$$ \implies \begin{align*} A .* B &=\begin{pmatrix} a_{1} & a_2 & a_{3} \\ a_{1} & a_2 & a_{3} \\ a_{1} & a_2 & a_{3} \\ a_{1} & a_2 & a_{3} \end{pmatrix} \begin{pmatrix} b_{1} & b_{1} & b_{1} \\ b_2 & b_2 & b_2 \\ b_{3} & b_{3} & b_{3} \\ b_{4} & b_{4} & b_{4} \end{pmatrix} \\ &= \begin{pmatrix} a_{1}b_{1} & a_2b_{1} & a_{3}b_{1} \\ a_{1}b_2 & a_2b_2 & a_{3} b_2 \\ a_{1}b_{3} & a_2 b_{3} & a_{3} b_{3} \\ a_{1}b_{4} & a_2 b_{4} & a_{3} b_{4} \end{pmatrix} \end{align*} $$
Example codes and their output are shown below.
A=[2 1 -3; 4 0 3]
B=[1 2 3]
C=[3; 1]
a=A.*B
b=A.*C
c=B.*C
d=3.*A
Division
rdivide()
,./
: Returns the result of dividing each element of two matrices.
The note about the size of matrices is the same as for .*
. This can be used to easily calculate a matrix where each element is the reciprocal of matrix A, as 1./A
.
Example codes and their output are shown below.
A=[2 1 -3; 4 0 3]
B=[1 2 3]
C=[3; 1]
a=rdivide(A,B)
b=A./C
c=B./C
d=1./A
Power
power()
,.^
: IfA.^B
, it returns the result where each element of A is the base and each element of B is the exponent.
Example codes and their output are shown below.
A=[2 1 -3; 4 0 3]
B=[1 2 3]
C=[3; 1]
a=power(A,B)
b=A.^C
c=B.^C
d=3.^A