Matrix subtraction in Python
In this post, you will learn different ways to perform matrix subtraction using the Python programming language.
Matrix, a set of numbers arranged in rows and columns so as to form a rectangular array. Matrices are utilised substantially more in everyday life than individuals would have suspected. A square matrix can represent a linear transformation of a geometric object. A real-life example is Adobe Photoshop. It uses matrices to process linear transformations to render images. In robotics and automation, matrices are the fundamental segments for the robot developments. The contributions for controlling robots are acquired depending on the calculations from matrices.
The different operations on matrix are also very important for us. There are the different ways to perform matrix subtraction in Python.
Matrix subtraction in Python using Nested Loop
A nested loop is a loop inside a loop. The following Python program uses a nested for loop to perform matrix subtraction.
# Program to add two matrices using nested loop
x = [[4,2,1],
[6,12,20],
[5,14,22]]
y = [[0,1,6],
[8,4,12],
[5,5,11]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(x)):
# iterate through columns
for j in range(len(x[0])):
result[i][j] = x[i][j] - y[i][j]
for r in result:
print(r)
Output of the above code:
[4, 1, -5]
[-2, 8, 8]
[0, 9, 11]
Matrix subtraction in Python using Nested List Comprehension
Nested List Comprehensions are nothing but a list comprehension within another list comprehension. It is quite similar to nested loop. The following Python program uses a nested list comprehension to perform matrix subtraction.
# Program to add two matrices using nested loop
x = [[12,1,2],
[9,11,17],
[4,10,20]]
y = [[0,2,6],
[8,4,13],
[5,5,11]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
result = [[x[i][j] - y[i][j]
for j in range(len(x[0]))]
for i in range(len(x))]
for r in result:
print(r)
Output of the above code
[12, -1, -4]
[1, 7, 4]
[-1, 5, 9]
Related Articles
Transpose of a matrix in python
Python program to multiply two matrices
Matrix addition in Python
Python program to multiply two matrices
Python Numpy Array Shape
Python Pandas Dataframe to CSV
Inverse of a matrix in Python
Remove element from list Python
Python iterate list with index
Python program to sum all the numbers in a list
Python print without newline
2d arrays in Python
Python add list to list
Python convert xml to dict
Python dict inside list
Multiply all elements in list Python
Python heap implementation using heapq module
numpy dot product
Python convert dict to xml
Python weather api
Python raise keyword