# Counting the number of elements surrounding another element.

4 views (last 30 days)
Phillip Smith on 25 Nov 2019
Edited: Andrei Bobrov on 27 Nov 2019
Hello,
I've created a matrix and have I randomly set one of these matrix elements equal to 1. Now I want to count how many elements are neighbouring it, I am taking into account diagonal neighbours too i.e. a fully surrounded element will have 8 neighbours etc.
Many thanks,
Phill
##### 2 CommentsShow 1 older commentHide 1 older comment
Phillip Smith on 25 Nov 2019
That works but I want to count the number of 0's around the element (since it's a matrix consisting of only 1's and 0's) and then change one of those 0's into a 1!

Sign in to comment.

### Accepted Answer

Turlough Hughes on 25 Nov 2019
If your matrix is called A. You could find the number of 0's surrounding an element at A(m,n) as follows:
D=padarray(A,[1 1],1,'both');
numberzeros=nnz(~D(m:m+2,n:n+2));
##### 1 CommentShow NoneHide None
Phillip Smith on 27 Nov 2019
This helped and made me understand my greater goal. Thank you!

Sign in to comment.

### More Answers (1)

Andrei Bobrov on 25 Nov 2019
Edited: Andrei Bobrov on 27 Nov 2019
Let x - your array with ones and zeros:
x = double(rand(10) > .45);
out = conv2(double(~x),[1,1,1;1,0,1;1,1,1],'same');
##### 2 CommentsShow 1 older commentHide 1 older comment
Andrei Bobrov on 25 Nov 2019
Please read about conv2.

Sign in to comment.

### Categories

Find more on Matrices and Arrays 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!

Translated by