How to count consuctive 0's inbetween values of 1

12 vues (au cours des 30 derniers jours)
Chris E.
Chris E. le 17 Oct 2012
I have really long code that does what I want, but I wanted to try to find a faster code to do this, for loop is taking forever. for example I have a vector of:
count = [0; 1; 0; 0; 0; 1; 0; 1; 1; 1; 0; 0; 0; 1; 0; 1; 1; 0; 0]
What I would like for an answer is the consecutive 0's between the ones... so,
ans =
1
3
1
0
0
3
1
0
2
Here is what I have to do it, (count coming in is the 1 and 0 vector list), the output is "store":
for m = 1:size(count,1)
store = 0;
countlast = 0;
j = 0;
if (sum(count)>=1)
for n = 1:size(count,1)
if count(n) == 0
countlast = countlast + 1;
else
j = j + 1;
store(j) = countlast;
countlast = 0;
end
end
j = j + 1;
store(j) = countlast;
end
end
store'
If there is a faster way of doing this Please help me out! Thanks, Chris

Réponse acceptée

Kye Taylor
Kye Taylor le 17 Oct 2012
Modifié(e) : Kye Taylor le 17 Oct 2012
This is a fun one.
Try
count = reshape(count,1,[]); % make it a row vector
store = [nnz(cumsum(count)==0),...
diff(find(count))-1,...
nnz(cumsum(count)==max(cumsum(count)))-1]
  1 commentaire
Chris E.
Chris E. le 18 Oct 2012
Thanks a ton! glad you found it fun...

Connectez-vous pour commenter.

Plus de réponses (2)

Sean de Wolski
Sean de Wolski le 17 Oct 2012
v = [0; 1; 0; 0; 0; 1; 0; 1; 1; 1; 0; 0; 0; 1; 0; 1; 1; 0; 0;1];
vzcount = diff(find([1;v;1]))-1; %find ones in a [1;v;1] vector and take the difference -1
%Remove zeros from first or last element
if vzcount(1)==0;
vzcount = vzcount(2:end);
end
if vzcount(end) == 0;
vzcount = vzcount(1:end-1);
end

Derek O'Connor
Derek O'Connor le 18 Oct 2012

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by