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

Can somebody help me out.Thanks in advance.


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;

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)...

This code is a little more compact. It uses ndgrid to generate all combinations of rows, and ismember to test adjancency between rows. [] (empty matrix) needs to be converted to '' (empty string) so that ismember can be applied. Empty strings are explicitly taken care of so that they don't count for adjacency.

mapr = {'mad'    []       []      []
       'sister'  []       []      []
       'dog'     'inter'  'mad'   'said'}; %// example data

N = size(mapr,1);
mapr = cellfun(@(x) num2str(x), mapr, 'uni', 0); %// convert [] to ''
[ii,jj] = ndgrid(1:N); %// generate all combinations of rows
adjMatr = NaN(N,N); %// pre-shape result matrix
adjMatr(:) = arrayfun( @(n) ...
  any(ismember(mapr(ii(n),:), mapr(jj(n),:)) & ... %// check adjancency
  ~cellfun('isempty', mapr(ii(n),:))), 1:numel(ii) ); %// rule out empty strings 
adjMatr = adjMatr - eye(N); %// remove self-coincidences

Need Your Help

ASP.NET 5 RC1 Deploy To IIS Hangs

c# iis

I installed the RC1 version of ASP.NET 5.0 on a Windows 2012 Server running IIS. After publishing my ASP.NET 5 application to the server, I try to access the default web page and the web browser h...

How to find max values from multiple lists?

python performance list numpy max

I have multiple lists (or numpy arrays) of the same size and I want to return an array of the same size with the max value at each point.