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