function [coeffstats] = tstats(Y, X)

% Tstats  Calculates T statistics for coefficients
%
%           Usage: [coeffstats] = tstats(Y, X)
%
% Basic calculations adapted from a MATLAB script by G. Anthony Reina
% called mregress.m available through the File Exchange at
% http://www.mathworks.com/matlabcentral/
% 
% Returns the coefficients, standard deviation of the coefficients, T
% statistics and associated p values as a 4 column matrix
%
% Author : Brian Kirtlan 28/05/04

% Check inputs

if (nargin < 2)
   error('tstats requires at least 2 input variables');
end

[nx, colx] = size(X);
[ny, coly] = size(Y);

if nx~=ny, 
    error('Rows in Y and X must be the same'); 
end 

if coly ~= 1, 
    error('Y must be a vector'); 
end

if (sum(X(:,1))~=nx | colx<2),
    error('The first row of X must contain 1s to allow a Y intercept to be calculated');
end

n = nx;
k = colx-1;

% Solve regression coefficients

xtxi = inv(X' * X);
coeffs = X\Y;

% Fitted values

Yhat = X * coeffs;
residuals = Y - Yhat;

% Calc standard deviation and t-values

stderr = sqrt(residuals'*residuals/(n-k-1));
covariance = xtxi.*stderr^2;
sd = sqrt(diag(covariance, 0));
pvalues = 2*(1-tcdf(abs(coeffs./sd),(n-(k+1))));
coeffstats = [coeffs,sd,(coeffs./sd),pvalues];
