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