MATLAB: Dont know what Polyval is here doing :-/

polyval

Hello Together, i dont know what polyval is doing here with the blue lines:
What i want is a line through all points (like the black one).
untitled.jpg
Code for it is at end.
  • As you can see, the black line with polyval is plotted correct.
  • The points yd1 for xd1 and yd2 for xd2 are plotted correct
  • What is not plotted correct, is the polyval for xd1 and xd2 -> What have i done wrong here?
Thanks a lot!
%Black line

xml1 = [ -0.3, 0.4];
yml1 = [-0.15, -0.15];
xml2 = 0.4 + 0.7 * cos(0:pi/50:pi/2) ;
yml2 = -0.85 +0.7 * sin(0:pi/50:pi/2);
xml3 = [1.1, 1.1];
yml3 = [-0.85, -1.15];
load ('xdata310519.mat')
%xd1 = 0 0.3906 0.7430 1.0227 1.2022 1.2641 1.2022
%yd1 = 0 -0.0619 -0.2414 -0.5211 -0.8735 -1.2641 -1.6547
%xd2 = 0 0.1943 0.3696 0.5087 0.5980 0.6288 0.5980
%yd2 = 0 -0.0308 -0.1201 -0.2592 -0.4345 -0.6288 -0.8231
grad = 5;
p1 = polyfit( xd1, yd1, grad);
p2 = polyfit( xd1, yd2, grad);
f1 = polyval( p1, xd1);
f2 = polyval( p2, xd2);
hold on
%Black line
plot(xml1, yml1, '--k');
plot(xml2, yml2,'--k');
plot(xml3, yml3, '--k');
%points
plot(xd1, yd1,'s', xd2, yd2,'s');
plot(xd1, f1,'b', xd2, f2,'b');

Best Answer

  • You fit yd2 vs xd1 but then plotted against xd2. One presumes the fit should be against xd2 as well.
    BUT: A perfect illustration why higher order polynomials are rarely the right fitting function--what your fit really is is shown below--
    untitled.jpg
    where this was generated from
    p2 = polyfit( xd2, yd2, grad); % fit against intended variable
    figure
    plot(xd2,yd2,'bx') % plot the data points
    hold on
    plot(xd2,f2,'b-') % and the fit at only those points (linear between)
    x2=linspace(min(xd2),max(xd2)); % fill in 100 points between first, last
    plot(x2,polyval(p2,x2),'r-') % and plot those as well...
    legend('Data','5th Order at X','5th Order at 100X')
    A polynomial is an exceedingly bad choice for such data; use an interpolating spline instead or something similar.