32 views (last 30 days)

I have a vector like this

v=[+1 +1 +1 0 0 0 +1 +1 -1 -1 +1 0 0 -1 -1 +1 +1]

I want to count how many times each number appears and for how long. i mean, for example let's consider +1. it appears indivigually only 1 time, then it appears in couple 2 times, then it appear in triplet only 1 time and so on. Could someone help me? thank you!

Jan
on 20 Jan 2021

Edited: Jan
on 20 Jan 2021

Start with a run-length-encoding, e.g. by FileExchange: RunLength . If you do not have a C-Compiler installed, use RunLength_M of this submission. Then:

v = [+1 +1 +1 0 0 0 +1 +1 -1 -1 +1 0 0 -1 -1 +1 +1];

[Num, Len] = RunLength_M(v)

Now you have the values and the lengths of the repetitions. Nur you can use histcounts to count, how often each sequence appears. If this is not time-ciritical, a simple loop does it also:

uniqNum = unique(Num);

for aNum = uniqNum(:).'

fprintf('Number: %d\n', aNum);

LenList = Len(Num == aNum);

uniqLenList = unique(LenList);

for aLen = uniqLenList(:)'

fprintf(' Block length: %d', aLen);

fprintf(' : %d times.\n', sum(LenList == aLen));

end

end

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

Start Hunting!
## 1 Comment

## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/722004-how-can-i-count-how-many-time-a-number-appears-and-for-how-long-in-a-vector#comment_1274324

⋮## Direct link to this comment

https://es.mathworks.com/matlabcentral/answers/722004-how-can-i-count-how-many-time-a-number-appears-and-for-how-long-in-a-vector#comment_1274324

Sign in to comment.