Matlab: Find the distance from an element to the matrix border
matlab, matrix, submatrix
Solution
Let's specify the question a bit further: You have a matrix of the size nxm and you pick an element i,j. You want to know the distance of element i,j from the border? That would be: min(i,j,n-i,m-j)
Problem
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 ``` I now need to find submatrixes 3x3 around every element (so each element in turn is the center of a 3x3 submatrix). When in the middle, it is no problem to find 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 the submatrix: ``` 2 3 4 2 3 4 2 3 4 ``` But when in the border of the matrix, that is elements in the first og last row or column, it of course isn't possible to find a 3x3 submatrix. Instead I need the submatrix that fits. In the corner fx 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 where the submatrix is: ``` 1 2 1 2 ``` and in the middle of the border, I get 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 gives: ``` 4 5 6 4 5 6 ``` or as another example: 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 gives: ``` 6 7 8 6 7 8 ``` I hope you understand my point. I am missing some feature that lets me find the distance from an element to the border. I can treat every element as a center of a submatrix, and if I can just test, if the distance from the element to the border is below the submatrix's border (the submatrix dimension will namely change, to fx a 5x5 submatrix), then I can truncate a part of the submatrix while it is being made. How do I find the distance from an element to the border of the matrix in the most efficient way?