How to Calculate the Local Gradient of an Image in MATLAB
Ok,
First of all, pay attention it is a calculation per pixel using a sata from a blog.
Basically summing the Gradient norm over a block / windows.

To calculate what you submitted above do the following:

1.Define the Finite Differences filters to approximate the gradient. Moreover build the "Win Summation" kernel which sums all elements within a window.

mLocalSumFilter = ones(filterWinSize, filterWinSize);
vGradXFilter = [-0.5, 0, 0.5];
vGradYFilter = [-0.5; 0; 0.5];


2.Calculate the image gradients:

mInputImageGradX = imfilter(mInputImage, vGradXFilter, 'replicate', 'same', 'corr');
mInputImageGradY = imfilter(mInputImage, vGradYFilter, 'replicate', 'same', 'corr');


3.Calculate the norm of the gradient vector. Afterwards sum the norm of the gradient within the window.

mInputImageGradNorm = sqrt((mInputImageGradX .^ 2) + (mInputImageGradY .^ 2));
mInputImageGradNorm = imfilter(mInputImageGradNorm, mLocalSumFilter, 0, 'same', 'corr') ;


This is it.
Enjoy.