How to find the sum of elements
조회 수: 3 (최근 30일)
이전 댓글 표시
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
Image Analyst
2015년 1월 16일
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
답변 (1개)
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!