How do you multiply matrix in python?

In Python, we can implement a matrix as nested list [list inside a list].

We can treat each element as a row of the matrix.

For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix.

The first row can be selected as X[0]. And, the element in first row, first column can be selected as X[0][0].

Multiplication of two matrices X and Y is defined only if the number of columns in X is equal to the number of rows Y.

If X is a n x m matrix and Y is a m x l matrix then, XY is defined and has the dimension n x l [but YX is not defined]. Here are a couple of ways to implement matrix multiplication in Python.

Source Code: Matrix Multiplication using Nested Loop

# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

# iterate through rows of X
for i in range[len[X]]:
   # iterate through columns of Y
   for j in range[len[Y[0]]]:
       # iterate through rows of Y
       for k in range[len[Y]]:
           result[i][j] += X[i][k] * Y[k][j]

for r in result:
   print[r]

Output

[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

In this program, we have used nested for loops to iterate through each row and each column. We accumulate the sum of products in the result.

This technique is simple but computationally expensive as we increase the order of the matrix.

For larger matrix operations we recommend optimized software packages like NumPy which is several [in the order of 1000] times faster than the above code.

Source Code: Matrix Multiplication Using Nested List Comprehension

# Program to multiply two matrices using list comprehension

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]

# result is 3x4
result = [[sum[a*b for a,b in zip[X_row,Y_col]] for Y_col in zip[*Y]] for X_row in X]

for r in result:
   print[r]

The output of this program is the same as above. To understand the above code we must first know about built-in function zip[] and unpacking argument list using * operator.

We have used nested list comprehension to iterate through each element in the matrix. The code looks complicated and unreadable at first. But once you get the hang of list comprehensions, you will probably not go back to nested loops.

In this tutorial, you’ll learn how to multiply two matrices in Python.

You’ll start by learning the condition for valid matrix multiplication and write a custom Python function to multiply matrices. Next, you will see how you can achieve the same result using nested list comprehensions.

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

How to Check if Matrix Multiplication is Valid

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

Matrix Multiplication between two matrices A and B is valid only if the number of columns in matrix A is equal to the number of rows in matrix B.

You’d have likely come across this condition for matrix multiplication before. However, have you ever wondered why this is the case?

Well, it’s because of the way matrix multiplication works. Take a look at the image below.

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

NumPy array using 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 take a closer look, this is equivalent to the nested for loops we had earlier—just that it’s more succinct.

You can also do this all the more efficiently using some built-in functions. Let’s learn about them in the next section.

Use NumPy matmul[] to Multiply Matrices in Python

The np.matmul[] takes in two matrices as input and returns the product if matrix multiplication between the input matrices is valid.

C = np.matmul[A,B]
print[C]

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

Notice how this method is simpler than the two methods we learned earlier. In fact, instead of np.matmul[], you can use an equivalent @ operator, and we’ll see that right 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 general, N-dimensional NumPy arrays, and returns the product matrix.

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

Here’s how you can use it.

C = A@B
print[C]

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

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

Can You Use np.dot[] to Multiply Matrices?

If you’ve ever come across code that uses np.dot[] to multiply two matrices, here’s how it works.

C = np.dot[A,B]
print[C]

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

You’ll see that np.dot[A, B] also returns the expected product matrix.

However, as per NumPy docs, you should use np.dot[] only to compute the dot product of two one-dimensional vectors and not for matrix multiplication.

Recall from the previous section, the element at index [i, j] of the product matrix C is the dot product of the row i of matrix A, and the column j of matrix B.

As NumPy implicitly broadcasts this dot product operation to all rows and all columns, you get the resultant product matrix. But to keep your code readable and avoid ambiguity, use np.matmul[] or the @ operator instead.

Conclusion

🎯 In this tutorial, you’ve learned the following.

  • Condition for matrix multiplication to be valid: number of columns in matrix A = number of rows in matrix B.
  • How to write a custom Python function that checks if matrix multiplication is valid and returns the product matrix. The body of the function uses nested for loops.
  • Next, you learned how to use nested list comprehensions to multiply matrices. They’re more succinct than for loops but are prone to readability issues.
  • Finally, you learned to use NumPy built-in function np.matmul[] to multiply matrices and how this is the most efficient in terms of speed.
  • You also learned about the @ operator to multiply two matrices in Python.

And that wraps up our discussion on matrix multiplication in Python. As a next step, learn how to check if a number is prime in Python. Or solve interesting problems on Python strings.

Happy learning!🎉

How do you multiply 2x2 matrices in Python?

Step1: input two matrix. Step 2: nested for loops to iterate through each row and each column. Step 3: take one resultant matrix which is initially contains all 0. Then we multiply each row elements of first matrix with each elements of second matrix, then add all multiplied value.

How do you multiply a matrix in NumPy?

There are three main ways to perform NumPy matrix multiplication:.
dot[array a, array b] : returns the scalar or dot product of two arrays..
matmul[array a, array b] : returns the matrix product of two arrays..
multiply[array a, array b] : returns the element-wise matrix multiplication of two arrays..

Does Python support matrix multiplication?

Python syntax currently allows for only a single multiplication operator *, libraries providing array-like objects must decide: either use * for elementwise multiplication, or use * for matrix multiplication. Right now, most numerical code in Python uses syntax like numpy. dot[a, b] or a.

Chủ Đề