If I select an element in a matrix, say MAT(2,2), how to find how many elements of the same value of MAT(2,2) in the matrix are "connected" to it.

3 views (last 30 days)
For example, Mat=[1 2 3 4 2;2 2 2 2 0;2 0 4 2 1;1 3 4 2 8] and there're 7 elements (namely MAT(1,2), MAT(2,1), MAT(2,3), MAT(2,4), MAT(3,1), MAT(3,4), MAT(4,4)). I found that the function "bwareaopen" can be used to remove connected pixels whose size is smaller than the given threshold; I thought it must have used a similar trick, but I failed to figure it out.

Answers (2)

Massimo Zanetti
Massimo Zanetti on 25 Oct 2016
Edited: Massimo Zanetti on 25 Oct 2016
You need bwconncomp
For example:
Mat=[1 2 3 4 2;2 2 2 2 0;2 0 4 2 1;1 3 4 2 8]
%checks for the elements of Mat that equals Mat(2,2)
CC = bwconncomp(Mat==Mat(2,2));
connComponents = labelmatrix(CC)
since Mat(2,2)=2 you get
Mat =
1 2 3 4 2
2 2 2 2 0
2 0 4 2 1
1 3 4 2 8
connComponents =
0 1 0 0 1
1 1 1 1 0
1 0 0 1 0
0 0 0 1 0

Andrei Bobrov
Andrei Bobrov on 25 Oct 2016
[~,out] = bwlabel(Mat(2,2)==Mat)

Community Treasure Hunt

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

Start Hunting!