Examples

Python Program to Multiply Two Matrices

A matrix is a rectangular number sequence separated into columns and rows. A matrix element, also known as an entry, is a number that occurs in a matrix. A matrix’s data can be numbers, strings, equations, symbols, and so on. Matrix is a type of data structure that can be utilized in mathematical and scientific operations. Multiplying matrices can provide quick but accurate approximations to considerably more sophisticated calculations in many time-critical engineering applications. In this article, we will learn about the programming logic and concept of Python matrix multiplication, and various methods carried out to perform this task.

Matrix Multiplication

Matrix multiplication is a binary operation that produces another matrix by multiplying two matrices. The elements of the matrix are multiplied using basic arithmetic. When two matrices are multiplied, the row elements of the first matrix are multiplied by the column elements of the second matrix.

Note: It is only possible to multiply two matrices if the number of columns in the first matrix equals the number of rows in the second matrix.

A matrix can be implemented as a hierarchical list in Python (list inside a list). Each element can be thought of as a row in the matrix.

A 3×2 matrix, for example, would be represented by X = [[1, 2], [4, 5], [3, 6]].

X[0] can be used to choose the first row. Furthermore, the element in the first row and the first column can be chosen as X[0][0].

Matrix Multiplication using Nested for Loop

In this Python matrix multiplication method, we will utilize a nested for loop on two matrices to execute multiplication on them and store the result of the multiplication in the third matrix as the result value.

This technique is simple, but it becomes computationally expensive as the order of the matrix increases. We recommend NumPy for larger matrix operations because it is several (in the order of 1000) times faster than the above code.

                    

# Program to multiply two matrices using nested for loops
# 3x3 matrix
A = [[1,2,3],
     [4,5,6],
     [7,8,9]]
# 3x4 matrix
B = [[1,2,3,4],
     [5,6,7,8],
     [2,4,6,8]]
# result is 3x4
result = [[0,0,0,0],
          [0,0,0,0],
          [0,0,0,0]]

# iterate through rows of Matrix A
for i in range(len(A)):
    # iterate through columns of Matrix B
    for j in range(len(B[0])):
        # iterate through rows of Matrix B
        for k in range(len(B)):
            result[i][j] += A[i][k] * B[k][j]

print('Multiplied Matrix:')
for r in result:
    print(r)

Output

                    

Multiplied Matrix:
[17, 26, 35, 44]
[41, 62, 83, 104]
[65, 98, 131, 164]

Explanation

In the above program, we first defined and initialized a set of variables that would be used throughout the program.

A = it will contain the first matrix.

B = It will store the second matrix.

result =  will save matrices’ additional values.

For iteration, use i, j, and k.

We utilized nested for loops to go through each row and column in our program. Finally, we total up all of the objects. The initial row components of the matrix(A) are multiplied by the column elements of the second matrix in the matrix multiplication of two matrices (B). This method is repeated until we had reached all of the row elements.

Matrix Multiplication Using Nested List Comprehension

This program yields the same outcomes as the previous one. In this Python matrix multiplication, we will utilize layered list comprehension in this approach to obtain the multiplication result of two input matrices. We will go through each element of the matrix using layered list comprehension. List comprehension enables us to build compact Python code. To understand this method, we must also know the concept of the built-in method zip() as well as how to unpack an argument list using the * operator.

                    

# Program to multiply two matrices using list comprehension
# 3x3 matrix
A = [[1,2,3],
    [4,5,6],
    [7,8,9]]

# 3x4 matrix
B = [[1,2,3,4],
    [5,6,7,8],
    [2,4,6,8]]

# result is 3x4
result = [[sum(a*b for a,b in zip(A_row,B_col)) for B_col in zip(*B)] for A_row in A]

print('Multiplied Matrix:')
for r in result:
   print(r)

Output

                    

Multiplied Matrix:
[17, 26, 35, 44]
[41, 62, 83, 104]
[65, 98, 131, 164]

Frequently Asked Questions

Q1. How do you perform matrix multiplication in Python?

Steps to Multiply Two Matrices in Python In the first matrix, ask the user to enter the number of rows and columns.

  • Fill in the blanks by entering elements for the first matrix.
  • Now, ask the user to provide only the number of columns for the second matrix, because the rows of the second matrix should be equal to the columns of the first.
  • Enter the elements/items for the second matrix.
  • Use a nested loop within a loop to execute the logic, yielding result [i][j] += matrixA [i][k] * matrixB [k][j].

We can only do matrix multiplication if both matrices meet the following two criteria:

  • The first matrix’s column count must be equal to the second matrix’s row count.
  • Their multiplication yields the same number of rows as the first matrix and the same number of columns as the second matrix.

In Python, we can multiply two matrices using the following methods:

  • Making use of nested loops
  • Making use of nested list comprehension
  • The Numpy module is being used

Q2. Can you multiply a 2×2 and 3×3 matrix?

For a 2×2 matrix multiplying with another 2×2 matrix we observe the following pattern:

  • The row #1 * column #1: enter the answer in row #1 column #1
  • row #1 * column #2: enter the answer in row #1 column #2
  • The row #2 * column #1: enter the answer in row #2 column #1
  • row #2 * column #2: enter the answer in row #2 column #2

Because you are multiplying each element in the first row by each element in the first column, multiplication will be impossible if the number of columns in matrix A is not equal to the number of rows in matrix B.

Q3. How do you multiply a matrix using Numpy in Python?

The Numpy module is a Python library that allows you to compute and manipulate multidimensional and single-dimensional list members. This module’s dot() function computes the dot product of the matrices.

Example

                    

# Program to multiply two matrices using Numpy
import numpy as np
# 3x3 matrix
A = [[1,2,3],
    [4,5,6],
    [7,8,9]]

# 3x4 matrix
B = [[1,2,3,4],
    [5,6,7,8],
    [2,4,6,8]]

# result is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

result = np.dot(A, B)

print('Multiplied Matrix:')
for r in result:
    print(r)

Output

                    

Multiplied Matrix:
[17 26 35 44]
[ 41  62  83 104]
[ 65  98 131 164]

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.