MATLAB: Finding the sum of array

arrayconvolutionsum

What I'm trying to do is to find the sum of the surrounding elements of an binary array
For example
[1 0 0 1;
1 0 1 0;
0 0 1 1;
1 0 0 0]
would return
[1 3 2 1;
1 4 3 3;
2 4 2 2;
0 2 2 2]
but is there a way to do so without using conv2? as I dont really understand what conv2 does

Best Answer

You can padded the array with 0's on all side. Then, run two for-loop to compare A and B.
A = randi([0 1], 100, 100);
B = [1 1 1;1 0 1;1 1 1];
A_prime = zeros(102);
A_prime(2:101,2:101) = A;
Sum = zeros(100);
for i = 2:101
for j = 2:101
Sum(i,j) = sum(sum(A_prime(i-1:i+1,j-1:j+1) == B));
end
end