runs of 1s and 2s in a long vector

1 view (last 30 days)
Pappu Murthy
Pappu Murthy on 26 Jul 2018
Commented: Pappu Murthy on 26 Jul 2018
i have a long vector which has a whole bunch of 1s and 2s.. I need to find how many such strings of 1s and 2s are there. Is there a slick way of getting this out of the array?
  2 Comments
jonas
jonas on 26 Jul 2018
Please provide an example including your desired output.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 26 Jul 2018
Edited: Guillaume on 26 Jul 2018
If you want to find the number of runs (regardless of their length) as opposed to the count of 1s or 2s:
v = [0 3 1 1 1 4 5 6 2 2 2 1 1 2 7 8 9 1 1 1 2 2 1 1 1 10 11 2 2 12 2]; %demo data
runcount = @(v, n) nnz(diff([false, v == n]) == 1); %works only for row vectors
runsof1 = runcount(v, 1)
runsof2 = runcount(v, 2)
  4 Comments
Pappu Murthy
Pappu Murthy on 26 Jul 2018
Thanks. I got it why false is needed.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!