Share on:

#### Python NumPy For Your Grandma | Section 2.5 | Basic Math

##### December 29, 2019
python courses

This video covers basic math operations for NumPy arrays like addition, subtraction, multiplication, division, and matrix multiplication.

# Code

import numpy as np

# make 2x2 arrays
foo = np.array([[4,3], [1,0]])
bar = np.array([[1,2], [3,4]])

foo + bar

# subtraction
foo - bar

# multiplication
foo * bar

# division
foo / bar

# matrix multiplication, you can use the @ operator
foo @ bar

# Transcript

Now let’s see some basic math operations using these 2x2 arrays. With numpy, you can

• subtract arrays
• multiply arrays
• divide arrays

and do other basic math operations pretty seamlessly if your arrays have the same shape.

It’s important to realize that these operations happen element-wise. For example, when we multiply foo times bar, the first element in the result is the product of the first element in foo times the first element in bar. This is different than matrix multiplication where the first element of the result would be equal to the dot product of the first row of foo with the first column of bar.
If you want to do standard matrix multiplication, you can use the ‘at’ operator.
In a future section, we’ll see how you can use broadcasting to do math on arrays with different shapes. 