MATLAB: Finding Maximum Difference Between Element and All Neighboring Elements in An Arary

Image Processing Toolboxmaximum differenceneighboring elements

Hello, I have an array and I am trying to find the maximum difference between an element and all of its neighboring elements for each element. For example if I have… array = [1 2 3; 4 10 5; 6 7 8 ]; I want to find the maximum difference between each element and any neighboring element to get an output with the maximum difference
output = [3 8 7; 6 9 5; 4 3 3]; Any help would be greatly appreciated!

Best Answer

If all you want are horizontal and vertical comparisons, then this too easy. Essentially two calls to diff, then a few max calls.
A = [1 2 3; 4 10 5; 6 7 8 ];
[n,m] = size(A);
D1 = abs(diff(A,[],1));
D2 = abs(diff(A,[],2));
D = max(max([zeros(1,m);D1],[D1;zeros(1,m)]),max([zeros(n,1),D2],[D2,zeros(n,1)]));
That yields D as
D
D =
3 8 2
6 8 5
2 3 3
So it looks vaguely like you want to consider diagonal neighbors also. This too would be doable, using a similar scheme. (It can also be done using conv2, as a nice trick.) But then the result that you show is incorrect.
The (1,1) element of A is 1. It has three neighbors, thus {2,4,10}. So the max difference would then be 9, NOT 3.
So unless you can CLEARLY define what you are looking for, giving a correct example, I cannot help you more.