Python Tutorials

Python Programs

Python Multiply Two Matrices


Python Multiply Two Matrices

In this tutorial, we will learn how to multiply two matrices in Python. We will cover the basic concept of matrix multiplication and implement a function to perform the operation.


What is Matrix Multiplication

Matrix multiplication is the process of multiplying two matrices by taking the dot product of rows and columns. The number of columns in the first matrix must be equal to the number of rows in the second matrix.


Syntax

The syntax to multiply two matrices in Python is:

def multiply_matrices(matrix1, matrix2):
    result = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))]
    for i in range(len(matrix1)):
        for j in range(len(matrix2[0])):
            for k in range(len(matrix2)):
                result[i][j] += matrix1[i][k] * matrix2[k][j]
    return result


Multiplying two matrices

We can create a function to multiply two matrices by taking the dot product of rows and columns.

For example,

  1. Define a function named multiply_matrices that takes two parameters matrix1 and matrix2.
  2. Initialize a result matrix with zeros, having the same number of rows as matrix1 and the same number of columns as matrix2.
  3. Use a nested for loop to iterate through the rows of matrix1 and the columns of matrix2.
  4. In the innermost loop, calculate the dot product of the corresponding row and column and update the result matrix.
  5. Return the result matrix.
  6. Call the function with sample matrices and print the result.

Python Program

def multiply_matrices(matrix1, matrix2):
    result = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))]
    for i in range(len(matrix1)):
        for j in range(len(matrix2[0])):
            for k in range(len(matrix2)):
                result[i][j] += matrix1[i][k] * matrix2[k][j]
    return result

# Sample matrices
matrix1 = [[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]]

matrix2 = [[9, 8, 7],
           [6, 5, 4],
           [3, 2, 1]]

# Multiply the matrices
result = multiply_matrices(matrix1, matrix2)

# Print the result
print('Product of the matrices is:')
for row in result:
    print(row)

Output

Product of the matrices is:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]