Search code examples
matlabmatrixadjacency-matrix

Create adjacency matrix from nearest neighbour search. (convert adjacency list to adjacency matrix) - Matlab


I have a matrix 2000x5, in the first column the point number, and in columns 2-5 the 4 neighbours (0s if there isnt a neighbour). Is there an efficient way to create an adjacency matrix out of this ?

1   129 0   65  0
2   130 0   66  85
3   131 169 67  0
4   132 170 68  87
5   133 0   69  81
6   134 0   70  82
7   135 173 71  83
8   136 174 72  84
9   137 161 73  0
10  138 162 74  93
11  139 163 75  0
12  140 164 76  95
13  141 165 77  89
14  142 166 78  90
15  143 167 79  91
16  144 168 80  92
17  145 0   81  65
18  146 0   82  66
....

I found the following thread, where it is explained for just one neighbour, but I am not sure how to use it for multiple neighbours. matlab adjacency list to adjacency matrix

I would very much appreciate any help.


Solution

  • A quick and simple technique:

    adjMat = zeros(size(A,1));
    for ind = 1:size(A,1)
        % Flag 1 on each row 'ind' at the indices mentioned in col 2-5
        adjMat(ind, nonzeros(A(ind,2:end))) = 1;
    end
    

    Since you have mentioned using the nearest neighbour search, it is likely that the adjacency list should be completely filled to result in a undirected graph, in the sense that if row 1 has 20 as a neighbour, row 20 very likely has 1 as a neighbour.

    However technically speaking, this will produce an adjacency matrix exactly equivalent to the adjacency list, assuming nothing by itself.

    Example:

    For an adjacency list

    A = [1 2 3; 2 0 1; 3 1 4; 4 5 3; 5 4 0]
    
    A =
    
     1     2     3
     2     0     1
     3     1     4
     4     5     3
     5     4     0
    

    The result is:

    adjMat =
    
     0     1     1     0     0
     1     0     0     0     0
     1     0     0     1     0
     0     0     1     0     1
     0     0     0     1     0
    

    P.S. To force undirected-ness, you can simply add another statement in the for loop body:

    adjMat(nonzeros(A(ind,2:end)),ind) = 1;
    

    This will ensure that the adjacency matrix will be symmetric, which is a characteristic of undirected graphs.