MATLAB: How to blur an image by averaging the pixels with their neighboring eight pixels

blurringdigital image processingImage Processing Toolbox

I have a picture imported and for each plane, and each row between 2 and r-1 and each column between 2 and c-1, I need to replace each pixel by the average of itself and its eight neighbors.
This is the code I know it starts with.
[r,c,p] = size(Y);
for k = 1:p
for i = 2:r-1
for j = 2:c-1
The result should be a blurred copy of the original image.

Best Answer

The code can be done as
result = zeros(size(Y), class(Y));
for k = 1 : size(Y, 3)
result(:,:,k) = conv2(Y(:,:,k), ones(3,3)/9, 'same');
end