MATLAB: Count groups of elements and distances between them

distancegroup of elements

Dear, Colleagues:
Let's say I have a matrix:
A= [6 6 6 4 4 4 4 4 6 5 5 7 7 7 8 9 8 7 0 0 0 0]
I would like to count number of six and number of zeros (as a group of consequent elements).
And, I would also like to know the distance between groups.
The Matlab output that I would like to get: _____________________________________________________________________________
There are two groups of 6 and one group of 0s.
L= [3 1 4] – length of each group
D= [5 9] – distance between groups
Thank you in advance.

Best Answer

A= [6 6 6 4 4 4 4 4 6 5 5 7 7 7 8 9 8 7 0 0 0 0];
a = A == 6 | A == 0;
a1 = [0 a(:)' 0];
i1 = strfind(a1,[0 1]);
i2 = strfind(a1,[1 0]);
L = i2 - i1;
D = i1(2:end) - i2(1:end-1);
or
A= [6 6 6 4 4 4 4 4 6 5 5 7 7 7 8 9 8 7 0 0 0 0];
a = [A(:) == 6 | A(:) == 0 ; false];
b = [true;diff(a(:))~=0];
bn = find(b);
idx = bn(cumsum(a(b))>0);
LD = diff(idx);
L = LD(1:2:end);
D = LD(2:2:end);