Search code examples
arraysmatlabcharactercharacter-arrays

How to form adjacency matrix in matlab


I am working on this code to find the adjacency matrix from the following matrix, mapr:

   'mad'     []       []      []

   'sister'  []       []      []

   'dog'     'inter'  'mad'   'said'

For the above matrix, based on the code I have written, this is the output I get which is not the desired one:

       0   1   1
       1   0   1
       1   1   0

The following is my code:

for i=1:no_of_rows
   for j=1:no_of_cols
      for m=i+1:no_of_rows
          for k=1:no_of_cols
             if(~isempty(mapr(i,j)))
               if(strcmp(mapr(i,j),mapr(m,k))==0)
                   Adjmatr(i,m)=1;
                   Adjmatr(m,i)=1;
                end
              end
          end
      end
    end
end

Can somebody help me out.Thanks in advance.


Solution

  • I think the following is what you were looking for:

    mapr={   'mad',      [],    [],     [];
          'sister',      [],    [],     [];
             'dog', 'inter', 'mad', 'said'};
    
    s1 = size(mapr,1);
    s2 = size(mapr,2);
    result = zeros(s1, s1);
    for i = 1 : s1
      for j = 1 : s2 - 1
        if ~isempty(mapr{i,j})
            for k = i+1:s1
                for l = j+1:s2
                     if strcmp(mapr{i,j}, mapr{k,l})
                        result(i,k) = 1;
                        result(k,i) = 1;
                     end
                end
            end
         end
      end
    end
    

    The resulting matrix is

    0 0 1
    0 0 0
    1 0 0
    

    I think the key was to move the ~isempty out by one more loop, and not to test elements against themselves (adjacency matrix diagonal is zero)...