使用Numpy模块中的内置方法实现矩阵相乘、逆序、转置和求和处理。
import numpy as np
if __name__ == "__main__":
# 矩阵相乘
mat1 = np.mat([ [1, 3] ]) # 一行两列
mat2 = np.mat([ [2], [4] ]) # 两行一列
mat3 = mat1 * mat2
print(mat3)
# 矩阵求逆
mat4 = np.mat([ [1, 0, 1], [0, 2, 1], [1, 1, 1] ])
mat5 = mat4.I
print(mat5)
# 矩阵转置
mat6 = np.mat([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ])
mat7 = mat6.T
print(mat7)
# 矩阵每一列的和
sum1 = mat6.sum(axis=0)
print(sum1)
# 矩阵每一行的和
sum2 = mat6.sum(axis=1)
print(sum2)
# 矩阵与数组之间的转换
mat8 = np.mat([ [1, 2, 3] ])
arr1 = np.array(mat8)
print(arr1)
arr2 = [3, 4, 5]
mat9 = np.mat(arr2)
print(mat9)
输出结果:
[[14]]
[[-1. -1. 2.]
[-1. 0. 1.]
[ 2. 1. -2.]]
[[1 4 7]
[2 5 8]
[3 6 9]]
[[12 15 18]]
[[ 6]
[15]
[24]]
[[1 2 3]]
[[3 4 5]]