How to find the sum of elements
3 views (last 30 days)
Show older comments
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 Comment
Image Analyst
on 16 Jan 2015
Earlier version (duplicate) superceded by this later version: http://www.mathworks.com/matlabcentral/answers/170076-finding-the-sum-of-surroudning-elemnts-for-binary-array#answer_164980
Answers (1)
Geoff Hayes
on 16 Jan 2015
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.
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!