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

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