LINE Solver
MATLAB API documentation
Loading...
Searching...
No Matches
randp.m
1function X = randp(P,varargin) ;
2% RANDP - pick random values with relative probability
3%
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.
7%
8% All values of PROB should be equal to or larger than 0.
9%
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.
14%
15% Example:
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)
19%
20% R = randp([1 1 0 0 1],10,1)
21% % 10 samples evenly drawn from [1 2 5]
22%
23%
24% Also see RAND, RANDPERM
25% RANDPERMBREAK, RANDINTERVAL, RANDSWAP (MatLab File Exchange)
26
27% Created for Matlab R13+
28% version 2.0 (feb 2009)
29% (c) Jos van der Geest
30% email: jos@jasen.nl
31%
32% File history:
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
37% previous algorithm)
38
39error(nargchk(2,Inf,nargin)) ;
40
41try
42 X = rand(varargin{:}) ;
43catch
44 E = lasterror ;
45 E.message = strrep(E.message,'rand','randp') ;
46 rethrow(E) ;
47end
48
49P = P(:) ;
50
51if any(P<0),
52 error('All probabilities should be 0 or larger.') ;
53end
54
55if isempty(P) || sum(P)==0
56 warning([mfilename ':ZeroProbabilities'],'All zero probabilities') ;
57 X(:) = 0 ;
58else
59 [junk,X] = histc(X,[0 ; cumsum(P(:))] ./ sum(P)) ;
60end
61
62% Method used before version 2
63% X = rand(varargin{:}) ;
64% sz = size(X) ;
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 ;
69% X = reshape(X,sz) ;
70
71
72
73
74
75
76