Counting the number of elements surrounding another element.

10 ビュー (過去 30 日間)
Phillip Smith
Phillip Smith 2019 年 11 月 25 日
編集済み: Andrei Bobrov 2019 年 11 月 27 日
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
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.
Phillip Smith
Phillip Smith 2019 年 11 月 25 日
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!

サインインしてコメントする。

採用された回答

Turlough Hughes
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 件のコメント
Phillip Smith
Phillip Smith 2019 年 11 月 27 日
This helped and made me understand my greater goal. Thank you!

サインインしてコメントする。

その他の回答 (1 件)

Andrei Bobrov
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');
  2 件のコメント
Phillip Smith
Phillip Smith 2019 年 11 月 25 日
could you explain to me what the 2nd line of your code is doing please?
Andrei Bobrov
Andrei Bobrov 2019 年 11 月 25 日
Please read about conv2.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by