Вы находитесь на странице: 1из 6

clear; % Clears all variables from memory

[Al_thick, Al_rate, Al_err] = textread('AgAttenFromAlE.txt','%f %f %f');


[Mo_thick, Mo_rate, Mo_err] = textread('AgAttenFromMo.txt','%f %f %f');
[Mo1_thick, Mo1_rate, Mo1_err] = textread('AgAttenFromMo1.txt','%f %f %f');
[Cu_thick, Cu_rate, Cu_err] = textread('AgAttenFromCu.txt','%f %f %f');

x = Mo1_thick;
y = Mo1_rate;
sig = Mo1_err;

%load gauss3.dat; % Loads sample data set 'gauss3.dat' into memory


% This script assumes that the data is in a text file,

% divided into 2 or 3 columns (depending on whether


there is
% a column for the error)
%x = gauss3(:,1); % Assigns the first column of mydata to a vector
called 'x'
%y = gauss3(:,2); % Assigns the second column of mydata to a vector
called 'y'

% There are several different ways to assign your error


vector
% You might want to use one of these three methods
below.

sigma = 2.5; % Constant error value, variance of gauss3 data set is


6.25.
%sig = ones(size(x))*sigma; % creates a constant vector the same size as 'x'
w/value sigma
%sig = sqrt(y); % sets sigma to the square root of 'y' for Poisson
statistics
%sig = mydata(:,3); % Assigns the third column to a vector called 'sig'

% For non-linear fits, you will need to create a Matlab 'function handle' for the
% functional form you want to fit. % Example 'function_handles'
% function_sin = @(x,a) a(1)*sin(a(2)*x+a(3));
% function_gaussian=@(x,a) a(1)*exp(-a(2)*((x-a(3)).^2));
function_exp=@(x,a) a(1)*exp(a(2)*x);

%function_gauss3=@(x,a) a(1)*exp(-a(2)*x)+a(3)*exp(-((x-a(4))/a(5)).^2)+a(6)*exp(-
((x-a(7))/a(8)).^2);

% function_gauss3=@(x,a) a(1)+a(2)*exp(-x/a(4))+a(3)*exp(-x/a(5));
% For non-linear fits using the Marquardt method, if you want to use
% analytic expressions instead of numerical derivatives, enter the
% expressions for derivatives in the following cell dYda, and let sgn be 1
% instead of 0. Note: the definition of dYda cannot be commented out since
% it has to be defined no matter whether it is actually used.

dYda={@(x,a) 1,
@(x,a) exp(-x/a(4)),
@(x,a) exp(-x/a(5)),
@(x,a) a(2)/a(4)^2*exp(-x/a(4)).*x,
@(x,a) a(3)/a(5)^2*exp(-x/a(5)).*x};
sgn=0;
a0 = [107 -30]; % Initial guestimates of fit parameters

% Junior Lab supports two Matlab fitting scripts which you may find useful:
% 'levmar' and 'fitnonlin' for non-linear fits and 'fitlin' for linear fits.
% All of these algorithms are based on the methods found in Bevington and Robinson.

% These scripts are well commented and we encourage you to inspect them to
strengthen
% your understanding of and intuition for fitting data.

% ** NON-LINEAR FITS **
% gradient search - Bevington and Robinson Section 8.4, Page 153
% [a,aerr,chisq,yfit] = fitnonlin(x,y,sig,function_gauss3,a0);

% Levenberg-Marquardt method - Bevington and Robinson Section 8.6, Page 161


[a,aerr,chisq,yfit,corr] = levmar(x,y,sig,function_exp,a0,dYda,sgn);
aerr

% Here the data in 'x' and 'y' are fit to the % function created by the function
handle 'function_gauss3'.
% Inputs: x -- the x data to fit
% y -- the y data to fit
% sig -- the uncertainties on the data points
% fitfun -- the name of the function to fit to
% a0 -- the initial guess at the parameters
% Outputs: a -- the best fit parameters
% aerr -- the errors on these parameters
% chisq -- the final value of chi-squared
% yfit -- the value of the fitted function
% at the points in x
%
% * NOTE * - since fitnonlin is an iterative function, you can vary
% the step size and tolerance used in the fitting process. These are
% specified within the 'fitnonlin.m' function

% ** LINEAR FITS **
% If you wish to fit your data to a straight line, you can use the function
% 'fitlin.m' This function is also taken directly from the pages of Bevington
% and Robinson Ch. 6 (p. 114) and it is very easy to follow. The usage of
% fitlin is as follows:
%
% [a,aerr,chisq,yfit] = fitlin(x,y,sig)
%
% Inputs: x -- the x data to fit
% y -- the y data to fit
% sig -- the uncertainties on the data points
%
% Outputs: a -- the best fit parameters
% aerr -- the errors on these parameters
% chisq -- the value of chi-squared
% yfit -- the value of the fitted function
% at the points in x

Parameters = [a', aerr'];

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% EVALUATING THE GOODNESS OF YOUR FIT %%%
%%% %%%
%%% More information on the following can be found %%%
%%% in the Matlab Help under 'Evaluating the Goodness of Fit' %%%
%%% in the Curve Fitting Toolbox %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

level = 0.68; % confidence level 68% =1-sigma, 95% = 2-sigma


dof = length(x) - length(a); % degree of freedom
RChiSquare = chisq/dof
residuals = y-yfit;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The confidence bounds for fitted coefficients are given by
% [b-t*sqrt(S),b+t*sqrt(S)].
% b are the coefficients produced by the fit, t depends on the confidence
% level, and is computed using the inverse of student's t cumulative
% distribution function, S is the vector of diagonal elements from the
% estimated covariance matrix. 'aerr' is the square root of 'S'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
width = tinv(level,dof)*aerr;
lower = a - width;
upper = a + width;
FitResults = [a', lower', upper']

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% This section sets up 'positions' for various graphics to be displayed
%% on your computer monitor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

set(0,'Units','pixels')
scnsize=get(0,'ScreenSize');
% [left bottom width height]
pos1=[5,scnsize(4)/2+100,scnsize(3)/2-8,scnsize(4)/2-98];
pos2=[pos1(1)+scnsize(3)/2+20,pos1(2),pos1(3),pos1(4)];
pos3=[5,35,pos1(3),pos1(4)];
pos4=[pos2(1),pos3(2),pos1(3),pos1(4)];

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Plot the 1st figure %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure('Position',pos1); % opens figure 1 and makes it active
clf; % clears the active figure
hold on; % Makes matlab plot without clearing the graph
errorbar (x,y,sig,'b.'); % Plots 'y' vs. 'x' with errobars of plus/minus 'sig'
(RAW DATA)
%plot(x,yfit,'r.'); % Plots the fitted curve
t = [0:.0005:0.013];
yy = a(1)*exp(a(2)*t);
plot(t,yy,'k');
axis([x(1),x(length(x)),min(y)-2*max(sig),max(y)+2*max(sig)]); % sets visible
range of the plot
title('Plot of rate of Ag radiation vs. Mo absorber thickness','fontsize',16);
text(5,35,'a(1)*exp(-a(2)*x)+a(3)*exp(-((x-a(4))/a(5)).^2)+a(6)*exp(-((x-
a(7))/a(8)).^2)','fontsize',10);
xlabel('Thickness of Absrobers (cm)','fontsize',14); ylabel('Radiation rate
(counts/sec)','fontsize',14);
legend('Attenuation Data Points','Fitted Curve'); % see 'helpwin legend'
for more information
str1=num2str(RChiSquare,2);
text(5,25,['\chi^2_{\nu-1} = ' str1]);
%str1=num2str(a(7)-a(4),2);
%str2=num2str(sqrt(width(7)^2+width(4)^2),2);
text(5,15,['Energy Splitting = ' str1 '\pm' str2 'nm']);
plot(zeros(size(y))+a(4),y,'r-');
plot(zeros(size(y))+a(7),y,'r-');
text(150,120,'Fit gaussian centers indicated by red lines');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Plot the 2nd figure %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure('Position',pos2);
hold on;
plot(x,zeros(size(x)),'r-');
text(5,-1,'Its useful to point out some value for comparison for your audience
(like this read line at zero');
plot(x,residuals,'b.');
xlabel('Energy (eV)','fontsize',14);
ylabel('Residuals (obs-fit)','fontsize',14);
title('Residuals are useful for examining quality of fit','fontsize',16);
text(30,6,'A good fit will produce residuals with a mean of zero and without
structure','fontsize',12);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Now plot the 3rd figure %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure('Position',pos3,'Name','Figure Example Using subplot to display related
data');
clf;
subplot(3,3,1);
plot(x,y);
xlabel('\theta = 10');
grid on;
subplot(3,3,2);
plot(x+10,y+10);
title('Use the subplot command to display related data','fontsize',14);
xlabel('\theta = 15');
grid on;
subplot(3,3,3);
plot(x+20,y+20);
xlabel('\theta = 30');
grid on;
subplot(3,3,4);
plot(x+30,y+25);
xlabel('\theta = 40');
grid on;
subplot(3,3,5);
plot(x+40,y+30);
xlabel('\theta = 50');
grid on;
subplot(3,3,6);
xlabel('\theta = 60');
plot(x+50,y+35);
grid on;
subplot(3,3,7);
plot(x+60,y+40);
xlabel('\theta = 70');
grid on;
subplot(3,3,8);
plot(x+70,y+45);
xlabel('\theta = 80');
grid on;
subplot(3,3,9);
plot(x+80,y+50);
xlabel('\theta = 90');
grid on;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Now plot the 4th figure %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure('Position',pos4,'Name','Figure Example Demonstrating Various axis
properties');
clf;
subplot(3,3,1);
plot(x,y);
hold on;
ym=mean(y);
plot([0 400],[ym ym],'Color','red')
xlabel('Default plot(x,y)');

subplot(3,3,2);
plot(x,y);
xlabel('axis tight');
axis tight;
title('Using axis properties to achieve various looks','fontsize',14);

subplot(3,3,3);
plot(x,y);
xlabel('axis[50 150 -20 100]');
axis([50 150 -20 100]);

subplot(3,3,4);
semilogx(x,y);
xlabel('semilogx(x,y)');

subplot(3,3,5);
semilogy(x,y);
xlabel('semilogy(x,y)')'

subplot(3,3,6);
loglog(x,y);
xlabel('loglog(x,y)');

subplot(3,3,7);
plot(x,y);
grid on;
xlabel('grid on');

subplot(3,3,8);
plot(x,y);
grid minor;
xlabel('grid minor;');

subplot(3,3,9);
plot(x,y);
xlabel('\theta = 90');
axis off;
text(20,20,'axis off');
% --------------------- Matlab Notes ---------------------------------
% ------------ See page 2-74 to 2-78 in curvefit.pdf ----------------
% Here are the definitions of some values used in the matlab curve fitting
% toolbox:
% y - response value, y_tilde - fit to the response value, y_bar - mean
% SSE (Sum of Squares due to Error) = weighted sum of (y - y_tilde)^2.
% SSR (Sum of Squares of the Regression)
% = weighted sum of (y_tilde - y_bar)^2
% SST (Total Sum of Squares) = weighted sum of (y - y_bar)^2
% SST = SSE + SSR
% R-square = SSR / SST = 1 - (SSE / SST)
% v - degree of freedom
% v = n - m (number of response values - number of fitted coefficients)
% adjust R-square = 1 - (SSE / SST) * (n - 1) / v
% The adjust R-square statistic can take on any value less than or equal to
% 1, with a value closer to 1 indicating a better fit.
% MSE (Mean Squared Error) = SSE / v (the same as R-chi-square)
% RMSE (Root Mean Squared Error) = sqrt(MSE)
% A RMSE value closer to 0 indicates a better fit.
% ----------------------------------------------------------------------

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% MATLAB Fitting Template Script %
% MIT Junior Lab %
% 28-Aug-2007 Version 2.2 %
% %
% Junior Lab Technical Staff w/ %
% %
% significant contributions from %
% Jim Kiger, William McGehee %
% and Xuangcheng Shao %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Вам также может понравиться