0

I have the following modified section of code, which is mimicking a section of MatLab code, which works fine;

import numpy as np
import math

dt = 1e-2;                      # time step
t = np.arange(0, 7, dt)         # t

mt=2
nt=2

rho=np.zeros((2,2,2,2))

Pe=np.array([[1,0],[0,0]])
Sm=np.array([[0,0],[1,0]])
Sz=np.array([[1,0],[0,- 1]])
Sy=np.array([[0,- 1j],[1j,0]])
Sx=[[0,1],[1,0]]

exp_Sz=np.zeros((2,2,len(t)))
exp_Sy=np.copy(exp_Sz)
exp_Sx=np.copy(exp_Sz)
exp_Pe=np.copy(exp_Sz)


for indx in (1,mt):
    for jndx in (1,nt):
        exp_Sz[indx,jndx,1]=np.trace(rho[:,:,indx,jndx] * Sz)
        exp_Sy[indx,jndx,1]=np.trace(rho[:,:,indx,jndx] * Sy)
        exp_Sx[indx,jndx,1]=np.trace(rho[:,:,indx,jndx] * Sx)
        exp_Pe[indx,jndx,1]=np.trace(rho[:,:,indx,jndx] * Pe)

But I get the following error;

exp_Sz[indx,jndx,1]=np.trace(rho[:,:,indx,jndx] * Sz)
IndexError: index 2 is out of bounds for axis 3 with size 2

I am unsure on what the error is.

Any help would be appreciated, Thanks!

2
  • I recommend you read this guide for MATLAB users before asking any more questions: wiki.scipy.org/NumPy_for_Matlab_Users Commented Mar 14, 2015 at 5:05
  • Cheers for the link, will take a look now. Commented Mar 14, 2015 at 5:25

1 Answer 1

1
for indx in (1,mt):
    for jndx in (1,nt):
         # etc

The nested loops above iterate over the two element tuples containing only the elements 1 and mt (outer loop) and 1 and nt (inner loop).

You probably wanted to iterate over range(mt) and range(nt) instead.

Note that numpy arrays are 0-index based.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.