%% fitter usage example
% we will fit Lorentzian shape function 
% Lorentzian= A/ (1 + ((x-x0)/width)^2)
% generally Lorentzian is a function of several parameters
% A - amplitude we will use p(1) for it
% x0 - offset   we will use p(2)
% width - HWHM width  we will use p(3)
% so our Lorentzian function will be
Lorentzian=@(x,p) (p(1) / (1+((x-p(2))/p(3))^2));

% load initial data file
data=load('data_to_fit.dat');
x=data(:,1); % 1st column is x
y=data(:,2); % 2nd column is y

pin=[3,3,1];
disp('initial guess pin = ');
disp(pin);

% let's fit
% note that Lorentzian is already defined as a handle
[pout, yfit, res] = fitter(x,y, Lorentzian, pin);

disp('fitted parameters pout =')
disp(pout)

figure(1)
subplot(2,1,1)
plot(x,y,'x'); % plotting data points
hold on;
plot(x,yfit,'r-'); % plotting fitted values
hold off;
legend('data','fit');
xlabel('x'); ylabel('y');
subplot(2,1,2)
plot(x,res,'x');  % plotting residuals
hold on;
plot(x,x*0, '-'); % this will plot a line along x axis
legend('residuals','');
xlabel('x'); ylabel('residuals');
hold off;


