Working with matrices in Python¶
Matrices can be described by multidimensional
numpy arrays, and we can perform matrix multiplication with the
numpy.matmul() function. 1
import numpy as np r = np.array([3,4]) M = np.array([[0,-1], [1, 0]]) r_prime = np.matmul(M, r) print(r_prime)
The inverse of a matrix can be calculated (if it exists) using
N = np.linalg.inv(M) print(N)
[[ 0. 1.] [-1. -0.]]
np.matmul(N, r_prime) # we should recover our original vector
Matrix–matrix multiplication can also be performed using
MM = np.matmul(M,M) # Two 90 degree rotations should be a 180 degree rotation. print(MM)
[[-1 0] [ 0 -1]]
Download the following files and add them to the working directory of your JupyterHub: visualisation.py and water.txt.
The first file is a text file containing a single Python function (we will explain how to package functions into your own modules later in the course). The second file contains the atomistic coordinates for a water molecule.
Let us read in the water molecule coordinates, and use the
visualisation.show() function to have a look.
import visualisation x, y, z = np.loadtxt('water.txt', unpack=True) visualisation.show(x, y)
You will notice that we do not pass the z-coordinates to the visualisation script. This is because:
3D visualisation is a bit tricky and we want to focus on the understanding of the matrix operations.
We are only going to focus on the rotation in the xy-plane (so the z-coordinate will never change).
The exercise this week is to use matrices and vector to rotate this molecule in the xy-plane. First, you should write a function that will return a NumPy matrix when passed some angle, \(\beta\), with the form,
This is called a rotation matrix, a rotation matrix in a linear algebra tool that lets us rotate something in Euclidean space such as the cartesian coordinate system that we use to describe the atomic positions.
Remember that the NumPy
sin functions will expect the angle to be in radians!
Then use the rotation matrix to obtain new coordinates for the water molecule, by performing the following matrix multiplication.
where \(x\) and \(y\) are the current positions of the x- and y-coordinates respectively and \(x'\) and \(y'\) are the rotated coordinates.
visualisation.show() function to help check that the rotation has been successful.
You can get the same results using
numpy.dot(), but we encourage
numpy.matmul()because it makes the final code easier to read and follow.