How can I extract all matrix element neighbors ?

4 visualizaciones (últimos 30 días)
sendja450
sendja450 el 20 de Abr. de 2017
Comentada: sendja450 el 20 de Abr. de 2017
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 ?

Respuestas (1)

Thorsten
Thorsten el 20 de Abr. de 2017
Editada: Thorsten el 20 de Abr. de 2017
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 comentarios
sendja450
sendja450 el 20 de Abr. de 2017
Editada: sendja450 el 20 de Abr. de 2017
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 el 20 de Abr. de 2017
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

Iniciar sesión para comentar.

Community Treasure Hunt

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

Start Hunting!

Translated by