The addition is one of the most basic operations that we perform on two or more matrices. The only condition to add or subtract two matrices is that both should have the same dimensions which means both matrices should have the same number of rows and columns.
Now to add two matrices just add the corresponding entries and place the sum at the corresponding position in the resultant matrix.
Suppose A = [aij]mxn
and B = [bij]mxn
are two matrices of order m x n, then the addition of A and B is given by;
A + B = [aij]mxn + [bij]mxn = [aij + bij]mxn
In this article, you will see the python code to add two matrices.
Python program for addition of two matrices
There are multiple ways in which you can perform the same task using programming. The two most common methods to add matrices in Python are given below.
- Using nested for loop
- Using list comprehension
Using nested for loop
Here we will iterate through all the elements of both matrices by using nested for loop one by one, adding them, and storing each element at their corresponding positions in a third matrix.
# Python program to add two matrices using nested for loops
matrix1 = [[1,0,-1],
[3 ,8,6],
[6 ,9,2]]
matrix2 = [[0,2,4],
[7,-9,3],
[4,0,1]]
matrix_sum = [[0,0,0],
[0,0,0],
[0,0,0]]
# Iterate through matrix rows
for i in range(len(matrix1)):
# Iterate through matrix columns
for j in range(len(matrix1[0])):
# Addition of matrix elements
matrix_sum[i][j] = matrix1[i][j] + matrix2[i][j]
for r in matrix_sum:
print(r)
print("\n")
Save this file with the .py extension and then run this program you will see the given output :
Using list comprehension
This method provides a shorter way to do the same task. Here we will use list comprehension to add two matrices.
# Python program to add two matrices using list comprehension
matrix1 = [[1,8,3],
[0 ,-5,7],
[7 ,0,5]]
matrix2 = [[0,6,1],
[6,9,0],
[1,2,9]]
# Addition of matrix elements
matrix_sum = [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))] for i in range(len(matrix1))]
for r in matrix_sum:
print(r)
You will see the given output in your terminal –
So I hope now you are able to add two matrices using Python code. If you have a query or feedback then write us in the comments below.