Effacer les filtres
Effacer les filtres

How to find the sum of elements

1 vue (au cours des 30 derniers jours)
Vaultec
Vaultec le 15 Jan 2015
Modifié(e) : Vaultec le 16 Jan 2015
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

Réponses (1)

Geoff Hayes
Geoff Hayes le 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.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by