function x = binoinv(y,n,p)
%BINOINV Inverse of the binomial cumulative distribution function (cdf).
%   X = BINOINV(Y,N,P) returns the inverse of the binomial cdf with 
%   parameters N and P. Since the binomial distribution is
%   discrete, BINOINV returns the least integer X such that 
%   the binomial cdf evaluated at X, equals or exceeds Y.
%
%   The size of X is the common size of the input arguments. A scalar input  
%   functions as a constant matrix of the same size as the other inputs.    
%
%   Note that X takes the values 0,1,2,...,N.

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

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

[errorcode y n p] = distchck(3,y,n,p);

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

% Initialize X to 0.
x = zeros(size(y));
cumdist = binopdf(x,n,p);

count = 0;

% Compare Y to the binomial distribution for each value of N.
while any(any(y > cumdist))  & any(any(n > count))
    count = count + 1;
    index = find(cumdist < y);
    x(index) = x(index) + 1;
    cumdist = cumdist + binopdf(count,n,p);
end

k1 = find(n < 0 | p < 0 | p > 1 | round(n) ~= n | y < 0 | y > 1 | isnan(y)); 
if any(k1)
   tmp = NaN;
    x(k1) = tmp(ones(size(k1))); 
end
