FTB 06 – Matrices

Previous: Iterating Through Array

Because this is a class for solving engineering problems using Python – you will now move on to a more advanced topic – matrices and matrix math. We will start with In Python – what is a matrix?

A matrix is simply a 2 dimensional array of numbers. To represent a matrix we will simply make them an array of arrays. So here is an example;

aMatrix = [[1,2,3], [4,5,6], [7,8,9]]

If you look at the variable aMatrix in the Variable Explorer you will see that is of Type: list. As you can see there is no special designation it is multi-dimensional, it is just a list of lists. We can easily look at one of the specific rows of the matrix;

aMatrix = [[1,2,3], [4,5,6], [7,8,9]]
row1 = aMatrix[0]
row2 = aMatrix[1]
row3 = aMatrix[2]

So now we have three variables that are each a list. We can also access and assign values in the matrix through using the bracket notation with multiple brackets;

aMatrix[0][0] = aMatrix[1][1] * aMatrix[2][2]
print(aMatrix[0][0])
45

This will print the number 45, as aMatrix[1][1] is 5 and aMatrix[2][2] is 9, so the product assigned to aMatrix[0][0] is 45. Also worth noting that the value of row1[0] will also be assigned the value 45.

print(row1[0])
45

So why is understanding matrices so important? Because many engineering mathematical problems are solved using matrices and using Python makes this really easy. There are a lot of operations available in the numpy library. Note that to use these you must first import the library.

1: import numpy
2: mult = numpy.matmul(aMatrix, aMatrix)
3: inv = numpy.linalg.inv(aMatrix)

Line 1 – Imports the numpy library (which comes with the anaconda installation) for use.
Line 2 – Using the matmul() function that comes with the numpy library, multiply aMatrix by itself and assign the values to mult. mult will be a matrix just like aMatrix.
Line 3 – numpy comes with libraries (for organization of its many functions), one such library is linalg and linalg contains the function inv() which returns the inverse of the passed matrix. Note that the functions here do not alter the passed array, they simply return the result of the operation.

You can find a list of all these function in the numpy documentation at https://docs.scipy.org/doc/numpy/reference/index.html you can also see more detail about the libraries within numpy such as the linear algebra library https://docs.scipy.org/doc/numpy/reference/routines.linalg.html With a basic understand of lists of lists (matrices) and a powerful library of function, you can quickly and easily solve many problems.