Matrix Multiplication in Python | Code with Simple Examples

Matrix multiplication is a fundamental operation in linear algebra and has numerous applications in data science, machine learning, computer graphics, and scientific computing. In this comprehensive guide, we'll explore various ways to implement matrix multiplication in Python, from basic implementations using nested loops to more efficient approaches using libraries like NumPy.

Understanding Matrix Multiplication

Before diving into the Python program for matrix multiplication, let's quickly review what matrix multiplication involves:

  • You can only multiply two matrices if the number of columns in the first one is the same as the number of rows in the second one
  • If A is an m × n matrix and B is an n × p matrix, the resulting matrix C will be an m × p matrix
  • Each element C[i][j] is calculated as the dot product of the ith row of A and the jth column of B

Matrix Multiplication in Python Using For Loops

Let's start with a basic implementation of matrix multiplication in Python using for loop structures:

def matrix_multiply(A, B):
    # Check if matrices can be multiplied
    if len(A[0]) != len(B):
        return "Matrices cannot be multiplied. Incompatible dimensions."
    
    # Initialize result matrix with zeros
    result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]
    
    # Perform matrix multiplication
    for i in range(len(A)):
        for j in range(len(B[0])):
            for k in range(len(B)):
                result[i][j] += A[i][k] * B[k][j]
                
    return result

# Example usage of our matrix multiplication Python code
A = [[1, 2, 3],
     [4, 5, 6]]

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

result = matrix_multiply(A, B)

# Print the result
for row in result:
    print(row)

 

This Python program to multiply two matrices demonstrates the classic triple-nested loop approach. While straightforward to understand, this method has a time complexity of O(n³) for n×n matrices, making it inefficient for large matrices.

Optimizing Matrix Operations in Python

For better performance, we can leverage NumPy, a powerful library for numerical computations in Python. NumPy provides highly optimized functions for matrix operations in Python:

import numpy as np

def numpy_matrix_multiply(A, B):
    # Convert to NumPy arrays
    A_array = np.array(A)
    B_array = np.array(B)
    
    # Perform matrix multiplication
    result = np.matmul(A_array, B_array)
    # Alternatively: result = A_array @ B_array
    
    return result

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

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

result = numpy_matrix_multiply(A, B)
print(result)

 

The NumPy implementation is not only more concise but also significantly faster than the manual implementation, especially for larger matrices.

Comparing Different Methods for Matrix Multiplication in Python

Let's compare the performance of different approaches to matrix multiplication in Python:

  1. Manual implementation with for loops: Easy to understand but inefficient for large matrices
  2. NumPy's matmul function: Highly optimized and much faster
  3. NumPy's @ operator: Syntactic sugar for matrix multiplication introduced in Python 3.5
  4. NumPy's dot function: Another alternative with similar performance to matmul

Here's an example comparing execution times:

import numpy as np
import time

def compare_matrix_multiplication_methods(A, B):
    # Method 1: Manual implementation
    start_time = time.time()
    manual_result = matrix_multiply(A, B)
    manual_time = time.time() - start_time
    
    # Convert to NumPy arrays
    A_np = np.array(A)
    B_np = np.array(B)
    
    # Method 2: NumPy matmul
    start_time = time.time()
    np_matmul_result = np.matmul(A_np, B_np)
    np_matmul_time = time.time() - start_time
    
    # Method 3: NumPy @ operator
    start_time = time.time()
    np_at_result = A_np @ B_np
    np_at_time = time.time() - start_time
    
    print(f"Manual implementation time: {manual_time:.6f} seconds")
    print(f"NumPy matmul time: {np_matmul_time:.6f} seconds")
    print(f"NumPy @ operator time: {np_at_time:.6f} seconds")

 

Complete Python Program to Multiply Two Matrices

Here's a complete Python program to multiply two matrices that includes input validation and formatting:

def matrix_multiplication_program():
    # Get matrix dimensions from the user
    rows_A = int(input("Enter the number of rows for matrix A: "))
    cols_A = int(input("Enter the number of columns for matrix A: "))
    rows_B = int(input("Enter the number of rows for matrix B: "))
    cols_B = int(input("Enter the number of columns for matrix B: "))
    
    # Check if matrices can be multiplied
    if cols_A != rows_B:
        print("Matrices cannot be multiplied. The number of columns in A must equal the number of rows in B.")
        return
    
    # Initialize matrices
    A = []
    B = []
    
    # Get elements of matrix A
    print("\nEnter elements of matrix A:")
    for i in range(rows_A):
        row = []
        for j in range(cols_A):
            element = float(input(f"Enter element A[{i+1}][{j+1}]: "))
            row.append(element)
        A.append(row)
    
    # Get elements of matrix B
    print("\nEnter elements of matrix B:")
    for i in range(rows_B):
        row = []
        for j in range(cols_B):
            element = float(input(f"Enter element B[{i+1}][{j+1}]: "))
            row.append(element)
        B.append(row)
    
    # Perform matrix multiplication
    result = [[0 for _ in range(cols_B)] for _ in range(rows_A)]
    
    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                result[i][j] += A[i][k] * B[k][j]
    
    # Display the matrices and result
    print("\nMatrix A:")
    for row in A:
        print(row)
    
    print("\nMatrix B:")
    for row in B:
        print(row)
    
    print("\nResult (A × B):")
    for row in result:
        print(row)

# Run the program
if __name__ == "__main__":
    matrix_multiplication_program()

 

Advanced Matrix Operations in Python

Beyond basic multiplication, Python offers various tools for other matrix operations in Python:

  • Transposition: np.transpose(A) or A.T
  • Inverse: np.linalg.inv(A)
  • Determinant: np.linalg.det(A)
  • Eigenvalues and eigenvectors: np.linalg.eig(A)

These operations are essential for advanced applications in machine learning, computer vision, and data analysis.

Conclusion

Matrix multiplication is a core operation in many computational and scientific fields. This guide has covered various approaches to implementing matrix multiplication in Python, from basic for-loop implementations to efficient NumPy solutions.

For small matrices or educational purposes, the manual implementation using nested loops helps understand the underlying algorithm. However, for real-world applications dealing with larger matrices, NumPy's optimized functions provide significantly better performance.

Whether you're developing algorithms for machine learning, computer graphics, or scientific simulations, understanding matrix multiplication Python code is an essential skill that will serve you well in your programming journey.

Remember that choosing the right approach depends on your specific requirements regarding performance, readability, and compatibility with the rest of your codebase.