Home > matutils > chisq.m

chisq

PURPOSE ^

chi2 = chisq(pars,func,y,e,x...)

SYNOPSIS ^

function chi2 = chisq(pars,func,y,e,varargin)

DESCRIPTION ^

 chi2 = chisq(pars,func,y,e,x...)

 Calculate the ChiSq between a set of points predicted by function func
 with parameters pars evaluated at x, and the observed values y
 with errors e.

 Note that for fitting count histograms should use hfit to get
 correct Poisson count errors.

 eg: x=-5:0.1:5; y=gauss([10,0,1],x); y=y+randn(size(y)); e=ones(size(y));
     plot(x,y,'.');
     p=fminsearch('chisq',[10,0,1],[],'gauss',y,e,x)
     [p,pe]=matmin('chisq',[10,0,1],[],'gauss',y,e,x)
     hold on; plot(x,gauss(p,x),'r'); hold off

 See also logl

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 function chi2 = chisq(pars,func,y,e,varargin)
0002 % chi2 = chisq(pars,func,y,e,x...)
0003 %
0004 % Calculate the ChiSq between a set of points predicted by function func
0005 % with parameters pars evaluated at x, and the observed values y
0006 % with errors e.
0007 %
0008 % Note that for fitting count histograms should use hfit to get
0009 % correct Poisson count errors.
0010 %
0011 % eg: x=-5:0.1:5; y=gauss([10,0,1],x); y=y+randn(size(y)); e=ones(size(y));
0012 %     plot(x,y,'.');
0013 %     p=fminsearch('chisq',[10,0,1],[],'gauss',y,e,x)
0014 %     [p,pe]=matmin('chisq',[10,0,1],[],'gauss',y,e,x)
0015 %     hold on; plot(x,gauss(p,x),'r'); hold off
0016 %
0017 % See also logl
0018 
0019 % If no data provided
0020 if(isempty(y))
0021   chi2=0;
0022   return
0023 end
0024 
0025 % Zero errors can result when assume e=sqrt(n) but they make no sense
0026 % so following paw I set the error huge so the point it excluded.
0027 e(e==0)=1e99;
0028 
0029 % Evaluate the function
0030 f=feval(func,pars,varargin{:});
0031 
0032 % This is the correct behavior when fitting to complex visibilities...
0033 if(~isreal(y))
0034   y=[real(y),imag(y)];  f=[real(f),imag(f)];
0035   % Allow for real or complex error
0036   if(~isreal(e))
0037     e=[real(e),imag(e)];
0038   else
0039     e=[e,e];
0040   end
0041 end
0042 
0043 
0044 % Calculate chi2 - don't want any nan's to fuck things up.
0045 chi2=nansum(((y(:)-f(:))./e(:)).^2);

Generated on Sun 14-Jun-2015 17:12:45 by m2html © 2005