%% Optimal Fit of a Non-linear Function
% This is a demonstration of the optimal fitting of a non-linear function to a
% set of data.  It uses FMINSEARCH, an implementation of the Nelder-Mead simplex% (direct search) algorithm, to minimize a nonlinear function of several
% variables.
%
% Modified by VdS from program fitdemo by
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision: 5.15.4.2 $ $Date: 2004/08/16 01:37:29 $

%%
% First, create some sample data and plot it.

t=[0:.5:6]'
%% note t is the same as xdata from before
%% and y is the same as ydata
y= [-3.1343460e-01  -1.4581711e+00   3.5146085e+00   1.6370541e+00   6.8302830e+00 2.1398192e+00   4.0574860e+00   2.1886413e+00  -1.8438032e+00   -6.5913490e+00 -5.1183756e+00  -1.0271267e+01  -1.0771074e+01]'

plot(t,y,'ro'); hold on; h = plot(t,y,'b'); hold off;
title('Input data');

%%
% The goal is to fit the following function with three linear parameters and one
% nonlinear parameter to the data:
%
%     y =  ax + b*sin(c*x) +d 
%
% To fit this function, you will edit a function hw4fitfun.m.  
% Given the nonlinear
% parameter and the data (t and y), hw4fitfun calculates the error in the
% fit for this equation and updates the line (h).  



%%
% Make a guess for initial estimate of c (start) and invoke FMINSEARCH.  It
% minimizes the error returned from HW4FITFUN by adjusting c.  It returns the
% final value of c.  Within HW4FITFUN optimal values for a,b, and d for
% the current c are found.


start = [1];
options = optimset('TolX',0.1);  % termination tolerance on x 
estimated_c = fminsearch(@(x) hw4fitfun(x,t,y,h),start,options)

