Python Program to Multiply Two Matrices

Created with Sketch.

Python Program to Multiply Two Matrices

Matrix multiplication is a fundamental operation in linear algebra. In this blog post, we’ll explore how to write a Python program to multiply two matrices. We’ll discuss the algorithm involved and provide a complete Python code example with output.

Matrix Multiplication Algorithm:

Matrix multiplication follows a specific algorithm where each element of the resulting matrix is calculated by taking the dot product of the corresponding row from the first matrix and column from the second matrix. Let’s denote the matrices as A and B, and the result matrix as C. The element at position (i, j) in matrix C is calculated as follows:

def multiply_matrices(A, B):
    # Get the dimensions of the matrices
    rows_A = len(A)
    cols_A = len(A[0])
    rows_B = len(B)
    cols_B = len(B[0])

    # Check if matrices can be multiplied
    if cols_A != rows_B:
        print("Matrices cannot be multiplied. Invalid dimensions.")
        return None

    # Initialize the result matrix with zeros
    C = [[0 for _ in range(cols_B)] for _ in range(rows_A)]

    # Perform matrix multiplication
    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k] * B[k][j]

    return C

# Example matrices
matrix_A = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

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

# Multiply matrices
result_matrix = multiply_matrices(matrix_A, matrix_B)

# Display the result
if result_matrix:
    print("Resultant Matrix after Multiplication:")
    for row in result_matrix:
        print(row)

Output:

 
Resultant Matrix after Multiplication:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]

This output represents the product of the given matrices and . The multiply_matrices function takes two matrices as input, checks if they can be multiplied, and returns the resulting matrix if the multiplication is valid.

Feel free to run this Python program in your environment to observe the matrix multiplication output. If you have any questions or need further clarification, don’t hesitate to ask!

Leave a Reply

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