Dark Mode On/Off

# Python Program to Add and Subtract Matrices

In this tutorial, we will learn to add and subtract matrices in Python. A matrix is a two-dimensional data structure where numbers are arranged into rows and columns. For subtracting and adding the matrices, the corresponding elements of the matrix should be subtracted or added.

Python does not have a built-in type for matrices but we can treat a nested list or list of a list as a matrix. Elements are the values inside the list. For example,

Look at the sample input and output for the program

Input:

A = [[3, 1], [5, 10]]

B = [[2, 6], [4, 1]]

Output:

A+B = [[5, 7], [9, 11]]

A-B = [[1, -5], [1, 9]]

To add and subtract the matrices, we can use nested loops which will operate on the elements in the matrices, but this is very time taking. To know how to use nested loops for matrix addition refer to this article.

A faster approach is to use the NumPy package in Python. It also gives an optimized solution. We will be discussing, how to use NumPy in this tutorial.

It is an open-source Python library that has many built-in functions for performing operations on multidimensional and single-dimensional array elements.

For adding two matrices, we will use the add() function in `NumPy` which will add the two matrices and return the result.

### Algorithm

Follow the algorithm to understand how to use this function.

Step 1- Import NumPy into the program

Step 2- Declare matrix 1 and give values

Step 3- Declare matrix 2 and give values

Step 4- Call the add() function

Step 5- Print the result

### Python Program 1

Look at the python program to add two matrices.

``````#Add two matrices

import numpy

# Matrix 1
A=[ [1, 2, 3], [3, 4, 5], [6, 7, 8] ]

# Matrix 2
B=[ [5, 6, 7], [1, 2, 3], [5, 3, 8] ]

print("Result: ")

Result:
[[ 6 8 10]
[ 4 6 8]
[11 10 16]]

## Subtracting Matrices

For subtracting two matrices, we will use the subtract() function in NumPy which will subtract the two matrices and return the result.

### Algorithm

Follow the algorithm to understand how to use this function.

Step 1- Import NumPy into the program

Step 2- Declare matrix 1 and give values

Step 3- Declare matrix 2 and give values

Step 4- Call the subtract() function

Step 5- Print the result

### Python Program 2

Look at the Python program to subtract two matrices.

``````#subtract two matrices
import numpy

# matrix 1
A=[ [1, 2, 3], [3, 4, 5], [6, 7, 8] ]

# matrix 2
B=[ [5, 6, 7], [1, 2, 3], [5, 3, 8] ]

print("Result: ")
print(numpy.subtract(A,B))``````

Result:
[[-4 -4 -4]
[ 2 2 2]
[ 1 4 0]]

## Conclusion

In this tutorial, we have learned about the NumPy module and the two functions in it- add() and subtract(). We have also seen how we can use these functions for adding and subtracting elements.