Matlab: Find the distance from the element to the border of the matrix.

Say in Matlab I have a matrix like this:

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9

Now I need to find 3x3 submatrices around each element (therefore, each element, in turn, is the center of the 3x3 submatrix). When in the middle, no problem finding fx

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9

which is a submatrix:

2 3 4
2 3 4
2 3 4

But if at the border of the matrix these are elements in the first or last row or column, then, of course, it is impossible to find the 3x3 submatrix. Instead, I need a submatrix that fits. In the fx corner, I would get

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9

:

1 2
1 2

, fx:

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9

:

4 5 6
4 5 6

:

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9

:

6 7 8
6 7 8

, . - , .

, , ( , fx - 5x5), .

?

+5
3

: nxm, i, j. i, j ? : min (i, j, n-i, m-j)

+2

, , - - 3x3. , , NaN. 3x3, NaNs.

padarray.

Edit (1): . , , . , , ?

mask = false(size(A));
mask(1:2,:) = true;
mask(end-1:end,:) = true;
mask(:,1:2) = true;
mask(:,end-1:end) = true;
+4
% Define the example data:

Matrix = repmat(1:9, 9, 1)

: : ( )

% Define the size of submatrix (square matrix assumed here).

SubmatrixSize = 5;

% Check that the size of submatrix is an odd number.

if (mod(SubmatrixSize, 2) == 0)
    error('SubmatrixSize must be odd number.');
end

Distance = floor(SubmatrixSize/2);

VertSize = size(Matrix, 1);
HorzSize = size(Matrix, 2);

for rowIndex = 1:VertSize
    yIndices = (rowIndex-Distance:rowIndex+Distance);
    yIndices = yIndices(find(yIndices >= 1 & yIndices <= VertSize));
    for colIndex = 1:HorzSize
        xIndices = (colIndex-Distance:colIndex+Distance);
        xIndices = xIndices(find(xIndices >= 1 & xIndices <= HorzSize));
        SubmatricesCellArray{rowIndex, colIndex} = Matrix(yIndices, xIndices);
    end
end

3x3:

% This code only works for 3x3 submatrices.

VertSize = size(Matrix, 1);
HorzSize = size(Matrix, 2);

for rowIndex = 1:VertSize
    yIndices = nonzeros(rowIndex-1:rowIndex+1);
    if yIndices(end) > VertSize
        yIndices(end) = [];
    end
    for colIndex = 1:HorzSize
        xIndices = nonzeros(colIndex-1:colIndex+1);
        if xIndices(end) > HorzSize
            xIndices(end) = [];
        end
        SubmatricesCellArray{rowIndex, colIndex} = Matrix(yIndices, xIndices);
    end
end

SubmatricesCellArray{y, x}.

+2

All Articles