annotate toolboxes/FullBNT-1.0.7/bnt/CPDs/@tabular_CPD/Old/sample_node.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
rev   line source
wolffd@0 1 function y = sample_node(CPD, pev, nsamples)
wolffd@0 2 % SAMPLE_NODE Draw a random sample from P(Xi | x(pi_i), theta_i) (tabular)
wolffd@0 3 % Y = SAMPLE_NODE(CPD, PEV, NSAMPLES)
wolffd@0 4 %
wolffd@0 5 % pev(i,m) is the value of the i'th parent in sample m (if there are any parents).
wolffd@0 6 % y(m) is the m'th sampled value (a row vector).
wolffd@0 7 % (If pev is a cell array, so is y.)
wolffd@0 8 % nsamples defaults to 1.
wolffd@0 9
wolffd@0 10 if nargin < 3, nsamples = 1; end
wolffd@0 11
wolffd@0 12 %if nargin < 4, usecell = 0; end
wolffd@0 13 if iscell(pev), usecell = 1; else usecell = 0; end
wolffd@0 14
wolffd@0 15 if nsamples == 1, pev = pev(:); end
wolffd@0 16
wolffd@0 17 sz = CPD.sizes;
wolffd@0 18 nparents = length(sz)-1;
wolffd@0 19 if nparents==0
wolffd@0 20 y = sample_discrete(CPD.CPT, 1, nsamples);
wolffd@0 21 if usecell
wolffd@0 22 y = num2cell(y);
wolffd@0 23 end
wolffd@0 24 return;
wolffd@0 25 end
wolffd@0 26
wolffd@0 27 sz = CPD.sizes;
wolffd@0 28 [nparents nsamples] = size(pev);
wolffd@0 29
wolffd@0 30 if usecell
wolffd@0 31 pvals = cell2num(pev)'; % each row is a case
wolffd@0 32 else
wolffd@0 33 pvals = pev';
wolffd@0 34 end
wolffd@0 35
wolffd@0 36 psz = sz(1:end-1);
wolffd@0 37 ssz = sz(end);
wolffd@0 38 ndx = subv2ind(psz, pvals);
wolffd@0 39 T = reshape(CPD.CPT, [prod(psz) ssz]);
wolffd@0 40 T2 = T(ndx,:); % each row is a distribution selected by the parents
wolffd@0 41 C = cumsum(T2, 2); % sum across columns
wolffd@0 42 R = rand(nsamples, 1);
wolffd@0 43 y = ones(nsamples, 1);
wolffd@0 44 for i=1:ssz-1
wolffd@0 45 y = y + (R > C(:,i));
wolffd@0 46 end
wolffd@0 47 y = y(:)';
wolffd@0 48 if usecell
wolffd@0 49 y = num2cell(y);
wolffd@0 50 end
wolffd@0 51
wolffd@0 52
wolffd@0 53