title: piecewise linear function with numpy.piecewise
body: <p>I am trying to use the data from two <code>x0</code> and <code>y0</code> coordinate arrays to create a function that uses the provided <code>x0</code> and <code>y0</code> to compute a piecewise series of segments.</p>
  
  <p>For doing that, I create a function
  </p>
  
  <pre><code>import numpy as np
  import matplotlib.pylab as pl
  
  def broken_line(x, x0, y0):
      cl = []
      fl = []
      for i in range(len(x0)-1):
          ab = np.polyfit(x0[i:i+2], y0[i:i+2], 1)
          # Compute and append a "condition" interval
          cl.append(np.logical_and(x &gt;= x0[i], x &lt;= x0[i+1]))
          # Create a line function for the interval
          fl.append(lambda x: x*ab[0] + ab[1])
      return(np.piecewise(x, condlist=cl, funclist=fl))
  </code></pre>
  
  <p>and then to test it I plot the results of</p>
  
  <pre class="lang-py prettyprint-override"><code>x0 = np.array([1, 3, 5, 10])
  y0 = np.array([2, 1, 5, 7])
  
  x = np.linspace(1, 10, 30)
  
  pl.plot(x, broken_line(x, x0, y0))
  pl.plot(x0, y0)
  pl.show()
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/ML8lq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ML8lq.png" alt="enter image description here"></a></p>
  
  <p>However, the results is not as I would expect.
  I had a look at other posts on the topic, including <a href="https://stackoverflow.com/questions/16574966/python-confused-by-numpys-piecewise-function">this</a> and <a href="https://stackoverflow.com/questions/47358953/matplotlib-plot-piecewise-linear-function-with-three-parts">this other</a>, together with the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.piecewise.html" rel="nofollow noreferrer">numpy.piecewise</a> documentation.
  However, I was not able to figure out why the code is not working as expected. It looks like only the last definition of <code>lambda</code> is considered.
  Suggestions are all welcome.</p>