Hello Programmers, today’s article is about matrix addition in python. We will discuss different ways of adding two matrices in python. Matrix addition in python means adding up the elements of one matrix with another. The added up elements are then stored in a third matrix.
Matrix addition in Python is a technique by which you can add two matrixes of the same shape. If the matrices don’t have the same shape, the addition will not be possible. Moreover, the addition in matrices works one way, which means that the (1,1) element will only add to (1, 1) element of another matrix.
Before we start with different ways of matrix addition, let me just cite an example of matrix addition for you.
Let A and B be two matrices which are added and the result is stored in a new matrix C.
A = [ [1, 2, 3], [4, 5, 6] ] B = [ [6, 5, 4], [3, 2, 1] ] C = [ [7, 7, 7], [7, 7, 7] ]
The elements of C matrix are sum of the elements of A and B matrix i.e.,
[ [1+6, 2+5, 3+4], [4+3, 5+2, 6+1] ]
Different ways of matrix addition in python:
- Using Nested for loop
- Use of Nested list Comprehension
- With sum and zip() function
- Using NumPy
Matrix Addition using Nested for loop
EXAMPLE:
<pre class="wp-block-syntaxhighlighter-code">A = [[1,2,3],
[4,5,6],
[7 ,8,9]]
B = [[9,8,7],
[6,5,4],
[3,2,1]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(A)):
# <a href="https://www.pythonpool.com/python-iterate-through-list/" target="_blank" rel="noreferrer noopener">iterate</a> through columns
for j in range(len(A[0])):
result[i][j] = A[i][j] + B[i][j]
for x in result:
print(x) </pre>
OUTPUT:
[10,10,10]
[10,10,10]
[10,10,10]
EXPLANATION:
In this example, nested for loops are used to iterate through each row and columns of the given matrices. After each iteration, we add the corresponding elements of the A and B matrix. And store the sum in the third matrix called result.
Using Nested List Comprehension method
EXAMPLE:
A = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
B = [[9,8,7],
[6,5,4],
[3,2,1]]
result = [[A[i][j] + B[i][j] for j in range
(len(A[0]))] for i in range(len(A))]
for r in result:
print(r)
OUTPUT:
[10,10,10]
[10,10,10]
[10,10,10]
EXPLANATION:
List comprehension means nested list, i.e., list inside a list. This method is used to implement a matrix as a nested list. In this example, list comprehension is used for iterating through each element of the given matrices. List comprehension method of matrix addition in python helps writing concise and to the point codes. Thus, it makes the codes of matrix addition simpler and helpful.
Matrix Addition with Sum and zip() function
EXAMPLE:
A = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
B = [[9,8,7],
[6,5,4],
[3,2,1]]
result = [map(sum, zip(*i)) for i in zip(X, Y)]
print(result)
OUTPUT:
[[10, 10, 10], [10, 10, 10], [10, 10, 10]]
EXPLANATION:
The zip() function’s function is to accept iterator of each element of the matrix, map them, and add them using the sum() function. It returns and stores the result in the mapping form.
Matrix addition using NumPy
EXAMPLE:
import numpy as np
import random
# Routine for printing a 2x2 matrix
def PrintMatrix(matrix_in):
for x in range(0, matrix_in.shape[0]):
for y in range(0, matrix_in.shape[1]):
print("%d \t"%(matrix_in[x][y]), end=''
if(y%3>1):
print("\n")
# Function to populate a 2x2 matrix with random data
def FillMatrix(matrix_in):
for x in range(0, matrix_in.shape[0]):
for y in range(0, matrix_in.shape[1]):
matrix_in[x][y] = random.randrange(2, 10) + 2
# Create matrices using ndarray
matrix1 = np.ndarray((3,3))
matrix2 = np.ndarray((3,3))
# Fill the matrices i.e., the two dimensional arrays created using ndarray objects
FillMatrix(matrix1)
FillMatrix(matrix2)
# Add two matrices - two nd arrays
add_results = matrix1.__add__(matrix2)
# Print Matrix1
print("Matrix1:")
PrintMatrix(matrix1)
# Print Matrix2
print("Matrix2:")
PrintMatrix(matrix2)
# Print the results of adding two matrices
print("Result of adding Matrix1 and Matrix2:")
PrintMatrix(add_results)
OUTPUT:
Matrix1:
[1 2 3
4 5 6
7 8 9]
Matrix2:
[9 8 7
6 5 4
3 2 1]
Result of adding Matrix1 and Matrix2:
[10 10 10
10 10 10
10 10 10]
EXPLANATION:
The first condition for adding two matrices is that both the matrices should have the same number of rows and columns. The result thus obtained also has the same number of rows and columns. The ndarray of the NumPy module helps create the matrix. The method __add__() provided by the ndarray of the NumPy module performs the matrix addition . The __add__ () function adds two ndarray objects of the same shape and returns the sum as another ndarray object.
Must Read
- Introduction to Python Super With Examples
- Python Help Function
- Why is Python sys.exit better than other exit functions?
- Python Bitstring: Classes and Other Examples | Module
Conclusion:
This article gives an insight into different ways of matrix addition in python. You can use any of the above ways as per your need and convenience. Using List Comprehension is one of the simplest and concise methods of matrix addition. This method is helpful and must be included quite frequently in python programs.
Still have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.
Happy Pythoning!