Search code examples
matlabadjacency-matrix

Find adjacency matrix given a list of class labels


I have a list L of the items that bellong to the same class, L = [1 1 1 0 0 1 1] and I want to construct the adjacency matrix 'A' using the list L and not using any for loop,

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

Clould you please help in that?

Thanks!!


Solution

  • Perhaps this is what you want:

    A = zeros(numel(L));
    A(logical(L),logical(L)) = 1;
    

    The result in your example is

    A =
         1     1     1     0     0     1     1
         1     1     1     0     0     1     1
         1     1     1     0     0     1     1
         0     0     0     0     0     0     0
         0     0     0     0     0     0     0
         1     1     1     0     0     1     1
         1     1     1     0     0     1     1
    

    More generally: suppose that you have L = [1 1 1 0 0 2 2], where each number indicates a different class, and zeros don't count. In this case

    A = bsxfun(@eq,L,L.');
    A(~L,~L) = 0;
    

    which gives

    A =
         1     1     1     0     0     0     0
         1     1     1     0     0     0     0
         1     1     1     0     0     0     0
         0     0     0     0     0     0     0
         0     0     0     0     0     0     0
         0     0     0     0     0     1     1
         0     0     0     0     0     1     1