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

## Answers

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

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