We earn commission when you buy through affiliate links.

This does not influence our reviews or recommendations.Learn more.

In this tutorial, youll learn how tomultiply two matricesin Python.

mattrix-multiply

Youll start by learning the condition for valid matrix multiplication and write a custom Python function to multiply matrices.

Next, you will see how you might achieve the same result using nested list comprehensions.

Finally, youll proceed to use NumPy and its built-in functions to perform matrix multiplication more efficiently.

product-matrix

Youd have likely come across this condition for matrix multiplication before.

However, have you ever wondered why this is the case?

Well, its because of the way matrix multiplication works.

dot-product

Take a look at the image below.

In our generic example, matrix A hasmrows andncolumns.

And matrix B hasnrows andpcolumns.

nested-list-comprehension-matrix-multiply

What is the Shape of the Product Matrix?

And the dot product or the inner product between two vectorsaandbis given by the following equation.

And this is precisely the reason why you need thenumber of columnsin matrixAto beequalto thenumber of rowsin matrixB.

Lets proceed to write some Python code to multiply two matrices.

you’re able to also declare matrices as nested Python lists.

Step 2:Go ahead and define the functionmultiply_matrix(A,B).

This function takes in two matricesAandBas inputs and returns the product matrixCif matrix multiplication is valid.

Parsing the Function Definition

Lets proceed to parse the function definition.

Declare C as a global variable: By default, all variables inside a Python function have local scope.

And you cannot access them from outside the function.

To make the product matrix C accessible from outside, well have to declare it as a global variable.

Just add theglobalqualifier before the variable name.

verify if matrix multiplication is valid:Use theshapeattribute to verify if A and B can be multiplied.

For any arrayarr,arr.shape[0]andarr.shape[1]give the number ofrowsandcolumns,respectively.

Soif A.shape[1] == B.shape[0]checks if matrix multiplication is valid.

Only if this condition isTrue, the product matrix will be computed.

Else, the function returns an warning pop-up.

The innerforloop helps us loop through the column of matrix B.

And the innermostforloop helps access each element in the selected column.

Now, youll see how you could use nested list comprehensions to do the same.

Heres the nested list comprehension to multiply matrices.

At first, this may look complicated.

But well parse the nested list comprehension step by step.

Lets focus on one list comprehension at a time and identify what it does.

Before going ahead, like note that we would like to build the resultant matrix Cone rowat a time.

Step 2:Build one row in the matrix C

Our next goal is to build an entire row.

And here is the first list comprehension.

And for this, youve to loop through all rows in matrix A.

Go back to the list comprehension yet again, and do the following.

And heres our final nested list comprehension.

Its time to verify the result!

you’re able to also do this all the more efficiently using some built-in functions.

Lets learn about them in the next section.

Notice how this method is simpler than the two methods we learned earlier.

It operates on two matrices, and in general, N-dimensional NumPy arrays, and returns the product matrix.

Note:you oughta have Python 3.5 and later to use the@operator.

Heres how you might use it.

Notice that the product matrix C is the same as the one we obtained earlier.

Can You Use np.dot() to Multiply Matrices?

If youve ever come across code that usesnp.dot()to multiply two matrices, heres how it works.

Youll see thatnp.dot(A, B)also returns the expected product matrix.

But to keep your code readable and avoid ambiguity, usenp.matmul()or the@operator instead.

Conclusion

In this tutorial, youve learned the following.

And that wraps up our discussion on matrix multiplication in Python.

As a next step, learn how to peek if anumber is prime in Python.

Or solve interesting problems on Python strings.