使用Numpy模块中的内置方法实现矩阵相乘、逆序、转置和求和处理。
import numpy as npif __name__ == "__main__":# 矩阵相乘mat1 = np.mat([ [1, 3] ]) # 一行两列mat2 = np.mat([ [2], [4] ]) # 两行一列mat3 = mat1 * mat2print(mat3)# 矩阵求逆mat4 = np.mat([ [1, 0, 1], [0, 2, 1], [1, 1, 1] ])mat5 = mat4.Iprint(mat5)# 矩阵转置mat6 = np.mat([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ])mat7 = mat6.Tprint(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]]
本文链接:https://my.lmcjl.com/post/4198.html
展开阅读全文
4 评论