1.列表作为数据结构
bash;gutter:true;
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</p>
<p>print(MatrixProduct([[1,0],[0,0]], [[0,1],[1,0]]))</p>
<pre><code>
时间复杂度太高O(n^3)
以后再想办法用矩阵快速幂来优化,降低时间复杂度
#### 2.numpy中ndarray作为数据结构
(注意numpy数组的a*b指的并不是矩阵乘法,a.dot(b)或者numpy.dot(a,b))
;gutter:true;
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了
bash;gutter:true;
import numpy as np</p>
<p>def MatrixProduct(a, b):
a=np.mat(a)
b=np.mat(b)
c=a*b
return c.tolist()</p>
<p>print(MatrixProduct([[1,0],[0,0]], [[0,1],[1,0]]))
作者:九命猫幺
博客出处:http://www.cnblogs.com/yongestcat/
欢迎转载,转载请标明出处。
如果你觉得本文还不错,对你的学习带来了些许帮助,请帮忙点击右下角的推荐
Original: https://www.cnblogs.com/yongestcat/p/13156077.html
Author: 九命猫幺
Title: python 矩阵乘法
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/565650/
转载文章受原作者版权保护。转载请注明原作者出处!