How can I extract all matrix element neighbors ?
10 views (last 30 days)
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
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 ?
Thorsten on 20 Apr 2017
Edited: Thorsten on 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.