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);