Matrix Addition in Python Using NumPy

Matrix Addition in Python Using NumPy | Here, we will discuss matrix addition in python using NumPy. For adding any two matrices, both the matrices should be of the same dimension; We carry out the addition by adding corresponding elements together. Similar to the add operation, we can also implement other mathematical operations.

Matrix Addition in Python Using NumPy

Numpy is a library in python which has several functions that make it easy for the programmer to concentrate on the logic part. In this section, we use NumPy for the addition of two matrices in python. numpy.add() function is used when we want to compute the addition of two arrays. It adds arguments element-wise.

In the code, we have imported NumPy as np then declared matrix 1 and matrix 2 as m1 and m2 respectively by using numpy.add(). We add m1 and m2 and store the result in r.

Program description:- Write a python program to add two matrices using NumPy

import numpy as np
m1 = np.array([[3, 4], [5, 6]])
m2 = np.array([[8, 9], [0, 6]])
r = np.add(m1, m2)
print(r)

Output:-

[[11,13]
[5,12]]

By adding m1 [3,4] and [5,6] and m2 [8,9] and [0,6] we get [11,13] and [5,12].

Matrix Subtraction in Python using NumPy

In the previous program, we will add two matrices using NumPy but in this program, we will subtract two matrices using NumPy. The numpy.subtract() function is used when we want to compute the difference of two arrays. It returns the difference of arr1 and arr2, element-wise.

import numpy as np
m1 = np.array([[3, 4], [5, 6]])
m2 = np.array([[8, 9], [0, 6]])
r = np.subtract(m1, m2)
print(r)

Output:-

[[-5 -5]
[ 5 0]]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *