MATLAB: Element by element subtraction using bsxfun

arraybsxfunmatrix array

Hi everyone,
I have an array, for simplicity let it be:
a = [1 2 3; 4 5 6; 7 8 10];
I would like to perform an element by element subtraction, I have using:
Av = bsxfun(@minus, a(:)', a(:));
However this does not give me the desired result. For the resulting array I want:
Aresult = [0 -1 -2 1 0 -1 2 1 0; -3 -4 -5 -2 -3 -4 -1 -2 -3;-6 -7 -8 -5 -6 -7 -4 -5 -6 ....(continued)]
So to explain the desired result I would like to take an individual element and then subtract the surrounding elements to create a 3×3 sub array in the larger 9×9 array. So in the array above going from left to right
1-0 = 0;
1-2 = -1;
1-3 = -2; (going to the next row down)
1-4 = -3;
1-5 = -4;
1-6 = -5; (going down a row again)
1-7 = -6;
1-8 = -7;
1-9 = -8;
So these results would provide the first 3×3 sub array. This would then be repeated for all elements of the initial array a.
I would be very grateful for any help/ comments you can provide, I hope my explanation wasn't too confusing :).
Thanks, John.

Best Answer

This works for an array whatever its size:
>> A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9
>> cell2mat(arrayfun(@(a)a-A,A,'UniformOutput',false))
ans =
0 -1 -2 1 0 -1 2 1 0
-3 -4 -5 -2 -3 -4 -1 -2 -3
-6 -7 -8 -5 -6 -7 -4 -5 -6
3 2 1 4 3 2 5 4 3
0 -1 -2 1 0 -1 2 1 0
-3 -4 -5 -2 -3 -4 -1 -2 -3
6 5 4 7 6 5 8 7 6
3 2 1 4 3 2 5 4 3
0 -1 -2 1 0 -1 2 1 0