Python 进行矩阵操作
我们可以使用Numpy库来轻松进行Python中的矩阵操作。NumPy是一个Python包。它代表’Numerical Python’。这是一个由多维数组对象和一组用于处理数组的例程组成的库。使用NumPy可以进行数组的数学和逻辑运算。
安装和导入Numpy
要安装Numpy,请使用pip −
pip install numpy
导入Numpy –
import numpy
添加、减去、除以和乘以矩阵
我们将使用以下的NumPy方法进行矩阵操作−
- numpy.add() − 添加两个矩阵
-
numpy.subtract() − 减去两个矩阵
-
numpy.divide() − 除以两个矩阵
-
numpy.multiply() − 乘以两个矩阵
现在让我们看一下代码 −
示例
import numpy as np
# Two matrices
mx1 = np.array([[5, 10], [15, 20]])
mx2 = np.array([[25, 30], [35, 40]])
print("Matrix1 =\n",mx1)
print("\nMatrix2 =\n",mx2)
# The addition() is used to add matrices
print ("\nAddition of two matrices: ")
print (np.add(mx1,mx2))
# The subtract() is used to subtract matrices
print ("\nSubtraction of two matrices: ")
print (np.subtract(mx1,mx2))
# The divide() is used to divide matrices
print ("\nMatrix Division: ")
print (np.divide(mx1,mx2))
# The multiply()is used to multiply matrices
print ("\nMultiplication of two matrices: ")
print (np.multiply(mx1,mx2))
输出
Matrix1 =
[[ 5 10]
[15 20]]
Matrix2 =
[[25 30]
[35 40]]
Addition of two matrices:
[[30 40]
[50 60]]
Subtraction of two matrices:
[[-20 -20]
[-20 -20]]
Matrix Division:
[[0.2 0.33333333]
[0.42857143 0.5 ]]
Multiplication of two matrices:
[[125 300]
[525 800]]
矩阵元素的求和
sum()方法用于找到求和结果-
示例
import numpy as np
# A 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]
转置矩阵
.T属性用于找到矩阵的转置-
示例
import numpy as np
# A 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]]