程序不是我写的,是在其他资料里面找的。程序如下:
% -------------------------------------------------------
function x = rndreject(l,type,options)
%RNDREJECT Inverse of the cumulative distribution function (cdf) of some
% discrete distribution. This fuction is used to generate randm variate
% with special cdf.
% X = RNDREJECT(L,TYPE, OPTIONS) returns the cumulative distribution
% function of TYPE with parameter OPTIONS at the probabilities in L.
% RNDREJECT uses rejection method to generate nonuniform distribution.
%
% TYPE OPTIONS PDF
% -------------------------------------------------------
% Binomial [n p] P(n,x)*p^x*(1-p)^(n-x)
% Poission b b^x/x!*exp(-b)
% Geometric p p*(1-p)^x
% Hypergeometric [M,K,n] P(K,x)*P(M-K,n-x)/P(M,n)
% -------------------------------------------------------
%
% See also BINOINV, POISSINV%
%---------------------------------------------------------------------------
% xywu
% Fudan university.
%
% $Revision: 1.0 $
% $Date: 03/20/2002 $
%
%---------------------------------------------------------------------------
if nargin<3
error('Requires at least three input arguments.');
end
% chang TYPE to standard case
type = lower(type);
type(1) = upper(type(1));
x = [];
switch type
case 'Binomial'
n = options(1);
q = options(2);
y = 0:n;
pdf = factorialv(n)./factorialv(y)./factorialv(n-y).*q.^y.*(1-q).^(n-y);
a = max(pdf);
count = 1;
while count
r1 = ceil(rand(1)*n);
r2 = rand(1);
pdf = factorial(n)/factorial(r1)/factorial(n-r1)*q^r1*(1-q)^(n-r1);
if r2*a
x(count) = r1;
count = count+1;
end
end
case 'Poission'
b = options(1);
a = b^b/factorial(b)*exp(-b);
count = 1;
while count
r1 = ceil(rand(1)*b*b);
r2 = rand(1);
pdf = b^r1/factorial(r1)*exp(-b);
if r2*a
x(count) = r1;
count = count+1;
end
end
otherwise
error('Illegal type!');
end
%---------------------------------------------------------------------------
% Factorial function for vector input
function f = factorialv(x)
f = zeros(1,length(x));
for i = 1:length(x)
f(i) = factorial(x(i));
end
return;
%-----------------------------------------------------------
我也在看关于Matlab的书了,但是感觉有点无从下手。大家能给推荐点入门的书吗?