{:check ["true"]}

Index

Vectorized Arithmetics of NDArrays

Operations

In [1]:
import numpy as np

Let's create a $2\times 3$ matrix as 2D nd-array. $$ x = \left[\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \\ \end{array}\right] $$

In [3]:
x = np.array([[1,2,3], [4,5,6]])

numpy ndarray allows natural operations that are closely analogous to the mathematical notations.

Here is the element-wise addition matrices: $x + x$.

In [16]:
x + x
Out[16]:
array([[ 2,  4,  6],
       [ 8, 10, 12]])

Here is element-wise inverse of the matrix $x$.

In [15]:
1 / x
Out[15]:
array([[1.        , 0.5       , 0.33333333],
       [0.25      , 0.2       , 0.16666667]])

Here is the element-wise product of matrices.

In [6]:
x * x
Out[6]:
array([[ 1,  4,  9],
       [16, 25, 36]])

We can take the element-wise power of the matrix $x$.

In [7]:
x ** 2
Out[7]:
array([[ 1,  4,  9],
       [16, 25, 36]])

Numpy comes with another function numpy.power that performs exponentiation.

In [8]:
np.power(x, 2)
Out[8]:
array([[ 1,  4,  9],
       [16, 25, 36]])

Let's create another matrix, also $2\times 3$ in dimensions.

$$ y = x + 10 $$
In [9]:
y = x + 10
y
Out[9]:
array([[11, 12, 13],
       [14, 15, 16]])

We can perform element-wise multiplication between $x$ and $y$ because they have the same shape.

In [10]:
x * y
Out[10]:
array([[11, 24, 39],
       [56, 75, 96]])

But we cannot quite multiple them as matrices because their shapes are not compatible.

In [17]:
x @ y
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-e6c6f87ceb97> in <module>
----> 1 x @ y

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)

However, we can compute the transpose of $y$.

$y^T$ has a shape of $3\times 2$, which is compatible to be multiplied with $x$.

In [12]:
y.T
Out[12]:
array([[11, 14],
       [12, 15],
       [13, 16]])

The result of $A_\mathrm{2\times 3}\cdot B_\mathrm{3\times 2} = C_\mathrm{2\times 2}$ is a square matrix of shape $2\times 2$.

In [13]:
x @ y.T
Out[13]:
array([[ 74,  92],
       [182, 227]])

We can also multiply the transpose of $x$ with $y$.

$A_\mathrm{3\times 2}\cdot B_\mathrm{2\times 3} = C_\mathrm{3\times 3}$

In [14]:
x.T @ y
Out[14]:
array([[ 67,  72,  77],
       [ 92,  99, 106],
       [117, 126, 135]])