"
This article is part of in the series
Published: Tuesday 18th April 2017

In Python and most other OOP programming languages, multiplying two numbers by each other is a pretty straightforward process. Where it gets a little more complicated, however, is when you try to multiply two matrices by each other. A matrix, as you may know, is basically just a nested list, or a number of lists inside of another list. When working with a matrix, each individual list inside the main list can be considered a row, and each value within a row can be considered a column. Here's what a matrix might look like:

x = [[4, 3], [88, 7], [56, 31]]

The matrix in the example above has three rows, each with two columns.

If you want to try to multiply two matrices (x and y) by each other, you'll need to make sure that the number of columns in x is equal to the number of rows in y, otherwise the equation won't work properly. For the sake of this tutorial, let's multiply two matrices by each other that each have three rows, with three columns in each -- so 3x3 matrices. Keep in mind that when you multiply two matrices by each other, the resulting matrix will have as many columns as the biggest matrix in you're equation, so for example, if you're multiplying a 3x3 by a 3x4, the resulting matrix will be a 3x4.

For the purposes of this tutorial, we'll be multiplying a 3x3 by a 3x3. Let's take a look at the example below to see how it works:

X = [[34,1,77],
 [2,14,8],
 [3 ,17,11]]

Y = [[6,8,1],
 [9,27,5],
 [2,43,31]]

result = [[0,0,0],
 [0,0,0],
 [0,0,0]]

for i in range(len(X)):
 for j in range(len(Y[0])):
 for k in range(len(Y)):
 result[i][j] += X[i][k] * Y[k][j]

for r in result:
 print(r)

In the example above, we first have to define our matrices. Then we need to define a result matrix that will represent the matrix that holds the answers to our equations. Because our two matrices are 3x3, our result matrix is 3x3 also. Next, we iterate through the rows of the x matrix, then the columns of the y matrix (this is done using y[0]), and finally through the rows of the y matrix. Then the arithmetic is performed.

The output of the example above would be as follows:

r =[[367, 3610, 2428], [154, 738, 320], [193, 956, 429]]

This basic information should be enough to get you started on multiplying matrices on your own. Once you've mastered multiplying like matrices, be sure to challenge yourself and try multiplying ones that don't have an equal number of columns and rows.