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.
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] ]
Contents of Tutorial
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
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)): # iterate through columns for j in range(len(A)): result[i][j] = A[i][j] + B[i][j] for x in result: print(x)
[10,10,10] [10,10,10] [10,10,10]
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
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))] for i in range(len(A))] for r in result: print(r)
[10,10,10] [10,10,10] [10,10,10]
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
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)
[[10, 10, 10], [10, 10, 10], [10, 10, 10]]
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
import numpy as np import random # Routine for printing a 2x2 matrix def PrintMatrix(matrix_in): for x in range(0, matrix_in.shape): for y in range(0, matrix_in.shape): 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): for y in range(0, matrix_in.shape): 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)
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
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.
- 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
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.