get edge between two node set

8 views (last 30 days)
Hamid Salari
Hamid Salari on 10 Aug 2017
Commented: Hamid Salari on 10 Aug 2017
hi . i have a undirected graph with n nodes and two sets of node . A = [1 2 3 4] , B = [5 6 7 8] . there is no common member in this two set . how should i get number of edges between this two set ? something like :
findedge(G,[1 2 3 4],[5 6 7 8]) ;
p.s: the find edge gives me some unreal answer : it says [3;382;1839] that cant be true ! 4*4 nodes at last can have 16 edges between . and i tested and those numbers is not the edges index of existed edges between two set .

Accepted Answer

Alex Karle
Alex Karle on 10 Aug 2017
Hi Hamid,
I wrote some code that should solve this problem for you. The details of the code are commented:
% Let us take this graph as our example
s = [1 1 1 1 2 1 2 2 3 3 4 5 5 6 7];
t = [2 4 8 3 4 6 3 7 4 6 5 6 8 7 8];
G = graph(s,t);
plot(G)
% Let us say A = [1,2,3,4], B = [5,6,7,8]
A = [1,2,3,4];
B = [5,6,7,8];
% One way to do this is the following:
% Assuming this is an unweighted graph, then the adjacency matrix will have a '1'
% in row 'i' col 'j' if there is an edge 'i' <-> 'j', else there will be a '0'
adj_matrix = adjacency(G)
% Note that this is a sparse matrix, so it may not look like a normal matrix, but we can still use
% matrix indexing on it!
% adj_matrix(A,B) is equal to adj_matrix([1,2,3,4],[5,6,7,8]), creates a new matrix where the only
% elements are those that start in A and end in B. Thus, to find the number of edges between A and B
% we simply need to find the sum of all the '1's in this subsection of the adj_matrix, which can be
% done with a sum(sum(adj_matrix(A,B))
count = sum(sum(adj_matrix(A,B)))
If you want more information about the functions used, I would recommend looking at the MATLAB documentation:
The reason why "findedge(G,[1 2 3 4],[5 6 7 8])" does not return the desired result is because findedge looks for pairs of edges, like the following:
findedge(G,[1,2],[3,4],[5,6])
This will look for edges between 1 and 2, 3 and 4, and 5 and 6 as three seperate queries about the edges of the graph. For more documentation on the usage of findedge, look here: findedge.
Hope this helps!

More Answers (0)

Categories

Find more on Graph and Network Algorithms in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!