function y = ncfpdf(x,nu1,nu2,delta)
%NCFPDF Noncentral F probability density function (pdf).
%   Y = NCTPDF(X,NU1,NU2,DELTA) Returns the noncentral F pdf with with numerator 
%   degrees of freedom (df), NU1, denominator df, NU2, and noncentrality
%   parameter, DELTA, at the values in X.
%
%   The size of Y is the common size of the input arguments. A scalar input  
%   functions as a constant matrix of the same size as the other inputs.     

%   Reference:
%      [1]  Johnson, Norman, and Kotz, Samuel, "Distributions in
%      Statistics: Continuous Univariate Distributions-2", Wiley
%      1970 p. 191. (equation 5)
%      [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:27:15 $


if nargin < 1, 
    error('Requires at least one input argument.');
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

[m,n] = size(x);

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

% Set up for infinite sum.
done = 0;
j = 0;
g = nu1.*x./nu2;
% Sum the series.
while ~done
   b      = beta(j + nu1./2,nu2./2);
   tmp    = poisspdf(j,delta/2).*(g.^(j-1+nu1/2))./((1+g).^(j + (nu1 + nu2)./2));
   deltay = tmp./b;
   y = y + deltay;
   
   % Convergence test.
   if all(deltay(:)./(y(:)+eps^(1/4)) < sqrt(eps))
      done = 1;
   end
   j = j + 1;
end
y = nu1.*y./nu2;

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