Python: Matrix Multiplication

1. Introduction

Matrix multiplication is a fundamental operation in linear algebra with numerous applications in various fields such as physics, computer graphics, and data science. In this blog post, we will write a Python program to multiply two matrices.

2. Program Overview

1. Input two matrices from the user.

2. Ensure that the number of columns in the first matrix is the same as the number of rows in the second matrix.

3. Perform matrix multiplication.

4. Display the result.

3. Code Program

# Python program to perform matrix multiplication

def input_matrix(rows, cols):
    """Function to input a matrix of given rows and columns."""
    mat = []
    for i in range(rows):
        row = list(map(int, input(f"Enter row {i+1} elements separated by space: ").split()))
        mat.append(row)
    return mat

def matrix_multiplication(mat1, mat2):
    """Function to multiply two matrices."""
    # Initialize the resulting matrix with zeros
    result = [[0 for j in range(len(mat2[0]))] for i in range(len(mat1))]

    # Perform matrix multiplication
    for i in range(len(mat1)):
        for j in range(len(mat2[0])):
            for k in range(len(mat2)):
                result[i][j] += mat1[i][k] * mat2[k][j]
    return result

# Input the two matrices
rows1 = int(input("Enter the number of rows for the first matrix: "))
cols1 = int(input("Enter the number of columns for the first matrix: "))
mat1 = input_matrix(rows1, cols1)

rows2 = int(input("Enter the number of rows for the second matrix: "))
cols2 = int(input("Enter the number of columns for the second matrix: "))
mat2 = input_matrix(rows2, cols2)

# Check if matrix multiplication is possible
if cols1 != rows2:
    print("Matrix multiplication is not possible as number of columns in first matrix is not equal to number of rows in second matrix.")
else:
    result = matrix_multiplication(mat1, mat2)
    print("The resulting matrix after multiplication is:")
    for row in result:
        print(" ".join(map(str, row)))

Output:

Enter the number of rows for the first matrix: 2
Enter the number of columns for the first matrix: 2
Enter row 1 elements separated by space: 1 2
Enter row 2 elements separated by space: 3 4
Enter the number of rows for the second matrix: 2
Enter the number of columns for the second matrix: 2
Enter row 1 elements separated by space: 2 0
Enter row 2 elements separated by space: 1 3
The resulting matrix after multiplication is:
4 6
10 12

4. Step By Step Explanation

1. We start by defining a helper function named input_matrix to input matrices from the user.

2. The matrix_multiplication function initializes an empty result matrix and then performs the multiplication using three nested loops.

3. In the main part of the program, we collect the matrices from the user.

4. We ensure that matrix multiplication is possible by comparing the number of columns in the first matrix with the number of rows in the second matrix.

5. If multiplication is possible, we call our matrix_multiplication function and then display the resulting matrix.

Comments