How can I count the number of values that are contiguous in an matrix? For example, if
A= [ 1 0 1 0 0 0 0 \ 1 1 1 0 0 0 1\ 1 1 0 1 1 1 1]
is a 7 by 3 matrix then the result should indicate that there are 12 contiguous values that are "1" (highlighted in bold), that there are 8 contiguous 0 values (highlighted in italics) and one lone 0 value. Code in IDL is preferred but MATLAB would also be helpful.
This is what you can do in MATLAB using the bwconncomp
function. This is a function in the Image Processing Toolbox. I don't know a whole lot about IDL, it might have a similar function.
bwconncomp
returns a struct with some information, one of the fields is PixelIdxList
, which is a cell array with one element per connected component. Each of these elements is a vector with the indices to one of the array elements in the connected component. For the case of the 1
elements in your example, this cell array will have one vector with 12 values. For the case of the 0
elements, it will have two vectors, one with 1 value and one with 8:
>> A = [ 1 0 1 0 0 0 0 ; 1 1 1 0 0 0 1 ; 1 1 0 1 1 1 1 ];
>> CC = bwconncomp(A==1, 8);
>> cellfun(@numel, CC.PixelIdxList)
ans =
12
>> CC = bwconncomp(A==0, 8);
>> cellfun(@numel, CC.PixelIdxList)
ans =
1 8
The bwconncomp
takes 4
or 8
as the second argument. This specifies what are considered connected elements (contiguous values, neighbors). 4 means only the 4 elements N,S,E,W are connected; 8 means also diagonal connections exist (8 neighbors).