I'm trying to create polynomials from some symbolic points to discretize derivations. This means I'm having data like $(a, \phi(a)),\ (b, \phi(b) ) $and $(c, \phi(c))$ and want to fit a second order polynomial through these points.
I tried Matlabs polyfit but it can't handle syms. I also had a look at Maxima, but couldn't find any function there neither.
I'd be really happy if someone could point out how to do this in a CAS.
It annoys me when Matlab functions aren't overloaded for symbolic calculation. Looking at the code for
polyfit(edit polyfitin the command window) it seems that doing what you need may be quite easy. I comes down to constructing a Vandermonde matrix and solving a least squares problem. The existing code can be adapted for symbolic math.In fact, I couldn't resist and gave it try. You can find my code for
polyfitsym.on my GitHub.For an example, in your three point, second-order polynomial case, let $\phi(x) = \sin(x)$. First we'll solve for three arbitrary symbolic points $x_1 = a$, $x_2 = b$, and $x_3 = c$. Later we'll explicitly set $a = -3$, $b = -1$, and $c = 1$.
which returns the symbolic result
This can be simplified a bit with
simpleorsimplifyor you can plug in numeric values withsubs:which gives (still symbolic – use
doubleto convert to floating point if you like)You might wish to plot this and see how good the fit is over a range:
which results in a figure like this:
There is another example in the help for the function. Since I don't know what exactly you're trying to do, the
polyfitsymfunction is pretty general and works very much likepolyfit. Feel free to modify, improve, and use it as you need. I can't guarantee that it won't have numeric issues (for some test cases all of the coefficients wereInffor some reason) or that it will be able to handle everything. It usessym/linsolverather that\(mldivide) to solve the least squares linear system because it returns warnings if the the problem is ill-conditioned.