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が下に8が左上に斜めに、3が右上に斜めにある場合にのみ、隣接としてA(4,4)にリンクされます。 、左下の対角線上に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 に答える