Search code examples
pythonnumpymatrixcomplex-numbers

Matrix with complex exponential elements in Python


I have been trying to create this Hamiltonian matrix, and I believe the complex exponential elements are giving me trouble. However, I don't know how to fix it.

This is what I have written so far:

t = 2.7
a = 1

z = -t * np.exp(-j*k*a)

y = -t * np.exp(j*k*a)

H = np.matrix(([0, -t,0,-t,0,0,0,0,0,0,0,0,0,0],
    [- t, 0,- t ,0,0,0,0,0,0,0,0,0,0,0]
    [0, - t ,0,y,0,-t,0,0,0,0,0,0,0,0]
    [-t, 0,z,0,-t,0,0,0,0,0,0,0,0,0]
    [0, 0,0,- t ,0,- t ,0,-t,0,0,0,0,0,0]
    [0, 0,-t,0,0,-t,0,-t,0,0,0,0,0,0]
    [0, 0,0,0,0,- t ,0,y,0,-t,0,0,0,0]
    [0, 0,0,0,-t,0,z,0,- t,0,0,0,0,0]
    [0, 0,0,0,0,0,0,- t,0,- t,0,-t,0,0]
    [0, 0,0,0,0,0,-t,0,- t,0,- t,0,0,0]
    [0, 0,0,0,0,0,0,0,0,- t,0,y,0,-t]
    [0, 0,0,0,0,0,0,0,-t,0,z,0,- t,0]
    [0, 0,0,0,0,0,0,0,0,0,0,- t ,0,- t]
    [0, 0,0,0,0,0,0,0,0,0,-t,0,- t ,0]),dtype = np.complex)`

When I try to run the cell, this error message appears

TypeError: list indices must be integers or slices, not tuple

The matrix needs to be a 14x14 one so that I can code and obtain the eigenvalues and eigenvectors.

In the past I have used np.array to build matrices, and it has worked fine. However, for this one it didn't. As can be seen, I have also tried using np.matrix.


Solution

  • Try using

    np.array([[val1, val2], [val3, val4]]) 
    

    instead of

    np.array(([val1, val2] [val3, val4])) ...
    

    You got the error because of the commas in between the rows. Don't forget them otherwise Python thinks you are trying to do list indexing:

    I.e.

    [1,2,3][0] 
    Output: 1
    

    Whereas

    [1,2,3], [0] 
    

    Output:

    ([1,2,3], [0])