function [p, f] = lyngby_ts_ftest(d1, d2)

% lyngby_ts_ftest	- F-test for two samples.
%
%       LYNGBY_TS_FTEST(X1, X2) gives the probability that the F value
%       calculated as the rati of the variances of the two samples is
%       greater than observed, i.e. the significance level.
%       [P, F] = LYNGBY_TS_FTEST(X1, X2) gives the probability P and returns
%       the value of F.
%
%       A small value of P would lead to reject the hypothesis that
%       both data sets are sampled from distributions with the same
%       variances.
%
% 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;

f = v1 / v2 ;
df1 = n1 - 1 ;
df2 = n2 - 1 ;
if (v1 > v2)
   p = 2 * betainc( df2 / (df2 + df1 * f), df2 * 0.5, df1 * 0.5) ;
else
   f = 1 / f ;
   p = 2 * betainc( df1 / (df1 + df2 * f), df1 * 0.5, df2 * 0.5) ;
end
if (p > 1)
   p = 2 - p ;
end   
