4

我有一个 6 * 6 矩阵

A=
  3     8     8     8     8     8
  4     6     1     0     7    -1
  9     7     0     2     6    -1
  7     0     0     5     4     4
  4    -1     0     2     8     1
  1    -1     0     8     3     9

我有兴趣从 A(4,4)=5 开始查找邻居的行数和列数。但仅当 A(4,4) 右侧有元素 4,左侧有 6 个,顶部有 2,底部有 8 时,它们才会作为邻居链接到 A(4,4) 对角线左上角 1,对角线右上角有 3 , 7 在左下角对角线和 9 在右下角对角线。更清楚地说,如果邻居围绕 A(4,4),则 A(4,4) 将有邻居,如下所示:

 1     2     3;
 6     5     4;
 7     8     9;

随着每个邻居的找到,这将继续下去。0 和 -1 也将被忽略。最后我想要这些单元格的行号和列号,如下图所示。有没有办法可视化这个网络。这只是样本。我真的有一个巨大的矩阵。

在此处输入图像描述

4

1 回答 1

1
A = [3     8     8     8     8     8;
     4     6     1     0     7    -1;
     9     7     0     2     6    -1;
     7     0     0     5     4     4;
     4    -1     0     2     8     1;
     1    -1     0     8     3     9];

test = [1 2 3; 
        6 5 4; 
        7 8 9];

%//Pad A with zeros on each side so that comparing with test never overruns the boundries    
%//BTW if you have the image processing toolbox you can use the padarray() function to handle this
P = zeros(size(A) + 2);        
P(2:end-1, 2:end-1) = A;

current = zeros(size(A) + 2);
past = zeros(size(A) + 2);

%//Initial state (starting point)
current(5,5) = 1; %//This is A(4,4) but shifted up 1 because of the padding

condition = 1;

while sum(condition(:)) > 0;
      %//get the coordinates of any new values added to current
     [x, y] = find(current - past); 
     %//update past to last iterations current
     past = current; 

     %//loop through all the coordinates returned by find above
     for ii=1:size(x); 

         %//Make coord vectors that represent the current coordinate plus it 8 immediate neighbours.
         %//Note that this is why we padded the side in the beginning, so if we hit a coordinate on an edge, we can still get 8 neighbours for it!
         xcoords = x(ii)-1:x(ii)+1; 
         ycoords = y(ii)-1:y(ii)+1; 

         %//Update current based on comparing the coord and its neighbours against the test matrix, be sure to keep the past found points hence the OR
         current(xcoords, ycoords) = (P(xcoords, ycoords) == test) | current(xcoords, ycoords); 

     end 

     %//The stopping condition is when current == past
     condition = current - past;

 end 

%//Strip off the padded sides
FinalAnswer = current(2:end-1, 2:end-1)
[R, C] = find(FinalAnswer);
coords = [R C] %//This line is unnecessary, it just prints out the results at the end for you.

好的很酷,你已经非常接近了,所以这是循环的最终解决方案。它在大约 0.002 秒内运行,所以我认为它非常快。输出是

FinalAnswer =

     0     0     0     0     0     0
     0     1     1     0     0     0
     0     1     0     1     0     0
     1     0     0     1     1     1
     0     0     0     0     1     0
     0     0     0     0     0     1


coords =

     4     1
     2     2
     3     2
     2     3
     3     4
     4     4
     4     5
     5     5
     4     6
     6     6
于 2013-01-25T12:33:05.563 回答