matlab - Count identical elements near each other in matrix -
consider matrix like
a = 0 1 0 1 1 1 0 0 0 0 0 0 1 1 1 1
i calculate average size of each cluster of 1's. define cluster occurring when 2 or more 1's near each other, i.e. next or above/below. eg, in matrix there cluster of size 3 in top left hand corner , cluster of size 4 in bottom row.
i need way extract information in non-visual way because need many times different a.
you may want use bwlabel
isolates connected components (clusters of 1) in binary matrix.
a = [0 1 0 1 1 1 0 0 0 0 0 0 1 1 1 1 ]; [l,n] = bwlabel(a,8) % # 8-pixel stencil % # (i.e. hor/vert/diag first neighbors)
or
[l,n] = bwlabel(a,4) % # 4-pixel stencil % # (just horizontal & vertical neighbors) l = 0 1 0 3 1 1 0 0 0 0 0 0 2 2 2 2
doing so, obtain matrix l
labels n
different connected components.
then may want extract statistics; instance may want histogram size of clusters.
cluster_size = hist(l(:),0:n); cluster_size = cluster_size(2:end); % # histogram of component vs. size % # (without zeros) hist(cluster_size) % # histogram of sizes
which tells thay have 1 cluser of 1 element, 1 cluster of 3 , 1 cluster of four.
finally, if looking average size of clusters, can do
mean(cluster_size) 2.6667
Comments
Post a Comment