简体   繁体   中英

numpy fill an array with arrays

I want to combine an unspecified (finite) number of matrices under a Kroneckerproduct. 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. But since Bulk is an ndarray object I suppose it wont accept arraylike objects inside it.

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.

and now the three particle chain is 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.

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.

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. I would suggest to use the standard python object 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).

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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