20/01/2025, 08:56 matrixOperations.
ipynb - Colab
import numpy as np
Declaring matrices
mx1 = np.array([[5, 10], [15, 20]])
mx2 = np.array([[25, 30], [35, 40]])
print("Matrix1 =\n",mx1)
print("\nMatrix2 =\n",mx2)
Matrix1 =
[[ 5 10]
[15 20]]
Matrix2 =
[[25 30]
[35 40]]
Addition using Numpy methods
print ("\nAddition of two matrices: ")
print (np.add(mx1,mx2))
Addition of two matrices:
[[30 40]
[50 60]]
Subtraction using Numpy methods
print ("\nSubtraction of two matrices: ")
print (np.subtract(mx1,mx2))
Subtraction of two matrices:
[[-20 -20]
[-20 -20]]
Division using Numpy methods
print ("\nMatrix Division: ")
print (np.divide(mx1,mx2))
Matrix Division:
[[0.2 0.33333333]
[0.42857143 0.5 ]]
Multiplication using Numpy methods
print ("\nMultiplication of two matrices: ")
print (np.multiply(mx1,mx2))
Multiplication of two matrices:
[[125 300]
[525 800]]
Optimized methods of multiplication
mx1 @ mx2
array([[ 475, 550],
[1075, 1250]])
np.matmul (mx1, mx2)
array([[ 475, 550],
[1075, 1250]])
np.dot (mx1, mx2)
https://colab.research.google.com/drive/1Pq2FoFKTTyCEL6emTRoWvVZV36n4dtDA#scrollTo=uaOrKLWQvlcA&printMode=true 1/3
20/01/2025, 08:56 matrixOperations.ipynb - Colab
array([[ 475, 550],
[1075, 1250]])
Summation of Matrix
mx = np.array([[5, 10], [15, 20]])
print("Matrix =\n",mx)
print ("\nThe summation of elements=")
print (np.sum(mx))
print ("\nThe column wise summation=")
print (np.sum(mx,axis=0))
print ("\nThe row wise summation=")
print (np.sum(mx,axis=1))
Matrix =
[[ 5 10]
[15 20]]
The summation of elements=
50
The column wise summation=
[20 30]
The row wise summation=
[15 35]
Transpose of Matrix
mx = np.array([[5, 10], [15, 20]])
print("Matrix =\n",mx)
print ("\nThe Transpose =")
print (mx.T)
Matrix =
[[ 5 10]
[15 20]]
The Transpose =
[[ 5 15]
[10 20]]
keyboard_arrow_down Numpy method is also available
np.transpose (mx)
array([[ 5, 15],
[10, 20]])
keyboard_arrow_down Inverse of a matrix
np.linalg.inv (mx)
array([[-0.4, 0.2],
[ 0.3, -0.1]])
Start coding or generate with AI.
https://colab.research.google.com/drive/1Pq2FoFKTTyCEL6emTRoWvVZV36n4dtDA#scrollTo=uaOrKLWQvlcA&printMode=true 2/3