Reputation: 65
How to sum only consecutive duplicate numbers in order to find a unique value? for example, I have a vector
A = [0 0 0 0 1 0 0 0 1 0 1 1 0 0 1 0 1]
then when summing only consecutive duplicate numbers, I will have
B = [0 1 0 1 0 2 0 1 0 1]
finally the number of unique values different from 0
and 1
:
sum(B>1)
I know one way to solve the problem:
sum(diff(find(A==1))==1)
but it seems it is not a good method.
Upvotes: 0
Views: 244
Reputation: 67537
This will give you the total number of repeated values in the array including "0" values.
sum(A(1:end-1)-A(2:end)==0)
ans =
7
If you are interested only in the repeated "1" values, you can change it to
sum(A(1:end-1)+A(2:end)==2)
ans =
1
Note that this is the count of duplicates if you have [1 1 1]
you'll get 2 not 1.
Upvotes: 0
Reputation: 25232
An alternative solution:
A = [0 0 0 0 1 0 0 0 1 0 1 1 0 0 1 0 1]
%// get Islands
a = cumsum(~A)
b = a(logical(A))
%// count occurences
c = histc(b,unique(b))
%// count number of occurences > 1
d = sum(c > 1)
%// or sum of occurences > 1
e = sum(c(c > 1))
c =
1 1 2 1 1
d =
1
e =
2
Upvotes: 1