0
0
PythonProgramBeginner · 2 min read

Python Program to Multiply Two Matrices

To multiply two matrices in Python, use nested loops to calculate the sum of products for each element, like result[i][j] += matrix1[i][k] * matrix2[k][j] inside three loops iterating over rows and columns.
📋

Examples

Inputmatrix1 = [[1, 2], [3, 4]] matrix2 = [[5, 6], [7, 8]]
Output[[19, 22], [43, 50]]
Inputmatrix1 = [[2, 0], [1, 3]] matrix2 = [[1, 4], [2, 5]]
Output[[2, 8], [7, 19]]
Inputmatrix1 = [[1]] matrix2 = [[9]]
Output[[9]]
🧠

How to Think About It

To multiply two matrices, think of each element in the result as the sum of multiplying elements from a row in the first matrix with elements from a column in the second matrix. You loop through each row of the first matrix and each column of the second matrix, multiplying and adding the matching elements to get the final value.
📐

Algorithm

1
Check if the number of columns in the first matrix equals the number of rows in the second matrix.
2
Create a result matrix with the number of rows of the first matrix and columns of the second matrix, filled with zeros.
3
For each row in the first matrix, loop through each column in the second matrix.
4
For each position, multiply corresponding elements and add them to the result matrix element.
5
Return or print the result matrix.
💻

Code

python
def multiply_matrices(matrix1, matrix2):
    rows1, cols1 = len(matrix1), len(matrix1[0])
    rows2, cols2 = len(matrix2), len(matrix2[0])
    if cols1 != rows2:
        return None  # Cannot multiply
    result = [[0 for _ in range(cols2)] for _ in range(rows1)]
    for i in range(rows1):
        for j in range(cols2):
            for k in range(cols1):
                result[i][j] += matrix1[i][k] * matrix2[k][j]
    return result

# Example usage
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
print(multiply_matrices(matrix1, matrix2))
Output
[[19, 22], [43, 50]]
🔍

Dry Run

Let's trace multiplying matrix1 = [[1, 2], [3, 4]] and matrix2 = [[5, 6], [7, 8]] through the code.

1

Initialize dimensions

rows1=2, cols1=2, rows2=2, cols2=2

2

Create result matrix

result = [[0, 0], [0, 0]]

3

Calculate result[0][0]

result[0][0] = 1*5 + 2*7 = 5 + 14 = 19

4

Calculate result[0][1]

result[0][1] = 1*6 + 2*8 = 6 + 16 = 22

5

Calculate result[1][0]

result[1][0] = 3*5 + 4*7 = 15 + 28 = 43

6

Calculate result[1][1]

result[1][1] = 3*6 + 4*8 = 18 + 32 = 50

ElementCalculationValue
result[0][0]1*5 + 2*719
result[0][1]1*6 + 2*822
result[1][0]3*5 + 4*743
result[1][1]3*6 + 4*850
💡

Why This Works

Step 1: Check matrix sizes

We ensure the number of columns in the first matrix equals the number of rows in the second matrix because this is required for multiplication.

Step 2: Prepare result matrix

We create a new matrix filled with zeros to store the multiplication results, sized by rows of the first and columns of the second matrix.

Step 3: Multiply and sum elements

For each element in the result, we multiply corresponding elements from the row of the first matrix and column of the second matrix, then add them up.

🔄

Alternative Approaches

Using NumPy library
python
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
result = np.dot(matrix1, matrix2)
print(result.tolist())
This method is faster and simpler but requires installing the NumPy library.
List comprehension
python
def multiply_matrices_lc(A, B):
    return [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))]

matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
print(multiply_matrices_lc(matrix1, matrix2))
This method uses concise list comprehension but may be harder to read for beginners.

Complexity: O(n * m * p) time, O(n * p) space

Time Complexity

The time depends on three nested loops: rows of first matrix (n), columns of second matrix (p), and columns of first matrix/rows of second matrix (m). So it is O(n * m * p).

Space Complexity

We create a new matrix of size n by p to store results, so space complexity is O(n * p).

Which Approach is Fastest?

Using NumPy is fastest due to optimized C code, while pure Python loops are slower but more educational.

ApproachTimeSpaceBest For
Nested loopsO(n*m*p)O(n*p)Learning and small matrices
NumPy dotOptimized C speedO(n*p)Large matrices and performance
List comprehensionO(n*m*p)O(n*p)Concise code, moderate readability
💡
Always check that the number of columns in the first matrix matches the number of rows in the second before multiplying.
⚠️
Trying to multiply matrices with incompatible sizes without checking dimensions first.