1

I have 6 cubic polynomial curves I'd like to plot. And I have the following code::

import numpy as np
import matplotlib.pyplot as plt 

a0 = np.array([ 0.04438, -0.01808, -0.01836,  0.01170, -0.01062, -0.01062])
a1 = np.array([-2.26095, -0.13595, -0.03577, -0.00400, -0.03577, -0.00400])
a2 = np.array([-0.13387,  0.01941,  0.02612,  0.00066,  0.02612,  0.00066])
a3 = np.array([ 0.00066, -0.00183, -0.00558, -0.00558,  0.00890,  0.00890])

x_max = 2.80
x_min = 0.30
diff  = 0.01

y = int(((x_max - x_min)/diff))
m_diff = np.zeros((y,6))

xmin = int(x_min * 100)
xmax = int(x_max * 100)
di   = int(diff  * 100)

for xx in range(xmin, xmax, di):
   x = xx*diff
   m_diff[xx] = a0 + (a1*x) + (a2*x*x) + (a3*x*x*x)

Why do I get an "IndexError: index 250 is out of bounds for axis 0 with size 250" error? What should this be? Ultimately I'd like to just do:

plt(xx, m_diff[:,0])
plt(xx, m_diff[:,1])
plt(xx, m_diff[:,2])
plt(xx, m_diff[:,3])
plt(xx, m_diff[:,4])
plt(xx, m_diff[:,5])

Thanks!!

1
  • 1
    m_diff has shape (250,6). Your for loop is going from 30 to 280. When your for loop reaches loop 250, your m_diff is not that big, which is why you get the error. Commented Nov 1, 2017 at 18:12

2 Answers 2

1

Here is the vectored approach, which prevents mistakes in the array shapes :

x=np.arange(x_min,x_max,diff)
xs=np.power.outer(x,range(4))
coeffs=np.vstack((a0,a1,a2,a3))
curves=np.dot(xs,coeffs)
plt.plot(x,curves)

You just have to learn to play with dimensions and all is simple ;):

for array in x,xs,coeffs,curves : print (array.shape) 
# (250,)
# (250, 4)
# (4, 6)
# (250, 6)

Results :enter image description here

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

Comments

1

Numpy has a function numpy.polyval to evaluate polynomials. You can use it in this case to plot the polynomials

import numpy as np
import matplotlib.pyplot as plt 

a0 = np.array([ 0.04438, -0.01808, -0.01836,  0.01170, -0.01062, -0.01062])
a1 = np.array([-2.26095, -0.13595, -0.03577, -0.00400, -0.03577, -0.00400])
a2 = np.array([-0.13387,  0.01941,  0.02612,  0.00066,  0.02612,  0.00066])
a3 = np.array([ 0.00066, -0.00183, -0.00558, -0.00558,  0.00890,  0.00890])

x_max = 2.80
x_min = 0.30
diff  = 0.01

coeff = np.c_[a3,a2,a1,a0]

x = np.arange(x_min,x_max,diff)
y = np.array([np.polyval(coeff[i],x) for i in range(coeff.shape[0])])

plt.plot(x,y.T)

plt.show()

enter image description here

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.