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:
-
@
- matrix multiplication operator.*
- element-wise (scalar) multiplication operator.array.shape
- attribute that returns the dimensions of each axis inarray
.array.size
- attribute that returns the number of elements inarray
.array.ndim
- attribute that returns the number of dimensions inarray
.array.T
/np.transpose(array)
- transpose of thearray
.np.round(array)
- Returns integer values of the argument.
-
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 axesxlabel
,ylabel
,xlim
,ylim
,title
, etc.
Demo#
We will multiply the following two matrices:
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]