Counting the number of elements surrounding another element.
13 次查看(过去 30 天)
显示 更早的评论
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 个评论
Adam
2019-11-25
Just determine if it is on an edge (5 neighbours) or a corner (3 neighbours) and if not then as you say, it has 8 neighbours. No need to count them.
采纳的回答
Turlough Hughes
2019-11-25
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 个)
Andrei Bobrov
2019-11-25
编辑:Andrei Bobrov
2019-11-27
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');
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Statistics and Machine Learning Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!