function p = ncfcdf(x,nu1,nu2,delta)
%NCFCDF Noncentral F cumulative distribution function (cdf).
%   P = NCFCDF(X,NU1,NU2,DELTA) Returns the noncentral F cdf with numerator 
%   degrees of freedom (df), NU1, denominator df, NU2, and noncentrality
%   parameter, DELTA, at the values in X.
%
%   The size of P is the common size of the input arguments. A scalar input  
%   functions as a constant matrix of the same size as the other inputs.     

%   References:
%      [1]  Johnson, Norman, and Kotz, Samuel, "Distributions in
%      Statistics: Continuous Univariate Distributions-2", Wiley
%      1970 p. 192.
%      [2]  Evans, Merran, Hastings, Nicholas and Peacock, Brian,
%      "Statistical Distributions, Second Edition", Wiley
%      1993 p. 73-74.

%   B.A. Jones 2-7-95
%   Copyright (c) 1993-96 by The MathWorks, Inc.
%   $Revision: 2.4 $  $Date: 1996/03/03 22:26:43 $

if nargin <  3, 
    error('Requires three input arguments.'); 
end

[errorcode x nu1 nu2 delta] = distchck(4,x,nu1,nu2,delta);

if errorcode > 0
    error('Requires non-scalar arguments to match in size.');
end

% Initialize P to zero.
[m,n] = size(x);
p = zeros(m,n);

%Value passed to Beta distribution function.
tmp = nu1.*x./(nu2+nu1.*x);

% Set up for infinite sum.
done = 0;
j = 0;

% Sum the series.
while ~done
   deltap = poisspdf(j,delta/2).*betacdf(tmp,j+nu1/2,nu2/2);
   p = p + deltap;
   
   % Convergence test.
   if all(deltap(:)./(p(:)+(eps^(1/4))) < sqrt(eps))
      done = 1;
   end
   j = j + 1;
end

% Return NaN if X is negative or NU1 or NU2 are not a positive integers.
k1 = find(x < 0 | round(nu1) ~= nu1 | round(nu2) ~= nu2);
if any(k1)
    tmp   = NaN; 
    p(k1) = tmp(ones(size(k1)));
end
