Python Lab · Experiment 25
Multiplication of two square matrices
PythonWeek 5JNTUH R22 · CS206ES
Aim
To write a Python program that reads the size n and the values of two n × n matrices from the user, multiplies them, and prints the product matrix.
Algorithm
- Read the size n. If n is not a positive number, print a message and stop.
- Read matrix A one row at a time, n integers per row. If a row does not have exactly n numbers, ask for it again.
- Read matrix B in the same way.
- Create an n × n result matrix C filled with zeros.
- For every row i of A and every column j of B, add up A[i][k] × B[k][j] for k = 0 to n − 1, and store the total in C[i][j].
- Print A, B and the product C in rows and columns.
Program
def read_matrix(n, name):
print(f"Enter matrix {name} ({n} numbers per row):")
matrix = []
for i in range(n):
row = [int(x) for x in input(f"Row {i + 1}: ").split()]
while len(row) != n:
print(f"Please enter exactly {n} numbers")
row = [int(x) for x in input(f"Row {i + 1}: ").split()]
matrix.append(row)
return matrix
def multiply_matrices(a, b):
n = len(a)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += a[i][k] * b[k][j]
return result
def print_matrix(matrix):
for row in matrix:
for value in row:
print(f"{value:5}", end="")
print()
def main():
n = int(input("Enter the size of the square matrices: "))
if n <= 0:
print("Size must be a positive number")
return
a = read_matrix(n, "A")
b = read_matrix(n, "B")
c = multiply_matrices(a, b)
print("Matrix A:")
print_matrix(a)
print("Matrix B:")
print_matrix(b)
print("Product A x B:")
print_matrix(c)
main()Output
Two 2 × 2 matrices
Enter the size of the square matrices: 2
Enter matrix A (2 numbers per row):
Row 1: 1 2
Row 2: 3 4
Enter matrix B (2 numbers per row):
Row 1: 5 6
Row 2: 7 8
Matrix A:
1 2
3 4
Matrix B:
5 6
7 8
Product A x B:
19 22
43 50Two 3 × 3 matrices
Enter the size of the square matrices: 3
Enter matrix A (3 numbers per row):
Row 1: 1 2 3
Row 2: 4 5 6
Row 3: 7 8 9
Enter matrix B (3 numbers per row):
Row 1: 9 8 7
Row 2: 6 5 4
Row 3: 3 2 1
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
9 8 7
6 5 4
3 2 1
Product A x B:
30 24 18
84 69 54
138 114 90Recorded by running this exact program. Typed input appears after each prompt.
How it works
Each value of the product is a row of A "times" a column of B. For the 2 × 2 run, C[0][0] = 1 × 5 + 2 × 7 = 19 and C[0][1] = 1 × 6 + 2 × 8 = 22.
The three nested loops do n × n × n multiplications, so the time grows as n³.
[[0] * n for _ in range(n)] builds n separate rows of zeros. The list comprehension is needed: [[0] * n] * n would make every row the same list.
With numpy, the product of two arrays is numpy.array(a) @ numpy.array(b) (or numpy.dot(a, b)). Note that * on numpy arrays multiplies element by element, which is not matrix multiplication.
Common mistakes
Multiplying element by element,
C[i][j] = A[i][j] * B[i][j]. Matrix multiplication needs the sum over k ofA[i][k] * B[k][j].Not starting
C[i][j]at 0 before adding, or resetting it inside the k loop. Then the sum is wrong.Writing
B[j][k]instead ofB[k][j]. That uses rows of B instead of columns and gives a wrong answer that is easy to miss.Creating the result with
[[0] * n] * n. All rows share one list, so every row of the answer comes out the same.
Viva questions
Try to answer each one aloud before you open it.
When can matrix A be multiplied by matrix B?
When the number of columns of A equals the number of rows of B. If A is m × n and B is n × p, the product is m × p. Two square matrices of the same size can always be multiplied.
Is matrix multiplication commutative?
No. In general A × B is not equal to B × A, so the order of the matrices matters.
How many multiplications does this program do for two n × n matrices?
n³, because there are three nested loops of n steps each. For 3 × 3 matrices that is 27 multiplications.
What is the formula for C[i][j]?
C[i][j] is the sum of A[i][k] × B[k][j] for k from 0 to n − 1, that is, row i of A multiplied with column j of B.
In numpy, what is the difference between a * b and a @ b?
a * bmultiplies element by element.a @ b(ornumpy.dot(a, b)) is matrix multiplication.
Learn the concepts
- Python Lists: Create, Access, Change and Loop (Beginner Guide)
- Python for Loops in Depth: range, enumerate, zip, Dictionaries and for-else
- Python Functions: def, Parameters and return Explained Simply
- Python Comprehensions: List, Dict and Set Comprehensions Explained
- Python User Input: input(), Converting Numbers and Validating Answers