Graph how to get every connected nodes from this specific graph
Show older comments
Hi, I have graph that is described in this way
U = {[1 3],[1 4],[1 5],[5 2]};
and it looks like this

How can i get two arrays, s array would show first node and t array would show accordingly the next node connected to it.
Example below.
s[1 1 1 2 3 4 5 5]
t[3 4 5 5 1 1 1 2]
Thanks in advance.
Accepted Answer
More Answers (2)
Guillaume
on 3 Dec 2018
Well, that's a bit silly. Your desired output is more or less the same as your input, just with duplicated information.
U = {[1 3],[1 4],[1 5],[5 2]}; %why is it in a cell array?
edgetable = vertcat(U{:}); %make a matrix out ot it
s = [edgetable(:, 1); edgetable(:, 2)]'
t = [edgetable(:, 2); edgetable(:, 1)]'
Note that since R2015b, matlab has functions dedicated to graphs. For example to visualise the above graph:
g = graph(edgetable(:, 1), edgetable(:, 2));
plot(g)
2 Comments
Tomas Maybacas
on 3 Dec 2018
Guillaume
on 3 Dec 2018
Well, I don't know what you've done. You certainly didn't just copy paste the code I wrote:
>> U = {[1 3],[1 4],[1 5],[5 2]}; %why is it in a cell array?
edgetable = vertcat(U{:}); %make a matrix out ot it
s = [edgetable(:, 1); edgetable(:, 2)]'
t = [edgetable(:, 2); edgetable(:, 1)]'
s =
1 1 1 5 3 4 5 2
t =
3 4 5 2 1 1 1 5
Steven Lord
on 3 Dec 2018
The s and t vectors in the original question double-count each edge. Since what your picture shows is an undirected graph (created by the MATLAB function graph), the edge (1, 3) is the same as the edge (3, 1). If you need those two edges to be different, use a directed graph (the digraph function.) See this documentation page for an illustration of the difference. There is an edge from A to B in both the graph and digraph shown in the first two pictures on that page, but there is an edge from B to A only in the undirected graph.
If you want a list of edges, you can either get the Edges table from the graph object or you can use findedge.
U = [[1 3];[1 4];[1 5];[5 2]];
G = graph(U(:, 1), U(:, 2));
plot(G)
E = G.Edges
[S, T] = findedge(G)
But I'm guessing you're not getting the edges just to get the edges. If you tell us what analysis or manipulation you want to perform on this graph we may be able to tell you what functions available for working on graphs may be of use to you.
Categories
Find more on Graph and Network Algorithms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
