Open In App

Adding and Subtracting Matrices in Python

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to add and subtract elements of the matrix in Python. 

Example:

Suppose we have two matrices A and B.
A = [[1,2],[3,4]]
B = [[4,5],[6,7]]

then we get
A+B = [[5,7],[9,11]]
A-B = [[-3,-3],[-3,-3]]

Now let us try to implement this using Python 

1. Adding elements of the matrix

In the above code, we have used np.add() method to add elements of two matrices. If shape of two arrays are not same, that is arr1.shape != arr2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

Python3




# importing numpy as np
import numpy as np
 
 
# creating first matrix
A = np.array([[1, 2], [3, 4]])
 
# creating second matrix
B = np.array([[4, 5], [6, 7]])
 
print("Printing elements of first matrix")
print(A)
print("Printing elements of second matrix")
print(B)
 
# adding two matrix
print("Addition of two matrix")
print(np.add(A, B))


Output:

Printing elements of first matrix
[[1 2]
 [3 4]]
Printing elements of second matrix
[[4 5]
 [6 7]]
Addition of two matrix
[[ 5  7]
 [ 9 11]]

2. Subtracting elements of matrices

In the above code, we have used np.subtract() to subtract elements of two matrices. It returns the difference of arr1 and arr2, element-wise.

Python3




# importing numpy as np
import numpy as np
 
 
# creating first matrix
A = np.array([[1, 2], [3, 4]])
 
# creating second matrix
B = np.array([[4, 5], [6, 7]])
 
print("Printing elements of first matrix")
print(A)
print("Printing elements of second matrix")
print(B)
 
# subtracting two matrix
print("Subtraction of two matrix")
print(np.subtract(A, B))


Output:

Printing elements of first matrix
[[1 2]
 [3 4]]
Printing elements of second matrix
[[4 5]
 [6 7]]
Subtraction of two matrix
[[-3 -3]
 [-3 -3]]

METHOD 3:Using nested loops

APPROACH:

The given task is to subtract two matrices in Python and print their elements. Approach 2 uses nested loops to subtract the two matrices. It prints the elements of both matrices using nested loops and then subtracts the corresponding elements of the matrices to get the result matrix.

ALGORITHM:

1. Define two matrices matrix1 and matrix2.
2.Print the elements of matrix1 and matrix2 using nested loops.
3. Define an empty matrix result of the same size as matrix1.
4. Subtract the corresponding elements of matrix1 and matrix2 using nested loops and store the result in the result matrix.
5. Print the result matrix.

Python3




# Input matrices
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[4, 5], [6, 7]]
 
# Printing elements of matrix1
print("Printing elements of first matrix")
for row in matrix1:
    for element in row:
        print(element, end=" ")
    print()
 
# Printing elements of matrix2
print("Printing elements of second matrix")
for row in matrix2:
    for element in row:
        print(element, end=" ")
    print()
 
# Subtracting two matrices
result = [[0, 0], [0, 0]]
for i in range(len(matrix1)):
    for j in range(len(matrix1[0])):
        result[i][j] = matrix1[i][j] - matrix2[i][j]
 
# Printing the result
print("Subtraction of two matrix")
for row in result:
    for element in row:
        print(element, end=" ")
    print()


Output

Printing elements of first matrix
1 2 
3 4 
Printing elements of second matrix
4 5 
6 7 
Subtraction of two matrix
-3 -3 
-3 -3 

Time complexity:

1. The time complexity of printing the matrices using nested loops is O(n^2), where n is the size of the matrices.
2. The time complexity of subtracting two matrices using nested loops is also O(n^2).
3. Therefore, the overall time complexity of this approach is O(n^2).
 

Space complexity:

1.The space complexity of this approach is O(n^2), as it requires three matrices of size n^2. The input matrices matrix1 and matrix2 require a space of n^2 each, and the result matrix requires a space of n^2.



Previous Article
Next Article

Similar Reads

Python | Convert LaTeX Matrices into SymPy Matrices using Python
A matrix is a rectangular two-dimensional array of data like numbers, characters, symbols, etc. which we can store in row and column format. We can perform operations on elements by using an index (i,j) where 'i' and 'j' stand for an index of row and column respectively. In the Python programming language, we can represent them in many formats like
5 min read
Date Calculator for adding and subtracting days Using Tkinter - Python
Prerequisite: Tkinter, tkcalendar in Tkinter, and DateTime Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI a
3 min read
PyQt5 QSpinBox – Subtracting region from Children Region
In this article we will see how we can subtract the region from children region of spin box, children region holds the combined region occupied by the spin box’s children. In order to get the children region we use childrenRegion method. Below is the representation of how subtracted region looks like. In order to do this we use subtracted method wi
2 min read
Python Program to Add Two Matrices
Given two matrices X and Y, the task is to compute the sum of two matrices and then print it in Python. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Output : result= [[10,10,10], [10,10,10], [10,10,10]]Add Two Matrices Using for loop Here we will use for loop with two matrices for adding the elements Python Cod
4 min read
Python program to add two matrices
Prerequisite : Arrays in Python, Loops, List Comprehension Program to compute the sum of two matrices and then print it in Python. We can perform matrix addition in various ways in Python. Here are a two of them. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Output : result= [[10,10,10], [10,10,10], [10,10,10]]U
2 min read
Python program to multiply two matrices
Given two matrix the task is that we will have to create a program to multiply two matrices in python. Examples: Input : X = [[1, 7, 3], [3, 5, 6], [6, 8, 9]] Y = [[1, 1, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] Output : [55, 65, 49, 5] [57, 68, 72, 12] [90, 107, 111, 21]Recommended: Please try your approach on {IDE} first, before moving on to the soluti
4 min read
Python List Equality | Program to check if two given matrices are identical
We are given two square matrices of same order. Check if two given matrices are identical. Examples: Input : A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] Output: Matrices are identical We have existing solution for this problem please refer C Program to check if two give
3 min read
Multiply matrices of complex numbers using NumPy in Python
In this article, we will discuss how to multiply two matrices containing complex numbers using NumPy but first, let's know what is a complex number. A Complex Number is any number that can be represented in the form of x+yj where x is the real part and y is the imaginary part. Multiplication of two complex numbers can be done using the below formul
2 min read
Python Program to multiply two matrices
Given two matrices, the task to multiply them. Matrices can either be square or rectangular. Examples: Input : mat1[][] = {{1, 2}, {3, 4}} mat2[][] = {{1, 1}, {1, 1}} Output : {{3, 3}, {7, 7}} Input : mat1[][] = {{2, 4}, {3, 4}} mat2[][] = {{1, 2}, {1, 3}} Output : {{6, 16}, {7, 18}}Recommended: Please solve it on "PRACTICE" first, before moving on
3 min read
Python Program for Kronecker Product of two matrices
Given a [Tex]{m} imes{n} [/Tex]matrix A and a [Tex]{p} imes{q} [/Tex]matrix B, their Kronecker product C = A tensor B, also called their matrix direct product, is an [Tex]{(mp)} imes{(nq)} [/Tex]matrix. A tensor B = |a11B a12B| |a21B a22B| = |a11b11 a11b12 a12b11 a12b12| |a11b21 a11b22 a12b21 a12b22| |a11b31 a11b32 a12b31 a12b32| |a21b11 a21b12 a22
3 min read
three90RightbarBannerImg