Simple Curve-fitting

When analysing numerical data it is often useful to fit a polynomial curve, passing the before-and-after through a graphical display then gives a quick wet-finger overview of data trends and possible outlier values.  The code below (presented as a Dyalog dynamic function, but readily translated to other APLs) applies a best-fit polynomial (of specified order) to a data matrix with x-values in the first column with distinct sets of y-values in successive columns...

     fit←{⎕IO ⎕ML←0 3
 ⍝ ⍺-th order polynomial least-squares fit
     x←,1↑[1]⍵                    ⍝ x-values are in first column
     y←1↓[1]⍵                     ⍝ remaining columns are y-values
     ct←⍉⊃(⊂[0]y)⌹¨⊂x∘.*⍳1+⍺      ⍝ coefficients calculated
     (x∘.*⍳1+⍺)+.×ct}             ⍝ and applied

Practical use would be enhanced by checking for a sensible order (given the number of data points).

A suggested exercise is to produce an equivalent function which fits curves up to and including the required order (arithmetic mean, linear, second-order and so on).

Page created 25 January 2010.
Copyright © Dogon Research 2009-2010