How to plot a defined function against one of its arguments in Python
<pre><code>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

def f(x, t):       #function for x'(t) = f(x,t)
    return -x

def exact(t):       #exact solution
    return np.exp(-t)

def Rk4(x0, t0, dt):      #Runge-Kutta Fourth Order Approximation
    t = np.arange(0, 1+dt, dt)
    n = len(t)
    x = np.array([x0]*n)
    E = np.array([x0]*n)
    E0 = x0-exact(1)
    x[0],t[0],E[0] = x0,t0,E0
    for i in range(n-1):
        h = t[i+1] - t[i]
        k1 = h*f(x[i], t[i])
        k2 = h*f(x[i] + 0.5 * k1, t[i] + 0.5 * h)
        k3 = h*f(x[i] + 0.5 * k2, t[i] + 0.5 * h)
        k4 = h*f(x[i] + k3, t[i+1])
        x[i+1] = x[i] + (k1 + 2.0*(k2 + k3) + k4 )/6.0
        E[i+1] = E[i]+(x[i+1]-x[i])
    return E

vecRk4 = np.vectorize(Rk4)
dtime = np.arange(10e-4,1,10e-5)
S = vecRk4(1.0,0.0,dtime)
plt.plot(dtime,S)
</code></pre>

<p>I'm just trying to plot the Rk4 function for x0 = 1.0, t0 = 0.0 as a function of dt. I tried by vectorizing the function and creating an array for the timestep dt, but get the error "ValueError: setting an array element with a sequence."</p>

<p>The problem is that your return value <code>E</code> is not a single number, but a numpy array.</p>

<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html" rel="nofollow">Vectorizing </a>many arrays would give you a list, vectorizing many numpy arrays does not work here.</p>

<p>To come back to your original question: The way to plot a function against one of its arguments using vectorization is:</p>

<pre><code>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

def myfunc(a,b):
    return 2*b+a


vecRk4 = np.vectorize(myfunc)
dtime = np.arange(10e-4,1,10e-5)
S = vecRk4(a=3, b=dtime)
plt.plot(dtime,S)
plt.show()
</code></pre>

<p><a href="http://i.stack.imgur.com/V2Sy7.png" rel="nofollow"><img src="http://i.stack.imgur.com/V2Sy7.png" alt="enter image description here"></a></p>

python numpy matplotlib runge-kutta