Mathematical Operations with Matrix in Python
Example 1: Adding values to a matrix with a for loop in python
Here, we are adding two matrices using the Python for-loop.
Python3
# Program to add two matrices using nested loop X = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] Y = [[ 9 , 8 , 7 ], [ 6 , 5 , 4 ], [ 3 , 2 , 1 ]] result = [[ 0 , 0 , 0 ], [ 0 , 0 , 0 ], [ 0 , 0 , 0 ]] # iterate through rows for row in range ( len (X)): # iterate through columns for column in range ( len (X[ 0 ])): result[row][column] = X[row][column] + Y[row][column] for r in result: print (r) |
Output:
[10, 10, 10] [10, 10, 10] [10, 10, 10]
Time Complexity: O(n*n)
Auxiliary Space: O(n*n)
Example 2: Adding and subtracting values to a matrix with list comprehension
Performing the Basic addition and subtraction using list comprehension.
Python3
Add_result = [[X[row][column] + Y[row][column] for column in range ( len (X[ 0 ]))] for row in range ( len (X))] Sub_result = [[X[row][column] - Y[row][column] for column in range ( len (X[ 0 ]))] for row in range ( len (X))] print ( "Matrix Addition" ) for r in Add_result: print (r) print ( "\nMatrix Subtraction" ) for r in Sub_result: print (r) |
Output:
Matrix Addition [10, 10, 10] [10, 10, 10] [10, 10, 10] Matrix Subtraction [-8, -6, -4] [-2, 0, 2] [4, 6, 8]
Time Complexity: O(n*n)
Auxiliary Space: O(n*n)
Example 3: Python program to multiply and divide two matrices
Performing the Basic multiplication and division using Python loop.
Python3
rmatrix = [[ 0 , 0 , 0 ], [ 0 , 0 , 0 ], [ 0 , 0 , 0 ]] for row in range ( len (X)): for column in range ( len (X[ 0 ])): rmatrix[row][column] = X[row][column] * Y[row][column] print ( "Matrix Multiplication" ,) for r in rmatrix: print (r) for i in range ( len (X)): for j in range ( len (X[ 0 ])): rmatrix[row][column] = X[row][column] / / Y[row][column] print ( "\nMatrix Division" ,) for r in rmatrix: print (r) |
Output:
Matrix Multiplication [9, 16, 21] [24, 25, 24] [21, 16, 9] Matrix Division [0, 0, 0] [0, 1, 1] [2, 4, 9]
Time Complexity: O(n*n)
Auxiliary Space: O(n*n)