How to find the sum of elements

1 次查看(过去 30 天)
Vaultec
Vaultec 2015-1-15
编辑: Vaultec 2015-1-16
What Im 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

回答(1 个)

Geoff Hayes
Geoff Hayes 2015-1-16
Jimmy - you could code up an equivalent to conv2 (and that would be a good exercise!) but how you are using this function in this case is very simple. You have a matrix A (let's use your 4x4 example from above) and you have a matrix B defined as
B=[1 1 1;
1 0 1;
1 1 1]
When you use conv2, it is basically going to slide the matrix B across each element of A, where the zero of B is centred on the element of A. We can then sum those elements around this centre by lining up the ones of B with elements of A.
So in your example, if we consider A(1,1), then there are only three possible elements neighbouring this centre given B - those at B(2,3), B(3,2) and B(3,3) (as all other elements of B fall outside of A) which means we sum 0 + 1 + 0 = 1.
For A(1,2), we would have five neighbouring elements at B(2,1), B(2,3), B(3,1), B(3,2), and B(3,3) which would sum the elements 1 + 1 + 0 + 1 + 0 = 3.
And so on. We continue to slide B over each element of A summing all of the neighbours according to B.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by