English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Matrix processing in Python

In Python, we can solve different matrix operations and calculations. The Numpy module provides different methods for matrix operations.

add() -Add the elements of two matrices.

Subtract() -Subtract the elements of two matrices.

split() -Divide the elements of two matrices.

Multiplication() -Multiply the elements of two matrices.

dot() -It performs matrix multiplication rather than element-wise multiplication.

sqrt() -The square root of each element in the matrix.

sum(x,axis) -It adds all elements to the matrix. The second parameter is optional, when we want to calculate the column sum for axis 0, and axis1It is used when you need to calculate the row sum.

“ T” -Execute the transpose of the specified matrix.

Example code

import numpy
# Two matrices are initialized by value
x = numpy.array([1, 2], [4, 5]])
y = numpy.array([7, 8], [9, 10]])
# add() is used to add matrices
print ("Addition of two matrices:")
print (numpy.add(x,y))
# subtract() is used to subtract matrices
print ("Subtraction of two matrices:")
print (numpy.subtract(x,y))
# divide() is used to divide matrices
print("Matrix Division : ")
print(numpy.divide(x,y))
print("Multiplication of two matrices: ")
print(numpy.multiply(x,y))
print("The product of two matrices : ")
print(numpy.dot(x,y))
print("square root is : ")
print(numpy.sqrt(x))
print("The summation of elements : ")
print(numpy.sum(y))
print("The column-wise summation  : ")
print(numpy.sum(y,axis=0))
print("The row-wise summation: ")
print(numpy.sum(y,axis=1))
# using "T" to transpose the matrix
print("Matrix transposition : ")
print(x.T)

Output Result

Addition of two matrices : 
[[ 8 10]
 [13 15]]
Subtraction of two matrices :
[[-6 -6]
 [-5 -5]]
Matrix Division :
[[0.14285714 0.25      ]
 [0.44444444 0.5       ]]
Multiplication of two matrices: 
[[ 7 16]
 [36 50]]
Product of two matrices :
[[25 28]
 [73 82]]
Square root is :
[[1.         1.41421356]
 [2.         2.23606798]]
Summation of elements :
34
Column-wise summation  :
[16 18]
Row-wise summation: 
[15 19]
Matrix transposition :
[[1 4]
[2 5]]