How do I find no. of instances of each value till it changes?

조회 수: 1 (최근 30일)
Advay Pawar
Advay Pawar 2018년 7월 18일
댓글: Rik 2018년 7월 18일
I have the following input: [4 4 4 4 4 4 0 0 0 4 4 4 4 4 4 0 0 0 0 0 0 0 0 4 4 4 4 4];
I want MATLAB to give me the number of 4s and 0s in each set till the digit changes. So I want my output to be: [6 3 6 8 5].
Thank you!

답변 (2개)

Rik
Rik 2018년 7월 18일
편집: Rik 2018년 7월 18일
You can use the runlength function that Jan made.
Another option is using the code below.
input = [4 4 4 4 4 4 0 0 0 4 4 4 4 4 4 0 0 0 0 0 0 0 0 4 4 4 4 4];
diff([0 find(diff(input)) numel(input)])

Paolo
Paolo 2018년 7월 18일
편집: Paolo 2018년 7월 18일
This can be achieved nicely with regular expressions. Capture a digit and backreference back to the same digits to find the patterns of consecutive numbers.
input = [4 4 4 4 4 4 0 0 0 4 4 4 4 4 4 0 0 0 0 0 0 0 0 4 4 4 4 4];
num = regexp(char(input+'0'),'(\d)\1+','match');
n = cellfun(@numel, num)
>>n
6 3 6 8 5
  댓글 수: 6
Paolo
Paolo 2018년 7월 18일
Cheers! Your solution is indeed very efficient. Reason as to why I asked you to do it is because I am on mobile and do not have pc access.
Rik
Rik 2018년 7월 18일
It's a not-uncommon question, so I've seen some solutions before. My first instinct with the first I saw was a for-loop, so yours is miles better already.
And yeah, it's a bit much to copy this code to Matlab online or the app, just to have a benchmark, so I fully understand ;)

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by