IndexError: index 4 is out of bounds for axis 0 with size 4 [closed]

0

Good evening. I have the following code in Python, but the error quoted appears:

import numpy as np 
x=np.ones((4,1)) 
for k in range (5,45): 
x[k]=5.5369*x[k-1]*(x[k-2])**2+0.1931*x[k-3] 
print(x) 

The error is:

IndexError: index 4 is out of bounds for axis 0 with size 4
    
asked by anonymous 03.10.2017 / 23:25

1 answer

0

You have two big problems in your code (plus a small formatting bug inside the loop).

One is in its range , the other in the vector allocation.

  • Range :

For a vector of size N, Python uses indices from 0 to N-1. In your case, N=4 , with maximum index of N-1=3 .

The first call uses range(5,45) = [5, 6, ... , 44] with k-1=4 . Obviously a problem there. Using range(4,45) , this problem is solved, but then we have the following problem.

  • Memory :

In% with_% its syntax works because it allocates memory as the matrix is called. Remember that this is a terrible programming practice!  Do not use this unless you really need it. In Python, it does not do this. At least not this way.

What you want is to make a Matlab of the matrix. But let's go to a code of the effective way, in which the vector was completely allocated before the calculation:

x=np.ones((45,1)) 
for k in range(3,45): 
  x[k]=5.5369*x[k-1]*(x[k-2])**2+0.1931*x[k-3] 

print(x)

If you want to use append (which is not necessary for this case, but may be for another), the code is:

x=np.ones((3,1)) 
for k in range (3,45): 
  x=np.append(x,5.5369*x[k-1]*(x[k-2])**2+0.1931*x[k-3])    
print(x)
    
04.10.2017 / 21:02