How can I extract all matrix element neighbors ?

조회 수: 3 (최근 30일)
sendja450
sendja450 2017년 4월 20일
댓글: sendja450 2017년 4월 20일
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).
sendja450
sendja450 2017년 4월 20일
Thanks for your answer @Thorsten, I got an answer in stackoverflow and this is the link to it. http://stackoverflow.com/questions/43523685/given-a-pixel-coordinates-how-can-i-extract-all-his-neighbors

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Image Filtering and Enhancement에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by