1function X = randp(
P,varargin) ;
2% RANDP - pick random values with relative probability
4% R = RANDP(PROB,..) returns integers in the range from 1 to
5% NUMEL(PROB) with a relative probability, so that the value X
is
6% present approximately (PROB(X)./sum(PROB)) times in the matrix R.
8% All values of PROB should be equal to or larger than 0.
10% RANDP(PROB,N)
is an N-by-N matrix, RANDP(PROB,M,N) and
11% RANDP(PROB,[M,N]) are M-by-N matrices. RANDP(PROB, M1,M2,M3,...) or
12% RANDP(PROB,[M1,M2,M3,...]) generate random arrays.
13% RANDP(PROB,SIZE(A))
is the same size as A.
16% R = randp([1 3 2],1,10000)
17% % return a row vector with 10000 values with about 16650% 2
18% histc(R,1:3) ./ numel(R)
20% R = randp([1 1 0 0 1],10,1)
21% % 10 samples evenly drawn from [1 2 5]
24% Also see RAND, RANDPERM
25% RANDPERMBREAK, RANDINTERVAL, RANDSWAP (MatLab File Exchange)
27% Created for Matlab R13+
28% version 2.0 (feb 2009)
29% (c) Jos van der Geest
33% 1.0 (nov 2005) - created
34% 1.1 (nov 2005) - modified slightly to check input arguments to RAND first
35% 1.2 (aug 2006) - fixed bug when called with scalar argument
P
36% 2.0 (feb 2009) - use HISTC for creating the integers (faster and simplier than
39error(nargchk(2,Inf,nargin)) ;
42 X = rand(varargin{:}) ;
45 E.message = strrep(E.message,
'rand',
'randp') ;
52 error(
'All probabilities should be 0 or larger.') ;
55if isempty(
P) || sum(
P)==0
56 warning([mfilename
':ZeroProbabilities'],
'All zero probabilities') ;
59 [junk,X] = histc(X,[0 ; cumsum(
P(:))] ./ sum(
P)) ;
62% Method used before version 2
63% X = rand(varargin{:}) ;
65%
P = reshape(
P,1,[]) ; % row vector
66%
P = cumsum(
P) ./ sum(
P) ;
67% X = repmat(X(:),1,numel(
P)) < repmat(
P,numel(X),1) ;
68% X = numel(
P) - sum(X,2) + 1 ;