gpt4 book ai didi

python - 将向量放入矩阵+变换中

转载 作者:太空宇宙 更新时间:2023-11-03 21:37:15 24 4
gpt4 key购买 nike

所以我有一个用 Numpy 创建的向量,名为

V = [10 20 30 40  0  1]

我想要一个像这样的矩阵 M :

 [10.  0.  0.  0.  0.  0.]
[20. 10. 0. 0. 0. 0.]
[30. 20. 10. 0. 0. 0.]
[40. 30. 20. 10. 0. 0.]
[ 0. 40. 30. 20. 10. 0.]
[ 1. 0. 40. 30. 20. 10.]
[ 0. 1. 0. 40. 30. 20.]
[ 0. 0. 1. 0. 40. 30.]
[ 0. 0. 0. 1. 0. 40.]
[ 0. 0. 0. 0. 1. 0.]
[ 0. 0. 0. 0. 0. 1.]

为此,我使用循环和向量提取,但它太长了,因为我的向量 V 有 500 列,而矩阵 M 有 500*2 -1线和500列。

此外,对于不同的向量 V,我必须重复此操作至少 100 000 次

是否可以使用矩阵计算并避免循环来得到这个结果? (尽可能快)

谢谢!

(我在 Spyder 上使用 Python 3.6)

编辑:我的解决方案:

t=480n=10000

t1 = time.time()
for p in range(n):
for j in range(M.shape[1]):
M[j:j+t,j] = np.transpose(V[:])
print(time.time()-t1)

14 秒仅 10 000 次...太长了

编辑2:评论中解决方案的基准:

(这里普拉特是V)

t1 = time.time()
for p in range(n):
for j in range(M.shape[1]):
M[j:j+t,j] = np.transpose(Prate[:])
print(time.time()-t1)


t1 = time.time()
for p in range(n):
n = len(Prate)
m = np.tile(np.concatenate((np.array(Prate), np.zeros(t))), t)[:2*t*t-t]
result = m.reshape(t, -1).T
print(time.time()-t1)

t1 = time.time()
for p in range(n):
ind = np.arange(t)
indices = ((ind[:,None] + ind).ravel() , np.repeat(ind, t))
base = np.zeros((n1, t))
base[indices] = np.tile(Prate, t)
print(time.time()-t1)

输出:

16.737313747406006
29.46031618118286
3.6843104362487793

编辑3:为了避免遍历所需大小两倍的数组,我以不同的方式提出我的问题:

我有一个向量 (1x6):

V = [1 20 5 0  0  9]

我想要一个像这样的矩阵 M (6x6) :

 [1.  20.  5.  0.  0.  9.]
[0. 1. 20. 5. 0. 0.]
[0. 0. 1. 20. 5. 0.]
[0. 0. 0. 1. 20. 5.]
[0. 0. 0. 0. 1. 20.]
[0. 0. 0. 0. 0. 1.]

在每一行中,它都是相同的向量 V(它的一部分),但带有偏移量以获得三角矩阵。

如何在没有循环的情况下做到这一点?

(这只是一个简单的例子,但实际向量 V 要大得多)

谢谢:D

最佳答案

如果您只想快速解决方案而不是避免循环的解决方案,您可以简单地使用 NumbaCython

示例

import numpy as np
import numba as nb

@nb.njit()
def create_mat(V):
arr=np.zeros((V.shape[0],V.shape[0]),dtype=V.dtype)
for i in range(V.shape[0]):
for j in range(i,V.shape[0]):
arr[i,j]=V[j-i]
return arr

时间

V=np.random.rand(10000)
#The first call has an constant compilation overhead of about 0.2s,
#which is neglected here.
create_mat: 0.35s

关于python - 将向量放入矩阵+变换中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53169156/

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