Counting number of runs (excluding zeros)?
1 view (last 30 days)
Show older comments
Hi there, I'm looking for a bit of help to count the number of runs of numbers but excluding zeros.
Scoured the internet but just cant find something that ignores zeros.
Bascially I have a column of data made up of 1's, -1's, and 0's
I need to count the number of runs of 1's and the number of runs of '-1's.
A = [0,1,1,1,1,1,0,0,0,1,1,1,0,1,1,1,0,-1,-1,-1,-1,-1,-1,0,0,1,1,-1,-1,0]
The data would like like this, and the answer would be 6!
Thanks for your help :)
Answers (2)
Image Analyst
on 16 Jun 2020
You need bwlabel() to stamp each contiguous region with an ID number. Then add them together:
A = [0,1,1,1,1,1,0,0,0,1,1,1,0,1,1,1,0,-1,-1,-1,-1,-1,-1,0,0,1,1,-1,-1,0]
[~, num1s] = bwlabel(A == 1)
[~, numMinus1s] = bwlabel(A == -1)
totalRegions = num1s + numMinus1s
3 Comments
Image Analyst
on 16 Jun 2020
It's in the Image Processing Toolbox, which almost everyone has. The closest thing is findgroups() but I'm not sure how to make it count the groups. Maybe if you use splitapply() or something. If you need to write your own bwlabel() routine, I'm sure there are "connected components labeling" code out there.
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!