Matrix subtraction without NumPy in python

In this tutorial let’s write an introduction explaining what we’ll be doing. Then, we’ll move on to creating a 2D array and writing without using the NumPy library in Python. Finally, we’ll discuss the output of our code and provide a conclusion.

In this type of situation, we will go with a few steps.

Introduction:

In this task, we will focus on matrix subtraction without using the NumPy library in Python. matrix subtraction includes subtracting corresponding elements of 2 matrices having the same number of rows and columns. We will implement this operation using basic Python constructs.

First, we know how to write code in Python without using NumPy?
To perform matrix subtraction without using NumPy in Python, we can use nested loops.

 

Matrix subtraction without NumPy in Python

First, let’s create 2D array or matrix that we can use for our example. A 2D is essentially an Array of Arrays where each element represents a row and column position in a matrix.

Here is an example of how you can create a 2D array in Python.

Algorithm :

  • Define two matrices ‘matrix1’ and ‘matrix2’.
  • create an empty result to store the result matrix.
  • Subtract the corresponding elements of ‘matrix2’ and ‘matrix1’ and store the result in ‘result’ .
  • print each row of the result list.

 

matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]

result = []

for i in range(len(matrix1)):
    row = []
    for j in range(len(matrix1[0])):
        row.append(matrix1[i][j] - matrix2[i][j])
    result.append(row)

for row in result:
     print(row)

 

 

OUTPUT :

[-4, -4]

Explanation of the code:

1. We define two matrices matrix1 and matrix, which  represent the matrices to be subtracted.

2. We create an empty array result to store the row values i.e. all rows combined to give us a resultant matrix.

3. We use nested loops to reach each element in the matrices.

4. Inside the inner loop, we subtract corresponding elements from both matrices and append the result to a temporary row list.

5. After completing a row, we add it to the result matrix.

6. Finally, we print each row of the result matrix.

Conclusion:

In this example, we successfully performed matrix subtraction without using NumPy in Python. By iterating over each element of the matrices and subtracting them individually, we were able to obtain a new matrix with the same dimensions as the original matrices.

Time Complexity :

Time complexity is O(n^2).

Here ‘n’ represents the number of rows or columns.

Space Complexity :

Space complexity is O(n^2).

Here ‘n’ represents the number of rows or columns.

Also read: Set Diagonal of 3×3 Matrix as inf in Python

Leave a Reply

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