# How to find separate graphs

2 views (last 30 days)
Na on 4 Jan 2019
Commented: Na on 5 Jan 2019
I have this graph
Ro=[0 0 0 1 0 0;
0 0 1 0 1 0;
0 0 0 0 0 0;
0 0 0 0 0 0;
0 0 0 0 0 0]
[row,col]=find(Ro==1)
G = graph(row,col);
plot(G)
I want to write a code that gives me set of separate graph. result shoud be [1,4],[2,3,5]

#### 1 Comment

GT on 4 Jan 2019
Hi Naime,
There probably is an easier way to do this, however I am on R2018b, and on MAC and this is what I quickly came up with:
Ro=[0 0 0 1 0 0;
0 0 1 0 1 0;
0 0 0 0 0 0;
0 0 0 0 0 0;
0 0 0 0 0 0];
[row,col]=find(Ro==1);
G = graph(row,col);
plot(G)
a = G.conncomp;
myN = 1:size(G.Nodes,1);
for i =1:size(unique(a),2)
myAns{i} = myN(a==i);
end
myAns{:}

GT on 4 Jan 2019
Ro=[0 0 0 1 0 0;
0 0 1 0 1 0;
0 0 0 0 0 0;
0 0 0 0 0 0;
0 0 0 0 0 0];
[row,col]=find(Ro==1);
G = graph(row,col);
plot(G)
a = G.conncomp;
myN = 1:size(G.Nodes,1);
for i =1:size(unique(a),2)
myAns{i} = myN(a==i);
end
myAns{:}

Steven Lord on 4 Jan 2019
Instead of post-processing the output of a call to conncomp, just ask it to return the output as a cell array directly.
A = conncomp(G, 'OutputForm', 'cell')
The contents of the first cell in A is [1 4], while the second is [2 3 5].
GT on 4 Jan 2019
Nice:) I did not know it was possible:)
Na on 5 Jan 2019
Thanks