% This script demonstrates least squares fitting using fminsearch

%% Create a data set

% the model is a simple line

A=3.5;
B=7;

x=(1:100)';
y=A*x+B;

% add noise
sigma=10; %this is the sigma in normally distributed noise model
y_noise=y+sigma*randn(size(y));

%% Find A and B by minimizing a function

% see 'doc fminsearch'

options=optimset;

X0=[1 1]; %these are the starting guesses
func=@LSQfunc; %this points to the function that will be minimized

% X0 and the inputs after 'options' get passed to the function 'func'
[out]=fminsearch(func,X0,options,x,y_noise);

%the parameters that minimize the function
A_found=out(1)
B_found=out(2)

fit_y=A_found*x+B_found;

%% Plot the results

figure
hold on
plot(x,y,'k','linewidth',2)
plot(x,y_noise,'r','linewidth',2)
plot(x,fit_y,'g','linewidth',2)
legend('underlying data','noisy data','fit results')
xlabel('X (m)','fontsize',16)
ylabel('Y (m)','fontsize',16)
set(gca,'fontsize',14)







