This post is also available as a PDF and as a Jupyter Notebook.

NumPy allows easy standard mathematics to be performed on arrays, a well as moire complex linear algebra such as array multiplication.

Lets begin by building a couple of arrays. We’ll use the np.arange method to create an array of numbers in range 1 to 12, and then reshape the array into a 3 x 4 array.

```
import numpy as np
# note that the arange method is 'half open'
# that is is includes the lower number, and goes up yo, but not including,
# the higher number
array_1 = np.arange(1,13)
array_1 = array_1.reshape (3,4)
print (array_1)
OUT:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
```

## Maths on a single array

We can multiple an array by a fixed number (or we can add, subtract, divide, raise to power, etc):

```
print (array_1 *4)
OUT:
[[ 4 8 12 16]
[20 24 28 32]
[36 40 44 48]]
print (array_1 ** 0.5) # square root of array
OUT:
[[1. 1.41421356 1.73205081 2. ]
[2.23606798 2.44948974 2.64575131 2.82842712]
[3. 3.16227766 3.31662479 3.46410162]]
```

We can define a vector and multiple all rows by that vector:

```
vector_1 = [1, 10, 100, 1000]
print (array_1 * vector_1)
OUT:
[[ 1 20 300 4000]
[ 5 60 700 8000]
[ 9 100 1100 12000]]
```

To multiply by a column vector we will transpose the original array, multiply by our column vector, and transpose back:

```
vector_2 = [1, 10, 100]
result = (array_1.T * vector_2).T
print (result)
OUT:
[[ 1 2 3 4]
[ 50 60 70 80]
[ 900 1000 1100 1200]]
```

## Maths on two (or more) arrays

Arrays of the same shape may be multiplied, divided, added, or subtracted.

Let’s create a copy of the first array:

```
array_2 = array_1.copy()
# If we said array_2 = array_1 then array_2 would refer to array_1.
# Any changes to array_1 would also apply to array_2
```

Multiplying two arrays:

```
print (array_1 * array_2)
OUT:
[[ 1 4 9 16]
[ 25 36 49 64]
[ 81 100 121 144]]
```

## Matrix multiplication (’dot product’)

See https://www.mathsisfun.com/algebra/matrix-multiplying.html for an explanation of matrix multiplication, if you are not familiar with it.

We can perform matrix multiplication in numpy with the np.dot method.

```
array_2 = np.arange(1,13)
array_2 = array_1.reshape (4,3)
print ('Array 1:')
print (array_1)
print ('\nArray 2:')
print (array_2)
print ('\nDot product of two arrays:')
print (np.dot(array_1, array_2))
OUT:
Array 1:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Array 2:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Dot product of two arrays:
[[ 70 80 90]
[158 184 210]
[246 288 330]]
```

## One thought on “35. Array maths in NumPy”