简体   繁体   中英

Adjacency lists of a graph in matlab

I have an adjacency matrix of a bi-partite graph (A,B) as follows.

A= [ 1 0 0; 0 1 0; 1 1 1;0 0 1;0 1 1;1 1 0];

I want to creat an adjacency list for the graph , ie a list like this [1,2,{1,2,3},3,{2,3},{1,2} ]. How can I do this in matlab ?

Also I want to find the nodes whose degree is 1, ie in our case nodes 1,2,4 in set A because they are connected to nodes 1,2,3 of the other set B respectively. After finding the nodes 1,2,4 I want to delete their adjacency lists also.

That's pretty easy. Use the find command to find all of the row and column values that are non-zero, then you can place the nodes each source node is incident to by a simple call to accumarray . Something like this:

A= [ 1 0 0; 0 1 0; 1 1 1;0 0 1;0 1 1;1 1 0];
[R,C] = find(A);
lst = accumarray(R, C, [], @(x) {sort(x)});

Bear in mind that the nodes will be unsorted, so you will need to sort these after you're done. lst is a cell array where each value gives you what nodes are incident to this node, indexed by value.

We get this:

>> format compact;
>> celldisp(lst)
lst{1} =
     1
lst{2} =
     2
lst{3} =
     1
     2
     3
lst{4} =
     3
lst{5} =
     2
     3
lst{6} =
     1
     2

To access a particular node, simply do lst{i} where i is the node you want.

If you want to find all nodes with degrees of 1, simply do:

degrees = cellfun(@numel, lst);

This will go through each list and count up how many nodes are incident to each source node:

>> degrees
degrees =
     1
     1
     3
     1
     2
     2

If you want to delete the adjacency lists for any values with degree 1, simply index into the cell array and find those that don't have degree 1:

lst2 = lst(degrees ~= 1);

We get:

>> celldisp(lst2)
lst2{1} =
     1
     2
     3
lst2{2} =
     2
     3
lst2{3} =
     1
     2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM