Search for a neighborhood in a specific place

I have a 2D matrix, and I want to find the neighborhood (i, j) in this matrix with sizes M and N in the x and y directions, respectively. I know this is easy to do, but my problem is that when (i, j) is close to the corners and M and N are big! In this case, I do not want to exceed the matrix. Is there any function or simple solution to this problem in MATLAB?

+1
source share
1 answer

If I understood correctly, you would like to extract the submatrix from the matrix, and the submatrix is ​​concentrated from row i-Mto i+Mand column j-Nto j+N.

If so, and you would like to avoid selecting invalid indexes, you can slice the selection using the min / max functions, for example:

matrix = randi(10,20,15);
siz = size(matrix);

i=2;
j=5;
M=10;
N=3;

selectrows = max(1,i-M):min(siz(1),i+M);
selectcols = max(1,j-N):min(siz(2),j+N);
result = matrix(selectrows, selectcols);
+5

All Articles