# 3 Ways to Multiply Matrices in Python

In this instructional, you can learn the way to multiply two matrices in Python.

You’ll get started via studying the situation for legitimate matrix multiplication and write a customized Python serve as to multiply matrices. Next, you’ll see how you’ll succeed in the similar end result the use of nested checklist comprehensions.

Finally, you can continue to use NumPy and its built-in purposes to carry out matrix multiplication extra successfully.

### How to Check if Matrix Multiplication is Valid

Before writing Python code for matrix multiplication, let’s revisit the fundamentals of matrix multiplication.

Matrix Multiplication between two matrices A and B is legitimate provided that the selection of columns in matrix A is equivalent to the selection of rows in matrix B.

You’d have most probably come throughout this situation for matrix multiplication sooner than. However, have you ever ever puzzled why that is the case?

Well, it is as a result of the way in which matrix multiplication works. Take a take a look at the picture beneath.

In our generic instance, matrix A has m rows and n columns. And matrix B has n rows and p columns.

### What is the Shape of the Product Matrix?

The part at index (i, j) in the ensuing matrix C is the dot fabricated from the row i of the matrix A, and column j of the matrix B.

So to get a component at a selected index in the ensuing matrix C, you can have to compute the dot fabricated from the corresponding row and column in matrices A and B, respectively.

Repeating the method above, you can get the product matrix C of form m x p—with m rows and p columns, as proven beneath.

And the dot product or the interior product between two vectors a and b is given via the next equation.

Let’s summarize now:

• It’s obtrusive that the dot product is outlined handiest between vectors of equivalent period.
• So for the dot product between a row and a column to be legitimate—when multiplying two matrices—you would want them each to have the similar selection of components.
• In the above generic instance, each and every row in matrix A has n components. And each and every column in matrix B has n components too.

If you are taking a more in-depth glance, n is the selection of columns in matrix A, and it is also the selection of rows in matrix B. And that is exactly the explanation why you want the selection of columns in matrix A to be equivalent to the selection of rows in matrix B.

I’m hoping you know the situation for matrix multiplication to be legitimate and the way to download each and every part in the product matrix.

Let’s continue to write some Python code to multiply two matrices.

## Write a Custom Python Function to Multiply Matrices

As a primary step, allow us to write a customized serve as to multiply matrices.

This serve as will have to do the next:

• Accept two matrices, A and B, as inputs.
• Check if matrix multiplication between A and B is legitimate.
• If legitimate, multiply the 2 matrices A and B, and go back the product matrix C.
• Else, go back an error message that the matrices A and B can’t be multiplied.

Step 1: Generate two matrices of integers the use of NumPy’s `random.randint()` serve as. You too can claim matrices as nested Python lists.

``````import numpy as np
np.random.seed(27)
A = np.random.randint(1,10,dimension = (3,3))
B = np.random.randint(1,10,dimension = (3,2))
print(f"Matrix A:n An")
print(f"Matrix B:n Bn")

# Output
Matrix A:
[[4 9 9]
[9 1 6]
[9 2 3]]

Matrix B:
[[2 2]
[5 7]
[4 4]]``````

Step 2: Go forward and outline the serve as `multiply_matrix(A,B)`. This serve as takes in two matrices `A` and `B` as inputs and returns the product matrix `C` if matrix multiplication is legitimate.

``````def multiply_matrix(A,B):
world C
if  A.form == B.form:
C = np.zeros((A.form,B.form),dtype = int)
for row in vary(rows):
for col in vary(cols):
for elt in vary(len(B)):
C[row, col] += A[row, elt] * B[elt, col]
go back C
else:
go back "Sorry, can't multiply A and B."``````

### Parsing the Function Definition

Let’s continue to parse the serve as definition.

Declare C as a world variable: By default, all variables within a Python serve as have local scope. And you can not get entry to them from out of doors the serve as. To make the product matrix C available from out of doors, we will have to claim it as a world variable. Just upload the `world` qualifier sooner than the variable title.

Check if matrix multiplication is legitimate: Use the `form` characteristic to test if A and B can also be multiplied. For any array `arr`, `arr.form` and `arr.form` give the selection of rows and columns, respectively. So `if A.form == B.form` tests if matrix multiplication is legitimate. Only if this situation is `True`, the product matrix can be computed. Else, the serve as returns an error message.

Use nested loops to compute values: To compute the weather of the ensuing matrix, we now have to loop in the course of the rows of matrix A, and the outer `for` loop does this. The internal `for` loop is helping us loop in the course of the column of matrix B. And the innermost `for` loop is helping get entry to each and every part in the chosen column.

▶️ Now that now we have discovered how the Python serve as to multiply matrices works, let’s name the serve as with the matrices A and B that we generated previous.

``````multiply_matrix(A,B)

# Output
array([[ 89, 107],
[ 47,  49],
[ 40,  44]])``````

As matrix multiplication between A and B is legitimate, the serve as `multiply_matrix()` returns the product matrix C.

## Use Python Nested List Comprehension to Multiply Matrices

In the former phase, you wrote a Python serve as to multiply matrices. Now, you can see how you’ll use nested checklist comprehensions to do the similar.

Here’s the nested checklist comprehension to multiply matrices.

At first, this will likely glance sophisticated. But we will parse the nested checklist comprehension step-by-step.

Let’s focal point on one checklist comprehension at a time and determine what it does.

We’ll use the next normal template for checklist comprehension:

``````[<do-this> for <item> in <iterable>]

the place,
<do-this>: what you would like to do—expression or operation
<merchandise>: each and every merchandise you would like to carry out the operation on
<iterable>: the iterable (checklist, tuple, and many others.) that you are looping via``````

▶️ Check out our information List Comprehension in Python – with Examples to achieve an in-depth figuring out.

Before going forward, please notice that we would really like to construct the ensuing matrix C one row at a time.

### Nested List Comprehension Explained

Step 1: Compute a unmarried price in the matrix C

Given row i of matrix A and column j of matrix B, the beneath expression offers the access at index (i, j) in matrix C.

``````sum(a*b for a,b in zip(A_row, B_col)

# zip(A_row, B_col) returns an iterator of tuples
# If A_row = [a1, a2, a3] & B_col = [b1, b2, b3]
# zip(A_row, B_col) returns (a1, b1), (a2, b2), and so forth``````

If `i = j = 1`, the expression will go back access `c_11` of the matrix C. So you’ll get one part in one row this fashion.

Step 2: Build one row in the matrix C

Our subsequent function is to construct a complete row.

For row 1 in matrix A, you will have to loop via all columns in matrix B to get one entire row in matrix C.

Go again to the checklist comprehension template.

• Replace `<do-this>` with the expression from step 1, as a result of that is what you need to do.
• Next, change `<merchandise>` with `B_col`—each and every column in matrix B.
• Finally, change `<iterable>` with `zip(*B)`—the checklist containing all columns in matrix B.

And here’s the primary checklist comprehension.

``````[sum(a*b for a,b in zip(A_row, B_col)) for B_col in zip(*B)]

# zip(*B): * is the unzipping operator
# zip(*B) returns an inventory of columns in matrix B``````

Step 3: Build all rows and acquire the matrix C

Next, you can have to populate the product matrix C via computing the remainder of the rows.

And for this, you will have to loop via all rows in matrix A.

Go again to the checklist comprehension once more, and do the next.

• Replace `<do-this>` with the checklist comprehension from step 2. Recall that we computed a complete row in the former step.
• Now, change `<merchandise>` with `A_row`—each and every row in matrix A.
• And your `<iterable>` is the matrix A itself, as you are looping via its rows.

And this is our ultimate nested checklist comprehension.🎊

``````[[sum(a*b for a,b in zip(A_row, B_col)) for B_col in zip(*B)]
for A_row in A]``````

It’s time to examine the outcome! ✔

``````# solid into NumPy array the use of np.array()
C = np.array([[sum(a*b for a,b in zip(A_row, B_col)) for B_col in zip(*B)]
for A_row in A])

# Output:
[[ 89 107]
[ 47  49]
[ 40  44]]``````

If you are taking a more in-depth glance, that is an identical to the nested for loops we had previous—simply that it is extra succinct.

You too can do that all of the extra successfully the use of some built-in purposes. Let’s know about them in the following phase.

## Use NumPy matmul() to Multiply Matrices in Python

The `np.matmul()` takes in two matrices as enter and returns the product if matrix multiplication between the enter matrices is legitimate.

``````C = np.matmul(A,B)
print(C)

# Output:
[[ 89 107]
[ 47  49]
[ 40  44]]``````

Notice how this system is more practical than the 2 strategies we discovered previous. In reality, as a substitute of `np.matmul()`, you’ll use an an identical @ operator, and we will see that straight away.

### How to Use @ Operator in Python to Multiply Matrices

In Python, `@` is a binary operator used for matrix multiplication.

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

Note: You want to have Python 3.5 and later to use the `@` operator.

Here’s how you’ll use it.

``````C = [email protected]
print(C)

# Output
array([[ 89, 107],
[ 47,  49],
[ 40,  44]])``````

Notice that the product matrix C is equal to the only we received previous.

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

If you will have ever come throughout code that makes use of `np.dot()` to multiply two matrices, this is the way it works.

``````C = np.dot(A,B)
print(C)

# Output:
[[ 89 107]
[ 47  49]
[ 40  44]]``````

You’ll see that `np.dot(A, B)` additionally returns the anticipated product matrix.

However, as consistent with NumPy docs, you can use `np.dot()` handiest to compute the dot product of 2 one-dimensional vectors and now not for matrix multiplication.

Recall from the former phase, the part at index (i, j) of the product matrix C is the dot fabricated from the row i of matrix A, and the column j of matrix B.

As NumPy implicitly proclaims this dot product operation to all rows and all columns, you get the ensuing product matrix. But to stay your code readable and steer clear of ambiguity, use `np.matmul()` or the `@` operator as a substitute.

### Conclusion

🎯 In this instructional, you will have discovered the next.

• Condition for matrix multiplication to be legitimate: selection of columns in matrix A = selection of rows in matrix B.
• How to write a customized Python serve as that tests if matrix multiplication is legitimate and returns the product matrix. The frame of the serve as makes use of nested for loops.
• Next, you discovered how to use nested checklist comprehensions to multiply matrices. They’re extra succinct than for loops however are susceptible to clarity problems.
• Finally, you discovered to use NumPy built-in serve as np.matmul() to multiply matrices and the way that is the best in phrases of pace.
• You additionally discovered concerning the @ operator to multiply two matrices in Python.

And that wraps up our dialogue on matrix multiplication in Python. As a subsequent step, learn the way to test if a bunch is key in Python. Or clear up fascinating issues on Python strings.

Happy studying!🎉