Reputation: 5
I want to count number of consecutive ones in a vector from last position in vector.
For example in a=[0 1 0 1 0 1]
number of consecutive ones is 1.
In b = [1 0 0 1 1 1]
number of consecutive ones is 3.
Upvotes: 2
Views: 145
Reputation: 45741
Try this:
sum(a(find(diff(a),1,'last')+1:end))
or if you want to disregard the trailing 0
s then
sum(a(find(diff(a)==1,1,'last')+1:end))
And if you want this to work when a
contains only 1
s then I would suggest
sum(a(find(diff([0,a])==1,1,'last'):end))
Upvotes: 1
Reputation: 221524
For a case, when you might have trailing zeros in the input -
find(A,1,'last') - find(diff(A)==1,1,'last')
Sample run -
>> A = [0,1,1,0,0,0,1,1,1,1,1,0,0]
A =
0 1 1 0 0 0 1 1 1 1 1 0 0
>> find(A,1,'last') - find(diff(A)==1,1,'last')
ans =
5
Upvotes: 2