Linear algebra is the subject involving vector and matrix operations. NumPy makes linear algebra a lot easier, so let's find out how to use it to do what we discussed in the previous math lesson.

Addition/Subtraction

To perform addition/subtraction, we can use the + or - operator between two matrices. For example:

u = np.array([0, 1, 2])
v = np.array([1, 2, 3])

# w = [1, 3, 5]
w = u + v
# x = [-1, -1, -1]
x = u - v

The above code will create two NumPy arrays, and their sum is stored in w, while their difference is stored in x. If you had to do this without NumPy, things would be a lot harder. We can do the same for any $n$-dimensional NumPy array as long as the arrays have the same dimensions.

Scalar Multiplication

To perform scalar multiplication, we just use the * operator between a scalar and a matrix. For example:

# z = [3, 6, 9]
z = 3 * np.array([1, 2, 3])

The above code stores the NumPy array $[3, 6, 9]$ in z.

Dot Product

The dot product is done by a in-built function: np.dot(x, y).

u = np.array([1, 2])
v = np.array([2, 3])

# z = 8
z = np.dot(u, v)

Broadcasting

u = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
z = u + 1

# z = [2, 3, 4, 5, 6, 7, 8, 9, 10]

This is a bit of a unique operation that NumPy allows. Broadcasting allows us to add a number to every element of the array.

Matrix Multiplication

# returns a * b
np.dot(a, b)

The dot function from the NumPy library would just multiply inputs if you enter constants. If you input 1-dimensional NumPy arrays, it returns the dot product as discussed earlier. If you enter 2D NumPy arrays, the np.dot will multiply the two matrices together.

For example,