Computer >> Máy Tính >  >> Lập trình >> Python

Thao tác ma trận trong Python

Trong Python, chúng ta có thể giải quyết các thao tác và thao tác ma trận khác nhau. Mô-đun Numpy cung cấp các phương pháp khác nhau cho các hoạt động của ma trận.

thêm () - thêm các phần tử của hai ma trận.

trừ () - trừ các phần tử của hai ma trận.

chia () - chia các phần tử của hai ma trận.

nhân () - nhân các phần tử của hai ma trận.

dấu chấm () - Nó thực hiện phép nhân ma trận, không thực hiện phép nhân khôn ngoan.

sqrt () - căn bậc hai của mỗi phần tử của ma trận.

sum (x, axis) - thêm vào tất cả các phần tử trong ma trận. Đối số thứ hai là tùy chọn, nó được sử dụng khi chúng ta muốn tính tổng cột nếu trục là 0 và tổng hàng nếu trục là 1.

“T” - Nó thực hiện chuyển vị của ma trận được chỉ định.

Mã mẫu

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)

Đầu ra

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]]
The product of two matrices :
[[25 28]
 [73 82]]
square root is :
[[1.         1.41421356]
 [2.         2.23606798]]
The summation of elements :
34
The column wise summation  :
[16 18]
The row wise summation: 
[15 19]
Matrix transposition :
[[1 4]
[2 5]]