wolffd@0: function y = sample_node(CPD, pev, nsamples) wolffd@0: % SAMPLE_NODE Draw a random sample from P(Xi | x(pi_i), theta_i) (tabular) wolffd@0: % Y = SAMPLE_NODE(CPD, PEV, NSAMPLES) wolffd@0: % wolffd@0: % pev(i,m) is the value of the i'th parent in sample m (if there are any parents). wolffd@0: % y(m) is the m'th sampled value (a row vector). wolffd@0: % (If pev is a cell array, so is y.) wolffd@0: % nsamples defaults to 1. wolffd@0: wolffd@0: if nargin < 3, nsamples = 1; end wolffd@0: wolffd@0: %if nargin < 4, usecell = 0; end wolffd@0: if iscell(pev), usecell = 1; else usecell = 0; end wolffd@0: wolffd@0: if nsamples == 1, pev = pev(:); end wolffd@0: wolffd@0: sz = CPD.sizes; wolffd@0: nparents = length(sz)-1; wolffd@0: if nparents==0 wolffd@0: y = sample_discrete(CPD.CPT, 1, nsamples); wolffd@0: if usecell wolffd@0: y = num2cell(y); wolffd@0: end wolffd@0: return; wolffd@0: end wolffd@0: wolffd@0: sz = CPD.sizes; wolffd@0: [nparents nsamples] = size(pev); wolffd@0: wolffd@0: if usecell wolffd@0: pvals = cell2num(pev)'; % each row is a case wolffd@0: else wolffd@0: pvals = pev'; wolffd@0: end wolffd@0: wolffd@0: psz = sz(1:end-1); wolffd@0: ssz = sz(end); wolffd@0: ndx = subv2ind(psz, pvals); wolffd@0: T = reshape(CPD.CPT, [prod(psz) ssz]); wolffd@0: T2 = T(ndx,:); % each row is a distribution selected by the parents wolffd@0: C = cumsum(T2, 2); % sum across columns wolffd@0: R = rand(nsamples, 1); wolffd@0: y = ones(nsamples, 1); wolffd@0: for i=1:ssz-1 wolffd@0: y = y + (R > C(:,i)); wolffd@0: end wolffd@0: y = y(:)'; wolffd@0: if usecell wolffd@0: y = num2cell(y); wolffd@0: end wolffd@0: wolffd@0: wolffd@0: