Math 171 - Alexiades
                  HW: Least Squares fitting to any function
Consider some data points, e.g.
      x = [0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 ];
      y = [0.01 0.1 0.2 0.5 0.4 0.6 0.5 0.4 0.1 0.2 0.04];
  • Try yFit(x)=A*sin(B*pi*x) to see how it looks:
          A=1; B=1; C=-0.2; %% initial coeffs
          yInit = A*sin(B*pi*x)+C; %%initial try
          ErrInit = sum( (y - yInit).^2 ) %%init error =0.50999
          plot( x,y,'ko', x, yInit, 'r-' ); title('yInit');

  • Now try yFit(x)=A*sin(B*pi*x) using fminsearch to hopefully improve it (better A,B,C):
          coefs = fminsearch( @LSerror , [A B C], [], x,y );   %see below for LSerror.m
          A=coefs(1); B=coefs(2); C=coefs(3);   %extract A,B,C
          fprintf('Fit coefs: A=% B=% C=% \n', A,B,C) %%print them
          yFit = A*sin(B*pi*x)+C;   %%model in LSerror
          ErrFit = sum( (y-yFit).^2 )   %% LS error of Matlab fit
          plot(x,y,'ko', x,yInit,'b-', x, yFit, 'r-*' );

  • The above produce:   A=0.510786   B=0.999581   C=-0.016074   with Err=0.077402

  • %................. file   LSerror.m :
          function E = LSerror(coefs, x,y)
              A=coefs(1); B=coefs(2); C=coefs(3);   %extract A,B,C
              Ymodel = A*sin(B*pi*x) +C;   %model formula
              E = sum( (y - Ymodel).^2 );   %LS error, to be minimized
          end