Reputation: 47
I understand that there are other questions with the same error message however I have looked at these and don't understand how it applies to my current situation. So I'm creating a matrix u=np.zeros(shape=(nt,nx))
and then I have also two arrays time=nt*[0]
and middles=nx*[0]
this is the full code I'm trying to implement in regards to plotting the diffusion equation:
import numpy as np
import matplotlib.pyplot as plt
import math
D=1 #diffusion constant set equal to 1
C=1 #creation rate of neutrons, set equal to 1
L=math.pi
nx=101 #number of steps in x
nt=10002 #number of timesteps
dx=L/(nx-1) #step in x
dt=0.0001 # time step
Z=(D*dt)/(dx*dx) #constant for diffusion term
Z1=C*dt #constant for u term
x1=np.arange(-math.pi/2+0.03079992797, 0, 0.03079992797)
y=np.arange(0.06159985595,math.pi/2, 0.03079992797)
z = np.hstack((x1, y))
u=np.zeros(shape=(nt,nx))
time=nt*[0]
middles=nx*[0]
u[50,0]=1/dx #setting our delta function
for j in range(0,nt-1):
for i in range(2,nx-1):
u[j+1,i]=Z*(u[j,i+1]-2*u[j,i]+u[j,i-1])+Z1*u[j,i]+u[j,i]
u[j,1]=0
u[j,nx-1]=0
time[j]=dt*j
middles[j]=u[j,((nx-1)/2)]
if i==50 or i==100 or i==250 or i==500 or i==1000 or i==10000:
plt.plot(time,middles)
plt.title('Numerical Solution of the Diffusion Equation')
plt.xlabel('time')
plt.ylabel('middles')
plt.show()
however I keep getting this error message seen in the title only integers, slices (
:), ellipsis (
...), numpy.newaxis (
None) and integer or boolean arrays are valid indices
The error message is in regards to the middles[j]=u[j,((nx-1)/2)]
line
I'm trying to convert this code from Matlabe if that explains things somewhat
Upvotes: 2
Views: 33015
Reputation: 31
Other reason for this type of error is when you store indices in set and try your ND array/dataframe through this
Upvotes: 1
Reputation: 8458
You often get this error when you accidentally create a float
with one of your calculations of an index value.
In this case:
middles[j] = u[j, ((nx-1)/2)]
...will create a float
when (nx-1)
is odd. So you could try:
middles[j] = u[j, int(np.round(((nx-1)/2), 0))]
(I'm using np.round
here, which is overkill perhaps, but if you start dividing by a number other than 2, then this approach makes much more sense, as it will round up OR down. int()
will always floor it.)
Python vs. Matlab
Two things to be aware of:
Upvotes: 4
Reputation: 77837
Never mind ... I see it: you're using a float
as an index in your final line of code:
u[j,((nx-1)/2)]
Convert the second index to int
:
u[j, int((nx-1)/2)]
Upvotes: 2