Python 矩阵和数组之间的区别
在Python中,数组是ndarray(多维数组)对象。矩阵对象严格为二维,而ndarray对象可以是多维的。要创建数组,可以使用Numpy库。
Python中的矩阵
矩阵是限定每个数据元素严格相同大小的二维数组的特例。矩阵是许多数学和科学计算的关键数据结构。每个矩阵也是二维数组,但反之则不一定成立。矩阵对象是ndarray的子类,因此它们继承了所有ndarrays的属性和方法。
示例
创建一个矩阵并显示
from numpy import *
# Create a Matrix
mat = array([['A',12,16],['B',11,13],
['C',20,19],['D',22,21],
['E',18,22],['F',12,18]])
# Display the Matrix
print("Matrix = \n",mat)
输出
Matrix =
[['A' '12' '16']
['B' '11' '13']
['C' '20' '19']
['D' '22' '21']
['E' '18' '22']
['F' '12' '18']]
示例
使用mat()函数创建矩阵
mat()函数将输入解释为矩阵-
import numpy as np
# Create a Matrix
mat = np.mat([[5,10],[15,20]])
# Display the Matrix
print("Matrix = \n",mat)
输出
Matrix =
[[ 5 10]
[15 20]]
Python中的数组
数组是一个容器,可以容纳固定数量的项目,这些项目应该是相同类型的。要在Python中使用数组,请导入NumPy库。
示例
import numpy as np
# Create an array
arr = np.array([5, 10, 15, 20])
# Display the Array
print("Array =\n")
for x in arr:
print(x)
输出
Array =
5
10
15
20
使用Numpy数组进行矩阵运算
根据官方文档,numpy.matrix类将在未来被移除。因此,现在必须使用Numpy数组来进行矩阵代数运算。
示例
现在让我们通过数组创建一个矩阵-
import numpy as np
# Create Matrices
mat1 = np.array([[5,10],[3,9]])
mat2 = np.array([[15,20],[10,11]])
# Display the Matrices
print("Matrix1 = \n",mat1)
print("Matrix2 = \n",mat2)
输出
Matrix1 =
[[ 5 10]
[ 3 9]]
Matrix2 =
[[15 20]
[10 11]]
示例
让我们将上述矩阵相乘 –
import numpy as np
# Create Matrices
mat1 = np.array([[5,10],[3,9]])
mat2 = np.array([[15,20],[10,11]])
# Display the Matrices
print("Matrix1 = \n",mat1)
print("Matrix2 = \n",mat2)
mulMat = mat1@mat2
print("\nMatrix Multiplication = \n",mulMat)
输出
Matrix1 =
[[ 5 10]
[ 3 9]]
Matrix2 =
[[15 20]
[10 11]]
Matrix Multiplication =
[[175 210]
[135 159]]
示例
获取转置 –
import numpy as np
# Create Matrices
mat1 = np.array([[5,10],[3,9]])
mat2 = np.array([[15,20],[10,11]])
# Display the Matrices
print("Matrix1 = \n",mat1)
print("Matrix2 = \n",mat2)
mulMat = mat1@mat2
print("\nTranspose = \n",mulMat.T)
输出
Matrix1 =
[[ 5 10]
[ 3 9]]
Matrix2 =
[[15 20]
[10 11]]
Transpose =
[[175 135]
[210 159]]