MATLAB: Calculating the neighbour values

matrix

i have a matrix
A=[1 2 3
4 5 6
7 8 9 ]
please tell how to calculate the neighbour values of centre pixel

Best Answer

A = [ 542 605 341 615 928
471 550 839 1185 315
945 798 809 421 625
982 876 201 723 863
231 932 147 277 1100]; %initial matrix
out1 = cell(numel(A),1);
q = false(size(A));
for ii = 1:numel(A)
w = q;
w(ii) = true;
w1 = imdilate(w,[1 1 1;1 0 1;1 1 1]);
out1{ii} = A(w1);
end
% other variant
B = padarray(A,[1 1],nan);
s = size(B);
addm = bsxfun(@plus,(0:2)',(0:2)*s(1));
ad = addm(:)';
C = reshape(1:prod(s),s);
C = C(1:end-2,1:end-2);
out2 = B(bsxfun(@plus,C(:),ad([1:4,6:9])));
% the centre pixel values is 809 and has index:
i1 = 13;
out1{i1}
ans =
550
798
876
839
201
1185
421
723
>> out2(i1,:)
ans =
550 798 876 839 201 1185 421 723
>>