您的位置:首页 > 编程语言 > Python开发

python 矩阵乘法

2020-06-19 16:57 363 查看

钉钉、微博极速扩容黑科技,点击观看阿里云弹性计算年度发布会!>>>

1.列表作为数据结构

def MatrixProduct(a, b):
temp2 = []
for i in range(len(a)):
temp1 = []
for j in range(len(b[0])):
total = 0
for k in range(len(a[0])):
total += a[i][k] * b[k][j]
temp1.append(total)
temp2.append(temp1)
return temp2

print(MatrixProduct([[1,0],[0,0]], [[0,1],[1,0]]))

时间复杂度太高O(n^3)

以后再想办法用矩阵快速幂来优化,降低时间复杂度

2.numpy中ndarray作为数据结构

(注意numpy数组的a*b指的并不是矩阵乘法,a.dot(b)或者numpy.dot(a,b))

import numpy as np

def MatrixProduct(a, b):
a=np.array(a)
b=np.array(b)
c=np.dot(a,b)
return c.tolist()

print(MatrixProduct([[1,0],[0,0]], [[0,1],[1,0]]))

3.numpy中mat作为数据结构

这种矩阵格式就可以a*b了

import numpy as np

def MatrixProduct(a, b):
a=np.mat(a)
b=np.mat(b)
c=a*b
return c.tolist()

print(MatrixProduct([[1,0],[0,0]], [[0,1],[1,0]]))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  numpy def python