function y = nctpdf(x,v,delta)
%NCTPDF Noncentral T probability density function (pdf).
%   Y = NCTPDF(X,V,DELTA) Returns the noncentral T pdf with V degrees 
%   of freedom 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 pp. 204-205 equation 8.
%      [2]  Evans, Merran, Hastings, Nicholas and Peacock, Brian,
%      "Statistical Distributions, Second Edition", Wiley
%      1993 pp. 147-148.

%   B.A. Jones 4-21-95
%   Copyright (c) 1993-96 by The MathWorks, Inc.
%   $Revision: 2.4 $  $Date: 1996/02/21 18:34:00 $


if nargin < 1, 
    error('Requires at least one input argument.');
end

[errorcode, x, v, delta] = distchck(3,x,v,delta);

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

%   Initialize Y to zero.
y = zeros(size(x));

k = find(v > 0 & round(v) == v);
if any(k)
    nu = v(k);
   d = delta(k);
   t = x(k);
    term = exp(-0.5.*(log(pi)+log(nu)) -(d.^2)/2  + gammaln((nu+1)/2) - gammaln(nu/2) ...
          + ((nu+1)/2).*(log(nu)-log(nu+t.^2)));

    infsum = zeros(size(k));
    % Set up for infinite sum.
    done = 0;
   j = 0;
   % Sum the series.
   while ~done
      newterm = ((t.*d.*sqrt(2)).^j) .* exp(gammaln((nu+j+1)/2)  - gammaln((nu+1)./2) ...
                -gammaln(j+1) - (j./2).*log(nu+t.^2));
      infsum = infsum + newterm;
       % Convergence test.
       if all(newterm(:)./infsum(:) < eps^(3/4))
          done = 1;
       end
      j = j + 1;
   end
   y(k) = term .* infsum;
end

k1 = find(v <= 0 | round(v) ~= v);
if any(k1)
    tmp   = NaN;
    y(k1) = tmp(ones(size(k1)));
end
