我有一个 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 在底部,1 在左上对角线,3 在对角线右上角时,它们才会作为邻居链接到 A(4,4) , 7 在左下角对角线和 9 在右下角对角线。更清楚的是,如果邻居围绕 A(4,4),则 A(4,4) 将有邻居,如下所示:
1 2 3;
6 5 4;
7 8 9;
这将在找到每个邻居时继续进行。 0 和 -1 也将被忽略。最后,我希望这些单元格的行号和列号如下图所示。有什么方法可以可视化这个网络吗?这只是 sample 。我真的有一个巨大的矩阵。
最佳答案
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
关于algorithm - 在Matlab中有条件地查找八个邻居的行号和列号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14514927/