gpt4 book ai didi

python - 将两个矩阵划分为8个小矩阵的更快方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:05:06 24 4
gpt4 key购买 nike

这是我用于划分两个矩阵的代码:

def divideM1(X,Y):
n=len(X)
a=[[col for col in row[:len(row)/2]] for row in X[:n/2]]
b=[[col for col in row[len(row)/2:]] for row in X[:n/2]]
c=[[col for col in row[:len(row)/2]] for row in X[n/2:]]
d=[[col for col in row[len(row)/2:]] for row in X[n/2:]]
e=[[col for col in row[:len(row)/2]] for row in Y[:n/2]]
f=[[col for col in row[len(row)/2:]] for row in Y[:n/2]]
g=[[col for col in row[:len(row)/2]] for row in Y[n/2:]]
h=[[col for col in row[len(row)/2:]] for row in Y[n/2:]]

return a,b,c,d,e,f,g,h

def divideM2(X,Y):
n=len(X)
a=[[0 for i in range(n/2)] for j in range(n/2)]
b=[[0 for i in range(n/2)] for j in range(n/2)]
c=[[0 for i in range(n/2)] for j in range(n/2)]
d=[[0 for i in range(n/2)] for j in range(n/2)]
f=[[0 for i in range(n/2)] for j in range(n/2)]
e=[[0 for i in range(n/2)] for j in range(n/2)]
g=[[0 for i in range(n/2)] for j in range(n/2)]
h=[[0 for i in range(n/2)] for j in range(n/2)]

for i in range(n/2):
for j in range(n/2):
a[i][j]=X[i][j]
b[i][j]=X[i][j+n/2]
c[i][j]=X[i+n/2][j]
d[i][j]=X[i+n/2][j+n/2]
e[i][j]=Y[i][j]
f[i][j]=Y[i][j+n/2]
g[i][j]=Y[i+n/2][j]
h[i][j]=Y[i+n/2][j+n/2]
return a,b,c,d,e,f,g,h

如果我使用 time.time(),似乎方法 2-“divideM2”比方法 1-“divideM1”快,但这是为什么呢?有没有更好的划分方法?

编辑1:有趣的是,当我使用 time.time() 时:

start = time.time()
print("method1")
for i in range(10000):
1>2
divideM2(a1,a1)
end = time.time()
t1=end-start
print t1 ,"m1"

start = time.time()
print("method2")
for j in range(10000):
1>2
divideM1(a2,a2)
end = time.time()
t2= end-start
print t2, "m2"

if t1>t2:
print "method 2 is faster"
else:
print "method 1 is faster"

即使我单独比较“divide1”,我也总是得到“方法 2 更快”。有人也可以解释一下吗?

最佳答案

我认为方法 2 更快,因为您只使用 2 个循环而不是第一种方法中使用的所有 for 循环。

关于换一种方式,你可以试试numpy.split。这是 doc .

关于python - 将两个矩阵划分为8个小矩阵的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45454584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com