function [p, t, df] = lyngby_ts_uttest(d1, d2)

% lyngby_ts_uttest	- Student's t-test for unequal variances.
%
%       LYNGBY_TS_UTTEST(X1, X2) gives the probability that Student's t
%       calculated on data X1 and X2, sampled from distributions
%       with different variances, is higher than observed, i.e.
%       the "significance" level.  This is used to test whether
%       two sample have significantly different means.
%       [P, T] = LYNGBY_TS_UTTEST(X1, X2) gives this probability P and the
%       value of Student's t in T. The smaller P is, the more
%       significant the difference between the means.
%       E.g. if P = 0.05 or 0.01, it is very likely that the
%       two sets are sampled from distributions with different
%       means.
%
%       This works if the samples are drawn from distributions with
%       DIFFERENT VARIANCE. Otherwise, use LYNGBY_TSTTEST.
%
% See also: LYNGBY_TS_TTEST, LYNGBY_TS_PTTEST.
%
%	Date		Author		Version
%       1997-06-01      Cyril Goutte    Initial Code
%       1997-06-15      Peter Toft      Modified to fit lyngby + optimization

[l1 c1] = size(d1) ;
n1 = l1 * c1 ;
x1 = reshape(d1, l1 * c1, 1) ;
[l2 c2] = size(d2) ;
n2 = l2 * c2 ;
x2 = reshape(d2, l2 * c2, 1) ;

a1 = mean(x1);
v1 = std(x1).^2;
a2 = mean(x2);
v2 = std(x2).^2;

vn1 = v1 / n1;
vn2 = v2 / n2;

df = (vn1 + vn2).^2/( vn1.^2 / (n1 - 1) + vn2.^2 / (n2 - 1) ) ;
t = (a1 - a2) / sqrt( vn1 + vn2 ) ;
p = betainc( df / (df + t*t), 0.5*df, 0.5) ;

