Filter löschen
Filter löschen

How can I extract all matrix element neighbors ?

1 Ansicht (letzte 30 Tage)
sendja450 am 20 Apr. 2017
Kommentiert: sendja450 am 20 Apr. 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);
Whene I run this code I got an error saying:
  • Error using fetchNeighbors (line 12)Index exceeds matrix dimensions.*
Can someone help ?

Antworten (1)

Thorsten am 20 Apr. 2017
Bearbeitet: Thorsten am 20 Apr. 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 Kommentare
sendja450 am 20 Apr. 2017
Bearbeitet: sendja450 am 20 Apr. 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 am 20 Apr. 2017
Thanks for your answer @Thorsten, I got an answer in stackoverflow and this is the link to it.

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by