annotate toolboxes/FullBNT-1.0.7/graph/mk_adj_mat.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 [A, names] = mk_adj_mat(connections, names, topological)
wolffd@0 2 % MK_ADJ_MAT Make a directed adjacency matrix from a list of connections between named nodes.
wolffd@0 3 %
wolffd@0 4 % A = mk_adj_mat(connections, name)
wolffd@0 5 % This is best explaine by an example:
wolffd@0 6 % names = {'WetGrass', 'Sprinkler', 'Cloudy', 'Rain'};
wolffd@0 7 % connections = {'Cloudy', 'Sprinkler'; 'Cloudy', 'Rain'; 'Sprinkler', 'WetGrass'; 'Rain', 'WetGrass'};
wolffd@0 8 % adds the arcs C -> S, C -> R, S -> W, R -> W. Node 1 is W, 2 is S, 3 is C, 4 is R.
wolffd@0 9 %
wolffd@0 10 % [A, names] = mk_adj_mat(connections, name, 1)
wolffd@0 11 % The last argument of 1 indicates that we should topologically sort the nodes (parents before children).
wolffd@0 12 % In the example, the numbering becomes: node 1 is C, 2 is R, 3 is S, 4 is W
wolffd@0 13 % and the return value of names gets permuted to {'Cloudy', 'Rain', 'Sprinkler', 'WetGrass'}.
wolffd@0 14 % Note that topological sorting the graph is only possible if it has no directed cycles.
wolffd@0 15
wolffd@0 16 if nargin < 3, topological = 0; end
wolffd@0 17
wolffd@0 18 n=length(names);
wolffd@0 19 A=zeros(n);
wolffd@0 20 [nr nc] = size(connections);
wolffd@0 21 for r=1:nr
wolffd@0 22 from = strmatch(connections{r,1}, names, 'exact');
wolffd@0 23 assert(~isempty(from));
wolffd@0 24 to = strmatch(connections{r,2}, names, 'exact');
wolffd@0 25 assert(~isempty(to));
wolffd@0 26 %fprintf(1, 'from %s %d to %s %d\n', connections{r,1}, from, connections{r,2}, to);
wolffd@0 27 A(from,to) = 1;
wolffd@0 28 end
wolffd@0 29
wolffd@0 30 if topological
wolffd@0 31 order = topological_sort(A);
wolffd@0 32 A = A(order, order);
wolffd@0 33 names = names(order);
wolffd@0 34 end
wolffd@0 35
wolffd@0 36