Matrices and vectors

1. Matrices and vectors#

Important!

If you’re completely new to Python, you may want to go through the exercises in the Python fundamentals notebook first!

Since this is a linear algebra class, our first demo will be working with matrices and vectors in Python using the NumPy library. Regardless of the dimensions, the objects are all NumPy arrays which can be built from lists and further manipulated. Using NumPy arrays (instead of list) will make our lives much easier, as you will see!

Summary of commands#

In this exercise, we will demonstrate the following:

  • Numpy

    • @ - matrix multiplication operator.

    • * - element-wise (scalar) multiplication operator.

    • array.shape - attribute that returns the dimensions of each axis in array.

    • array.size - attribute that returns the number of elements in array.

    • array.ndim - attribute that returns the number of dimensions in array.

    • array.T/np.transpose(array) - transpose of the array.

    • np.round(array) - Returns integer values of the argument.

  • Matplotlib

    • plt.subplots() - Create Figure and Axes objects for plotting. Many possible parameters.

    • ax.plot(x, y, ...) - Create a scatter/line plot in 1D, y vs. x. Many styles possible.

    • ax.set(...) - Set axes xlabel, ylabel, xlim, ylim, title, etc.

Demo#

We will multiply the following two matrices:

\[\begin{split} A = \begin{bmatrix} 1 & 2 \\ -1 & 3 \end{bmatrix}, \qquad B = \begin{bmatrix} 1 & 0 & 1 \\ 2 & 1 & 0 \end{bmatrix}. \end{split}\]

We will determine the size of the resulting matrix, and display the bottom-left element and the second column on the screen.

Important

Recall that Python is 0-indexed! This is a key difference from MATLAB.

# initial matrices
import numpy as np
A = np.array([[1, 2], [-1, 3]])
B = np.array([[1, 0, 1], [2, 1, 0]])

# calculate and display their product
C = A @ B
print("Product of A * B:")
print(C)
print()

# calculate the size of the new matrix
print("The size of matrix C:")
print(C.shape)
print()

# display bottom-left element and second column
print("Bottom-left element of C:")
print(C[1,0])
print()

print("Second column of C:")
print(C[:,1])
Product of A * B:
[[ 5  2  1]
 [ 5  3 -1]]

The size of matrix C:
(2, 3)

Bottom-left element of C:
5

Second column of C:
[2 3]