Python Program to Add Two Matrices
Beginner · Matrices
Two matrices can be added when they have the same number of rows and columns. Each entry of the result is the sum of the entries in the same position, so result[i][j] = A[i][j] + B[i][j]. This program adds two 3 x 3 matrices with nested loops and prints all three, row by row.
Program
Matrix A: 1 2 3 4 5 6 7 8 9 Matrix B: 5 1 0 2 7 3 4 6 8 A + B: 6 3 3 6 12 9 11 14 17
How it works
- A matrix is stored as a list of rows, so
A[i][j]is the entry in rowi, columnj. - The outer loop goes through the rows and the inner loop through the columns of each row.
- Each pair of matching entries is added and appended to
row, and each finishedrowis appended toresult. print_matrix()prints each row on its own line, and{value:4}gives every number four spaces so the columns line up.
Other ways to write it
Using zip() and a list comprehension
A + B: [6, 3, 3] [6, 12, 9] [11, 14, 17]
The outer zip() pairs up the rows of A and B, and the inner one pairs up the numbers in each pair of rows.
Subtracting two matrices
A - B: [-4, 1, 3] [2, -2, 3] [3, 2, 1]
Subtraction works the same way, entry by entry, with - instead of +.
Try it yourself
Add a check that prints a message when the two matrices do not have the same number of rows and columns.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises