Counting number of runs (excluding zeros)?

1 view (last 30 days)
Aaron Varma
Aaron Varma on 16 Jun 2020
Commented: Aaron Varma on 18 Jun 2020
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 :)
  2 Comments
Aaron Varma
Aaron Varma on 16 Jun 2020
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 asnwer would be 6!
Thanks

Sign in to comment.

Answers (2)

Alan Stevens
Alan Stevens on 16 Jun 2020
Try plus1 = sum(data>0) and neg1 = sum(data<0)
  1 Comment
Aaron Varma
Aaron Varma on 16 Jun 2020
Thanks Alan but i think this would just add up all the 1's whereas I need to know the number of seperate run's of 1's. I've updated my query to make that more clear.
Thanks

Sign in to comment.


Image Analyst
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
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.
Aaron Varma
Aaron Varma on 18 Jun 2020
Thanks for your help, i'll have a look into it, when using bwlabel i get a message about not having th right package so guess i dont have it yet.
Thanks

Sign in to comment.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!