I lately had to implement a number of function that I had to apply to 2D matrices, for example a sliding window averager.
With each of these things I had to take into account that the operation I was doing was not the same if the element I was treating was in the corner or on the edge of the matrix. To continue my example I can't take the average of the surrounding values of the element in (0,0) because it would get me outside of the matrix.
Each time I face this my approach is different : I use imbricated ifs or do loops that doesn't start in the edges then treat them separately but I'm under the impression I'm not doing it the "best way".
I tried to search if there was a widely adopted approach for this problem but couldn't find that's why I'm asking for some input here.
I'm mainly using C, C++, matlab and python so if you have elegant ways of doing that in these languages I'm also interested!
Thank you.
For the cost of a bit of extra memory, you can "surround" the matrix with zeros (or ones, or whatever is appropriate for your algorithm) like this:
and run the loops like:
Where
N-1andM-1were your original matrix dimensions.