To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.
root / _FullBNT / BNT / CPDs / @tabular_CPD / Old / sample_node.m @ 8:b5b38998ef3b
History | View | Annotate | Download (1.12 KB)
| 1 |
function y = sample_node(CPD, pev, nsamples) |
|---|---|
| 2 |
% SAMPLE_NODE Draw a random sample from P(Xi | x(pi_i), theta_i) (tabular) |
| 3 |
% Y = SAMPLE_NODE(CPD, PEV, NSAMPLES) |
| 4 |
% |
| 5 |
% pev(i,m) is the value of the i'th parent in sample m (if there are any parents). |
| 6 |
% y(m) is the m'th sampled value (a row vector). |
| 7 |
% (If pev is a cell array, so is y.) |
| 8 |
% nsamples defaults to 1. |
| 9 |
|
| 10 |
if nargin < 3, nsamples = 1; end |
| 11 |
|
| 12 |
%if nargin < 4, usecell = 0; end |
| 13 |
if iscell(pev), usecell = 1; else usecell = 0; end |
| 14 |
|
| 15 |
if nsamples == 1, pev = pev(:); end |
| 16 |
|
| 17 |
sz = CPD.sizes; |
| 18 |
nparents = length(sz)-1; |
| 19 |
if nparents==0 |
| 20 |
y = sample_discrete(CPD.CPT, 1, nsamples); |
| 21 |
if usecell |
| 22 |
y = num2cell(y); |
| 23 |
end |
| 24 |
return; |
| 25 |
end |
| 26 |
|
| 27 |
sz = CPD.sizes; |
| 28 |
[nparents nsamples] = size(pev); |
| 29 |
|
| 30 |
if usecell |
| 31 |
pvals = cell2num(pev)'; % each row is a case |
| 32 |
else |
| 33 |
pvals = pev'; |
| 34 |
end |
| 35 |
|
| 36 |
psz = sz(1:end-1); |
| 37 |
ssz = sz(end); |
| 38 |
ndx = subv2ind(psz, pvals); |
| 39 |
T = reshape(CPD.CPT, [prod(psz) ssz]); |
| 40 |
T2 = T(ndx,:); % each row is a distribution selected by the parents |
| 41 |
C = cumsum(T2, 2); % sum across columns |
| 42 |
R = rand(nsamples, 1); |
| 43 |
y = ones(nsamples, 1); |
| 44 |
for i=1:ssz-1 |
| 45 |
y = y + (R > C(:,i)); |
| 46 |
end |
| 47 |
y = y(:)'; |
| 48 |
if usecell |
| 49 |
y = num2cell(y); |
| 50 |
end |
| 51 |
|
| 52 |
|
| 53 |
|