wolffd@0: function sample = sample_bnet(bnet, varargin) wolffd@0: % SAMPLE_BNET Generate a random sample from a Bayes net. wolffd@0: % SAMPLE = SAMPLE_BNET(BNET, ...) wolffd@0: % wolffd@0: % sample{i} contains the value of the i'th node. wolffd@0: % i.e., the result is an Nx1 cell array. wolffd@0: % Nodes are sampled in the order given by bnet.order. wolffd@0: % wolffd@0: % Optional arguments: wolffd@0: % wolffd@0: % evidence - initial evidence; if evidence{i} is non-empty, node i won't be sampled. wolffd@0: wolffd@0: % set defauly params wolffd@0: n = length(bnet.dag); wolffd@0: sample = cell(n,1); wolffd@0: wolffd@0: % get optional params wolffd@0: args = varargin; wolffd@0: nargs = length(args); wolffd@0: for i=1:2:nargs wolffd@0: switch args{i}, wolffd@0: case 'evidence', sample = args{i+1}(:); wolffd@0: otherwise, error(['unrecognized argument ' args{i}]) wolffd@0: end wolffd@0: end wolffd@0: wolffd@0: for j=bnet.order(:)' wolffd@0: if isempty(sample{j}) wolffd@0: %ps = parents(bnet.dag, j); wolffd@0: ps = bnet.parents{j}; wolffd@0: e = bnet.equiv_class(j); wolffd@0: sample{j} = sample_node(bnet.CPD{e}, sample(ps)); wolffd@0: end wolffd@0: end