简体   繁体   English

如何在Matlab中形成邻接矩阵

[英]How to form adjacency matrix in matlab

I am working on this code to find the adjacency matrix from the following matrix, mapr: 我正在研究此代码,以从以下矩阵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. 有人可以帮我吗,谢谢。

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)... 我认为关键是~isempty移出一个循环,而不是针对自身测试元素(邻接矩阵对角线为零)...

This code is a little more compact. 这段代码更加紧凑。 It uses ndgrid to generate all combinations of rows, and ismember to test adjancency between rows. 它使用ndgrid生成行的所有组合,并使用ismember测试行之间的邻接关系。 [] (empty matrix) needs to be converted to '' (empty string) so that ismember can be applied. 需要将[] (空矩阵)转换为'' (空字符串), ismember可以应用ismember 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM