简体   繁体   English

numpy用数组填充数组

[英]numpy fill an array with arrays

I want to combine an unspecified (finite) number of matrices under a Kroneckerproduct. 我想在Kronecker产品下合并未指定(有限)的矩阵。 In order to do this I want to save the matrices in an array but I don't know how to do this. 为了做到这一点,我想将矩阵保存在数组中,但是我不知道该怎么做。 At the moment I have: 目前,我有:

for i in range(LNew-2):
    for j in range(LNew-2):
        Bulk = np.empty(shape=(LNew-1,LNew-1))
        if i == j:
            Bulk[i,j]=H2
        else:
            Bulk[i,j]=idm

Here the H2 and idm are both matrices, which I want to combine under a Kronecker product. 这里H2和idm都是矩阵,我想在Kronecker产品下合并它们。 But since Bulk is an ndarray object I suppose it wont accept arraylike objects inside it. 但是由于Bulk是一个ndarray对象,我想它不会接受其中的arraylike对象。

edit: 编辑:

This is the function in which I want to use this idea. 这是我要使用此功能的功能。 I am using it to build a Hamiltonian matrix for a quantum spin chain. 我正在用它为量子自旋链建立哈密顿矩阵。 So H2 is the Hamiltonian for a two particle chain, H2 is a 4x4 matrix and idm is the 2x2 identity matrix. 因此,H2是两个粒子链的哈密顿量,H2是4x4矩阵,idm是2x2恒等矩阵。

and now the three particle chain is np.kron(H2,idm)+np.kron(idm,H2) 现在三个粒子链是np.kron(H2,idm)+ np.kron(idm,H2)

and for four particles np.kron(np.kron(H2,idm),idm)+np.kron(idm,np.kron(H2,idm))+np.kron(idm,np.kron(idm,H2)) and so on. 对于四个粒子np.kron(np.kron(H2,idm),idm)+ np.kron(idm,np.kron(H2,idm))+ np.kron(idm,np.kron(idm,H2) )等。

def ExpandHN(LNew):
idm = np.identity(2)
H2 = GetH(2,'N')
HNew = H2
for i in range(LNew-2):
    for j in range(LNew-2):
        Bulk = np.empty(shape=(LNew-1,LNew-1))
        if i == j:
            Bulk[i,j]=H2
        else:
            Bulk[i,j]=idm
i = 0
for i in range(LNew-2):
    for j in range(LNew-3):
        HNew += np.kron(Bulk[i,j],Bulk[i,j+1]) #something like this

return HNew

As you can see the second set of for loops hasn't been worked out. 如您所见,第二组for循环尚未制定。

That being said, if someone has a totaly different but working solution I would be happy with that too. 话虽这么说,如果某人有一个完全不同但可行的解决方案,我也会对此感到满意。

If I understand correctly, the your question boils down to how to create arrays of arrays with numpy. 如果我理解正确,那么您的问题可以归结为如何使用numpy创建数组的数组。 I would suggest to use the standard python object dict : 我建议使用标准的python对象dict

Bulk = dict()
for i in range(LNew-2):
    for j in range(LNew-2):
        if i == j:
            Bulk[(i,j)]=H2
        else:
            Bulk[(i,j)]=idm

The usage of tuples as keys allows you to maintain an array-like indexing of the matrices. 通过使用元组作为键,您可以维护矩阵的类似数组的索引。 Also note, that you should define Bulk outside of the two for loops (in any case). 还要注意,您应该在两个for循环之外定义Bulk(无论如何)。

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM