Python 中的矩阵操作
programmingpythonserver side programming更新于 2025/3/14 16:44:17
我们可以使用 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]]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

