How can I extract all matrix element neighbors ?

4 次查看(过去 30 天)
I want to built a 3x3 block for a given matrix point with that point in the center of the block. This is my code
% code
function frmBlock = fetchNeighbors(frame, row, column)
%Create a 3x3 matrix contains the neighbors of the point(x, y)
%[n, m] = size(frame);
frmBlock = zeros(3, 3);
x = floor(row);
y = floor(column);
frmBlock(1) = frame(x-1, y-1);
frmBlock(2) = frame(x, y-1);
frmBlock(3) = frame(x+1, y+1);
frmBlock(4) = frame(x-1, y);
frmBlock(5) = frame(x, y);
frmBlock(6) = frame(x+1, y);
frmBlock(7) = frame(x-1, y+1);
frmBlock(8) = frame(x, y+1);
frmBlock(9) = frame(x+1, y-1);
end
Whene I run this code I got an error saying:
  • Error using fetchNeighbors (line 12)Index exceeds matrix dimensions.*
Can someone help ?

回答(1 个)

Thorsten
Thorsten 2017-4-20
编辑:Thorsten 2017-4-20
You have to ensure that the indices are always valid, i.e., between 1 and the maximum number of rows / columns. For example, what is the output for row = 1, col = 1? In your implementation, you try to get frame(0, 0) in this case, which does not work.
You can use something like
frame(min(1, x - 1), min(1, y - 1))
frame(max(size(frame, 1), x +1, max(size(frame, 2), y + 1))
and accordingly for all instances where you refer to x/y +/- 1.
Please not that the first index into a matrix is the row that runs from top to bottom. Using variable named 'x' is bit misleading.
  3 个评论
sendja450
sendja450 2017-4-20
编辑:sendja450 2017-4-20
As you can see, I create I 3x3 matrix initialized by 0. What I want to do is to fill that matrix with all the neighbors of the coordinate in input(row, column). If I can't get the neighbors for some reason I do nothing(i.e let that position in the 3x3 block as 0).

请先登录,再进行评论。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by