LINE Solver
MATLAB API documentation
Loading...
Searching...
No Matches
DiscreteSampler.m
1classdef DiscreteSampler < DiscreteDistribution
2 % A class for discrete distributions specified from the probability mass function
3 %
4 % Copyright (c) 2012-2026, Imperial College London
5 % All rights reserved.
6
7 methods
8 function self = DiscreteSampler(p,x)
9 % SELF = DISCRETESAMPLER(P,X)
10
11 % Construct a discrete distribution from a finite probability
12 % vector p at the points specificied in vector x
13
14 % p(i) is the probability of item i
15 % x(i) is the value of item i
16 n = length(p);
17 if nargin<2 %~exist('x','var')
18 x=1:n;
19 end
20 self@DiscreteDistribution('DiscreteSampler',3,[min(x),max(x)]);
21 setParam(self, 1, 'p', p(:)');
22 setParam(self, 2, 'x', x(:)');
23 setParam(self, 3, 'f', cumsum(p(:)')/sum(p));
24 end
25
26 function ex = getMean(self)
27 % EX = GETMEAN()
28
29 % Get distribution mean
30 p = self.getParam(1).paramValue;
31 n = length(p);
32 ex = sum(p*(1:n)');
33 end
34
35 function SCV = getSCV(self)
36 % SCV = GETSCV()
37
38 % Get distribution squared coefficient of variation (SCV = variance / mean^2)
39
40
41 p = self.getParam(1).paramValue;
42 n = length(p);
43 e2 = sum(p*(1:n).^2');
44 var = e2 - ex^2;
45 SCV = var / ex^2;
46 end
47
48 function X = sample(self, n)
49 % X = SAMPLE(N)
50
51 x = self.getParam(2).paramValue;
52 f = self.getParam(3).paramValue;
53 r = rand(n,1);
54 X = x(maxpos(min(repmat(r,1,size(f,2))<=f,2)')');
55 end
56
57 function Ft = evalCDF(self,k)
58 % FT = EVALCDF(SELF,K)
59
60 f = self.getParam(3).paramValue;
61 if k>=1 && k<length(f)
62 Ft = f(k);
63 else
64 Ft = 0;
65 end
66 end
67
68 function pk = evalPMF(self, v)
69 % PK = EVALPMF(V)
70
71 p = self.getParam(1).paramValue;
72 x = self.getParam(2).paramValue;
73 if nargin<2 %~exist('v','var')
74 pk = p;
75 return
76 end
77 for i=1:length(v)
78 pk(i) = p(find(x==v(i),1));
79 end
80 end
81
82 function bool = isDisabled(self)
83 % BOOL = ISDISABLED()
84
85 p = self.getParam(1).paramValue;
86 bool = any(isnan(p));
87 end
88 end
89
90end
91