Matrix Multiplication in Python

This program multiplies two matrices. Matrix multiplication involves multiplying the rows of the first matrix by the columns of the second matrix.

Python Code


# Function to multiply two matrices
def multiply_matrices(matrix1, matrix2):
    """
    Multiplies two matrices and returns the result.
    
    :param matrix1: List of lists where each sublist is a row in the first matrix
    :param matrix2: List of lists where each sublist is a row in the second matrix
    :return: Resultant matrix as a list of lists
    """
    # Number of rows in the first matrix
    rows_matrix1 = len(matrix1)
    # Number of columns in the first matrix (and rows in the second matrix)
    cols_matrix1 = len(matrix1[0])
    # Number of columns in the second matrix
    cols_matrix2 = len(matrix2[0])
    
    # Initializing the result matrix with zeros
    result = [[0 for _ in range(cols_matrix2)] for _ in range(rows_matrix1)]
    
    # Iterating through rows of matrix1
    for i in range(rows_matrix1):
        # Iterating through columns of matrix2
        for j in range(cols_matrix2):
            # Iterating through rows of matrix2
            for k in range(cols_matrix1):
                result[i][j] += matrix1[i][k] * matrix2[k][j]
    
    return result

# Example usage
matrix1 = [
    [1, 2, 3],
    [4, 5, 6]
]

matrix2 = [
    [7, 8],
    [9, 10],
    [11, 12]
]

# Print the matrices
print("Matrix 1:")
for row in matrix1:
    print(row)

print("\nMatrix 2:")
for row in matrix2:
    print(row)

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

# Print the result
print("\nResultant Matrix:")
for row in result:
    print(row)

Explanation

The program includes a function multiply_matrices that takes two matrices as input and returns their product.

  • Defining the function: The function is defined to accept two parameters: matrix1 and matrix2.
  • Determining the dimensions: The number of rows and columns in each matrix is determined using the len() function.
  • Initializing the result matrix: The result matrix is initialized with zeros. It has dimensions equal to the number of rows of the first matrix and the number of columns of the second matrix.
  • Matrix multiplication logic: Nested loops are used to iterate through the rows of the first matrix and the columns of the second matrix. The innermost loop performs the multiplication and addition to compute each element of the resultant matrix.
  • Example usage: Two matrices are defined and printed. The function is called with these matrices, and the resultant matrix is printed.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)