Indexerror: index 4 is out of Bounds for Axis 0 with size 4

Asked

Viewed 1,835 times

0

Good evening. I have the following Python code, but the cited error 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 mistake is:

IndexError: index 4 is out of bounds for axis 0 with size 4
  • What are you trying to do with that code?

  • 2

    You are creating a 4x1 matrix and then trying to access it as if it were an array at the positions of 2 through 45.

  • I already have the first 4 values of vector x, so through the recursive function inside the for, I want to calculate the other values

1 answer

1


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

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

  • Range:

For a size N vector, Python uses indices from 0 to N-1. In your case, N=4, with a maximum rate 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 next problem.

  • Memoriam:

In Matlab your syntax works because it allocates the memory as the Matrix is called. It is worth remembering that this is a terrible programming practice! Don’t wear it unless you really precise. In Python, it doesn’t do that. At least not this way.

What you want is to make one append the Matrix. But let’s go to a code in the effective way, in which the vector was allocated completely 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 really want to use the 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.