runs of 1s and 2s in a long vector

조회 수: 2 (최근 30일)
Pappu Murthy
Pappu Murthy 2018년 7월 26일
댓글: Pappu Murthy 2018년 7월 26일
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
Sushant Mahajan
Sushant Mahajan 2018년 7월 26일
Do you need the total number of 1s and 2s? Or are you looking for the number of consecutive bunches (groups) of 1s/2s in that array?
jonas
jonas 2018년 7월 26일
Please provide an example including your desired output.

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2018년 7월 26일
편집: Guillaume 2018년 7월 26일
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
Stephen23
Stephen23 2018년 7월 26일
@Pappu Murthy: try starting the vector with one of the values that you are matching, and you will see why false is required.
Pappu Murthy
Pappu Murthy 2018년 7월 26일
Thanks. I got it why false is needed.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by