1.快速构造一个矩阵
a = np.zeros(shape=(3, 5), dtype=int)
print(a)
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]]
a = np.ones(shape=(2, 4), dtype=int)
print(a)
[[1 1 1 1]
[1 1 1 1]]
a = np.full((3, 5), 666)
print(a)
[[666 666 666 666 666]
[666 666 666 666 666]
[666 666 666 666 666]]
- 构造一个3*5,元素是[0,10)之间随机数的矩阵
a = np.random.randint(0, 10, (3, 5))
print(a)
[[7 5 0 9 3]
[7 3 9 8 7]
[9 1 6 9 7]]
- 构造一个3*5,所有元素符合均值为0,方差为1的正态分布的随机数的矩阵
a = np.random.normal(0, 1, (3, 5))
print(a)
[[ 0.43121389 -1.45724221 0.84369408 -1.62208387 0.42111614]
[-2.70974994 0.46920864 1.48373216 -1.72006643 -0.29006381]
[-0.70056842 0.22743593 0.6276454 -0.78630736 -1.17294585]]
b = np.mat(np.eye(3, 3, dtype=int))
print(b)
# 生成一个3*3的对角矩阵
[[1 0 0]
[0 1 0]
[0 0 1]]
b = np.mat(np.diag([1, 2, 3]))
print(b)
[[1 0 0]
[0 2 0]
[0 0 3]]
2.矩阵的常用操作
a = np.mat([[1, 1, 1], [2, 3, 6], [4, 5, 7]])
[[1 1 1]
[2 3 6]
[4 5 7]]
print(a.ndim) # 查询几维数组 2
print(a.shape) # 查询几行几列 (3, 3)
print(a.size) # 查询元素个数 9
print(a[1, 1]) # 输出1行1列(0开始算起)元素 3
print(a.max()) # 计算矩阵中最大元素 7
print(max(a[:, 1])) # 计算第一列中的最大值,得到的是矩阵 [[5]]
print(a[1, :].max()) # 计算第二行的最大值,得到一个数 6
print(np.max(a, 0)) # 计算所有列的最大值
[[4 5 7]]
print(np.max(a, 1)) # 计算所有行的最大值
[[1]
[6]
[7]]
print(np.argmax(a, 0)) # 求所有列的最大值的索引
[[2 2 2]]
print(np.argmax(a[1, :])) # 计算第二行的最大值在该行的索引 2
print(a[:2, :2]) # 从原矩阵中分割出(0-2)*(0-2)的子矩阵
[[1 1]
[2 3]]
d1 = np.mat(np.ones((2, 2)))
d2 = np.mat(np.eye(2))
print(d1, d2)
[[1. 1.]
[1. 1.]]
[[1. 0.]
[0. 1.]]
d3 = np.vstack((d1, d2)) # 两个矩阵按列合并
print(d3)
[[1. 1.]
[1. 1.]
[1. 0.]
[0. 1.]]
d4 = np.hstack((d1, d2))
print(d4) # 按行合并
[[1. 1. 1. 0.]
[1. 1. 0. 1.]]
3.矩阵的运算
b1 = np.mat([1, 2, 3])
b2 = np.mat([[3], [2], [1]])
print(b1, b2)
b = b1 * b2
print(b)
[[1 2 3]]
[[3]
[2]
[1]]
[[10]]
b1 = np.mat([1, 2])
b2 = np.mat([3, 4])
print(b1, b2)
b = np.multiply(b1, b2)
print(b)
[[1 2]] [[3 4]]
[[3 8]]
b1 = np.mat([1, 1])
b = b1 * 2
print(b)
# 矩阵与数的点乘
[[2 2]]
c1 = np.mat(np.eye(2, 2)*0.5) # 构建一个2行2列的对角矩阵,元素为0.5
print(c1)
c = c1.I
print(c)
[[0.5 0. ]
[0. 0.5]]
[[2. 0.]
[0. 2.]]
c1 = np.array([[1, 2], [3, 4]])
c = np.linalg.inv(c1)
print(c)
[[-2. 1. ]
[ 1.5 -0.5]]
c1 = np.mat([[1, 2], [3, 4]])
c = c1.T
print(c)
[[1 3]
[2 4]]
c1 = np.array([[1, 2], [3, 4]])
c = c1.transpose()
print(c)
[[1 3]
[2 4]]
c = np.array([[1, 2], [3, 4]])
print(np.linalg.det(c))
-2.0000000000000004
c = np.array([[1, 2], [3, 4]])
print(np.linalg.eig(c))
# 所得的元组中,第一个为特征值元组,第二个为相对应的特征向量
(array([-0.37228132, 5.37228132]), array([[-0.82456484, -0.41597356],
[ 0.56576746, -0.90937671]]))
c = np.array([[1, 2], [3, 4]])
d = np.array([[5], [10]])
print(np.linalg.solve(c, d))
"""
求解线性方程组
1X + 2Y = 5
3X + 4Y = 10
"""
[[0. ]
[2.5]]
c = np.mat([[1, 1], [2, 3], [4, 5]])
c1 = c.sum(axis=0)
print(c1)
# 求列和,得到1*2的矩阵
c2 = c.sum(axis=1)
print(c2)
# 求行和,得到3*1的矩阵
[[7 9]]
[[2]
[5]
[9]]