lrtest.m 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. function [p, teststat] = lrtest(varargin)
  2. % Based on https://statlect.com/fundamentals-of-statistics/likelihood-ratio-test
  3. if isnumeric(varargin{1})
  4. % Assume we are doing the form of fullLL, redLL, dof
  5. fLL = varargin{1};
  6. rLL = varargin{2};
  7. dof = varargin{3};
  8. varargin = varargin(4:end);
  9. elseif isobject(varargin{1})
  10. if ismethod(varargin{1},'fixedEffects')
  11. % This is a mixed effect model
  12. error('Mixed-Effects models not get implemented.\n Use compare');
  13. end
  14. % Assume we were passed in model objects.
  15. m1 = varargin{1};
  16. m2 = varargin{2};
  17. m1_params = m1.NumEstimatedCoefficients;
  18. m2_params = m2.NumEstimatedCoefficients;
  19. if m1_params > m2_params
  20. fullm = m1;
  21. redm = m2;
  22. else
  23. fullm = m2;
  24. redm = m1;
  25. end
  26. dof = fullm.NumEstimatedCoefficients - redm.NumEstimatedCoefficients;
  27. fLL = fullm.LogLikelihood;
  28. rLL = redm.LogLikelihood;
  29. varargin = varargin(3:end);
  30. end
  31. if dof==0
  32. error('Models are not nested - same number of free params');
  33. end
  34. teststat = 2*(fLL - rLL);
  35. p=1-chi2cdf(teststat, dof);
  36. fprintf('Full Model log likelihood:\t %.3f\n', fLL);
  37. fprintf('Reduced Model log likelihood:\t %.3f\n', rLL);
  38. fprintf('Extra parameters in full model:\t %d\n', dof);
  39. fprintf('\t\tChi-Sqr Test, \tp=%.4f\n', p);