Matrix Addition and Subtraction in Python

Matrix Addition and Subtraction in Python | Here, we will discuss matrix addition and subtraction in python. For adding and subtracting 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.

We will see these below topics:

  1. Matrix Addition And Subtraction In Python Using Numpy
  2. Matrix Addition And Subtraction In Python User Input
  3. Matrix Addition And Subtraction In Python Using Function
  4. Matrix Addition And Subtraction In Python Using Nested Loop

Python Program to Add and Subtract Two Matrices 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 and subtraction of two matrices in python. 

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() and numpy.subtract(). We add and subtract  m1 and m2 and store the result in r.

Program description:- Write a python program to add and subtract two matrices

# Python program to add and subtract two matrices

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

print("Add Matrix:")
a = np.add(m1, m2)
print(a)

print("Subtract Matrix:")
b = np.subtract(m2, m1)
print(b)

Output:-

Add Matrix:
[[ 9 9 13]
[17 5 12]]
Subtract Matrix:
[[ 7 3 5]
[ 1 -5 0]]

Matrix Addition and Subtraction in Python User Input

Here we add and subtract matrices by taking user input, we use a list and map. We use lists to store multiple items of a single variable, it is one of the data types in python. A map is an inbuilt function that allows us to process and transform all the items in an iterable without using a loop.

# Python program to add and subtract two matrix

# take first matrix inputs
m1 = [list(map(int, input("Enter row: ").split(" ")))
      for i in range(int(input("Enter Number of rows: ")))]

# take second matrix inputs
m2 = [list(map(int, input("Enter row: ").split(" ")))
      for i in range(int(input("Enter Number of rows:")))]

# add these matrix
print("Add Matrix:")
r = [[m1[i][j] + m2[i][j]
      for j in range(len(m1[0]))] for i in range(len(m1))]
print(r)

# subtract these matrix
print("Subtract Matrix:")
r = [[m1[i][j] - m2[i][j]
      for j in range(len(m1[0]))] for i in range(len(m1))]
print(r)

Output:-

Enter Number of rows: 2
Enter row: 9 8
Enter row: 7 6
Enter Number of rows:2
Enter row: 5 4
Enter row: 3 2
Add Matrix:
[[14, 12], [10, 8]]
Subtract Matrix:
[[4, 4], [4, 4]]

In the above code, we first take the matrix from the user and store it in m1, then similarly we take m2 and we read all the row elements as well. Then we add and subtract both the matrix and put it in the result. While adding and subtracting, we use a for loop to check whether the dimension is the same or not. 

In the output shown first it takes the number of rows for matrix 1 and reads the matrix elements similarly it is done for matrix 2 then it adds, subtracts, and gives the result.

Matrix Addition and Subtraction in Python using Function

In python we can define our own function, so by using this we can add and subtract two matrices. Here in the below code, we have defined a function called add() and subtract() which takes two parameters m1 and m2.

def add(m1, m2):
   new = []
   for i in range(0, len(m1)):
      new.append(m1[i] + m2[i])
   return new

def subtract(m1, m2):
   new = []
   for i in range(0, len(m1)):
      new.append(m1[i] - m2[i])
   return new

# main
m1 = [[9, 2], [2, 5]]
m2 = [[1, 4], [0, 3]]
c = []
for i in range(0, len(m1)):
   c.append(add(m1[i], m2[i]))
print("Add Matrix:")
print(c)

c = []
for i in range(0, len(m1)):
   c.append(subtract(m1[i], m2[i]))
print("Subtract Matrix:")
print(c)

Output:-

Add Matrix:
[[10, 6], [2, 8]]
Subtract Matrix:
[[8, -2], [2, 2]]

In the add() and subtract() function, we initiate new to an empty array, then we append new to the addition and subtraction of matrix 1 and matrix2. Then in the main function, we take two matrices and then call add() and subtract() to add and subtract the matrices and store them in c. 

Matrix Addition Program in Python using a Nested Loop

A nested loop is a loop inside another loop. In this example, we use nested for-loops to add and subtract matrices.

Program description:- Python program to add and subtract two matrices taking input from a user

# Python program to add and subtract two matrices

r = int(input("Enter the rows: "))
c = int(input("Enter the columns: "))

print("Enter Matrix 1:")
m1 = [[int(input()) for i in range(c)] for i in range(r)]
print("Matrix 1 is: ")
for n in m1:
   print(n)

print("Enter Matrix 2:")
m2 = [[int(input()) for i in range(c)] for i in range(r)]
for n in m2:
   print(n)

r = [[0 for i in range(c)] for i in range(r)]
for i in range(len(r)):
   for j in range(c):
      r[i][j] = [m1[i][j] + m2[i][j]]
print("Add Matrix:")
for i in r:
   print(i)

for i in range(len(r)):
   for j in range(c):
      r[i][j] = [m1[i][j] - m2[i][j]]
print("Subtract Matrix:")
for i in r:
   print(i)

Output:

Enter the rows: 2
Enter the columns: 2
Enter Matrix 1:
9
8
7
6
Matrix 1 is:
[9, 8]
[7, 6]
Enter Matrix 2:
5
4
3
2
[5, 4]
[3, 2]
Add Matrix:
[[14], [12]]
[[10], [8]]
Subtract Matrix:
[[4], [4]]
[[4], [4]]

In the above code, we have used a nested for loop to add m1 and m2. The outer loop reads the row elements the inner loop reads the column elements and stores the result in r.

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 *