title: Finding the best monotonic curve fit
body: <p>Edit: Some time after I asked this question, an R package called <code>MonoPoly</code> (available <a href="https://cran.r-project.org/web/packages/MonoPoly/index.html" rel="noreferrer">here</a>) came out that does exactly what I want. I highly recommend it.</p>
  
  <hr>
  
  <p>I have a set of points I want to fit a curve to. The curve must be monotonic (never decreasing in value) i.e. the curve can only go upward or stay flat.</p>
  
  <p>I originally had been polyfitting my results and this had been working great until I found a particular dataset. The polyfit for data in this dataset was non-monotonic.</p>
  
  <p>I did some research and found a possible solution in <a href="https://uk.mathworks.com/matlabcentral/newsreader/view_thread/260827" rel="noreferrer">this</a> post:</p>
  
  <blockquote>
    <p>Use lsqlin. Constrain the first derivative to be non-negative at both
    ends of the domain of interest.</p>
  </blockquote>
  
  <p>I'm coming from a programming rather than math background so this is a little beyond me. I don't know how to constrain the first derivative to be non-negative as he said. Also, I think in my case I need a curve so I should use <a href="http://uk.mathworks.com/help/optim/ug/lsqcurvefit.html" rel="noreferrer">lsqcurvefit</a> but I don't know how to constrain it to produce monotonic curves.</p>
  
  <p>Further research turned up <a href="https://uk.mathworks.com/matlabcentral/newsreader/view_thread/72931" rel="noreferrer">this</a> post recommending <code>lsqcurvefit</code> but I can't figure out how to use the important part:</p>
  
  <blockquote>
    <p>Try this non-linear function F(x) also. You use it together with
    lsqcurvefit but it require a start guess on the parameters. But it is
    a nice analytic expression to give as a semi-empirical formula in a
    paper or a report.</p>
    
    <p>%Monotone function F(x), with c0,c1,c2,c3 varitional constants F(x)=
    c3 + exp(c0 - c1^2/(4*c2))<em>sqrt(pi)</em>...
          Erfi((c1 + 2*c2*x)/(2*sqrt(c2))))/(2*sqrt(c2))</p>
    
    <p>%Erfi(x)=erf(i*x) (look mathematica) but the function %looks much like
    x^3    %derivative f(x), probability density f(x)>=0
    f(x)=dF/dx=exp(c0+c1*x+c2*x.^2)</p>
  </blockquote>
  
  <p>I must have a monotonic curve but I'm not sure how to do it, even with all of this information. Would a random number be enough for a "start guess". Is <code>lsqcurvefit</code> best? How can I use it to produce a best fitting monotonic curve?</p>
  
  <p>Thanks</p>