Daniel@0: function [A, names] = mk_adj_mat(connections, names, topological) Daniel@0: % MK_ADJ_MAT Make a directed adjacency matrix from a list of connections between named nodes. Daniel@0: % Daniel@0: % A = mk_adj_mat(connections, name) Daniel@0: % This is best explaine by an example: Daniel@0: % names = {'WetGrass', 'Sprinkler', 'Cloudy', 'Rain'}; Daniel@0: % connections = {'Cloudy', 'Sprinkler'; 'Cloudy', 'Rain'; 'Sprinkler', 'WetGrass'; 'Rain', 'WetGrass'}; Daniel@0: % adds the arcs C -> S, C -> R, S -> W, R -> W. Node 1 is W, 2 is S, 3 is C, 4 is R. Daniel@0: % Daniel@0: % [A, names] = mk_adj_mat(connections, name, 1) Daniel@0: % The last argument of 1 indicates that we should topologically sort the nodes (parents before children). Daniel@0: % In the example, the numbering becomes: node 1 is C, 2 is R, 3 is S, 4 is W Daniel@0: % and the return value of names gets permuted to {'Cloudy', 'Rain', 'Sprinkler', 'WetGrass'}. Daniel@0: % Note that topological sorting the graph is only possible if it has no directed cycles. Daniel@0: Daniel@0: if nargin < 3, topological = 0; end Daniel@0: Daniel@0: n=length(names); Daniel@0: A=zeros(n); Daniel@0: [nr nc] = size(connections); Daniel@0: for r=1:nr Daniel@0: from = strmatch(connections{r,1}, names, 'exact'); Daniel@0: assert(~isempty(from)); Daniel@0: to = strmatch(connections{r,2}, names, 'exact'); Daniel@0: assert(~isempty(to)); Daniel@0: %fprintf(1, 'from %s %d to %s %d\n', connections{r,1}, from, connections{r,2}, to); Daniel@0: A(from,to) = 1; Daniel@0: end Daniel@0: Daniel@0: if topological Daniel@0: order = topological_sort(A); Daniel@0: A = A(order, order); Daniel@0: names = names(order); Daniel@0: end Daniel@0: Daniel@0: