forked from najjajm/myosort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
findpaths.m
117 lines (93 loc) · 2.73 KB
/
findpaths.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
%% FINDPATHS find paths
% Identifies all sets of connected nodes in an undirected graph.
%
% SYNTAX
% [grp,solo] = findpaths(A)
%
% REQUIRED INPUTS
% A (square array) - adjacency matrix for an undirected graph. Where
% a_{ij} is true or 1 indicates a connection between nodes i and j.
%
% OPTIONAL INPUTS: none
%
% VARIABLE INPUTS: none
%
% OUTPUTS
% grp (cell array) - list of connected nodes
% solo (cell array) - list of unconnected nodes
%
% EXAMPLE
%
% % generate a list of connected nodes
% nNodes = 10;
% x = nchoosek(1:nNodes,2);
% y = rand(size(x,1),1);
% y(y>.9)=1;
% y(y~=1)=0;
%
% % make adjacency matrix
% A = false(nNodes);
% A(sub2ind(size(A), x(y==1,1), x(y==1,2))) = true;
%
% % find connected nodes
% grp = findpaths(A);
%
% IMPLEMENTATION
% Other m-files required: none
% Subfunctions: none
% MAT-files required: none
%
% SEE ALSO:
% Authors: Najja Marshall
% Emails: [email protected]
% Dated: August 2017
function [grp,solo] = findpaths(A, varargin)
%% Parse inputs
% initialize input parser
P = inputParser;
P.FunctionName = 'FINDPATHS';
% add required, optional, and parameter-value pair arguments
addRequired(P, 'A', @(x) size(x,1)==size(x,2));
% clear workspace (parser object retains the data while staying small)
parse(P, A, varargin{:});
clear ans varargin
%% Main loop
grp = {[]};
rowNo = 1;
while nnz(A) > 0
% find connections from node in current row
edges = find(A(rowNo,:));
if ~isempty(edges)
% add unique nodes to path list
grp{end} = [rowNo, edges(~ismember(edges,grp{end}))];
% remove connections from adjacency matrix
A(rowNo,edges) = 0;
% check connections to and from each node in the path
nodeIdx = 2;
while nodeIdx <= length(grp{end})
% current node
node = grp{end}(nodeIdx);
% add connections from current node
edges = find(A(node,:));
grp{end} = [grp{end}, setdiff(edges,grp{end})];
% remove from adjacency matrix
A(node,edges) = 0;
% add connections to current node
edges = find(A(:,node));
grp{end} = [grp{end}, setdiff(edges',grp{end})];
% remove from adjacency matrix
A(edges,node) = 0;
nodeIdx = nodeIdx+1;
end
% add cell to path list if any edges remain
if nnz(A) > 0
grp = [grp; {[]}];
end
end
% increment row to check in adjacency matrix
rowNo = rowNo+1;
end
% sort list of nodes
grp = cellfun(@sort,grp,'uni',false);
% unsorted
solo = num2cell(setdiff(1:size(A,1),cell2mat(grp')))';