MATLAB Answers

How can i count how many time a number appears and for how long in a vector?

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!

Accepted Answer

Jan
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

  5 Comments

Show 2 older comments
salvatore vergine
salvatore vergine on 21 Jan 2021
For this vector, i want to obtain these 3 vectors (one for 0, one for 1 and one for 2):
v0=[0 1 0 0 0 0 0 0]
v1=[0 2 0 0 0 0 0 0]
v2=[0 1 0 0 0 0 0 0]
If the input vector was [0 1 1 2 1 1 1] the result would be:
v0=[1 0 0 0 0 0 0]
v1=[0 1 1 0 0 0 0]
v2=[1 0 0 0 0 0 0]
Thank you!!
Jan
Jan on 21 Jan 2021
I do not reliably recognize the relation between the inputs and outputs.
salvatore vergine
salvatore vergine on 21 Jan 2021
I try to explain it better. In each vector each column represents a pattern. For example, let s consider the number 1 and the input vector [0 1 1 2 1 1 1]. The result is the vector v1=[0 1 1 0 0 0 0] in which column 1 indicates how many times number 1 appears individually in the input vector (zero times in this case). Column 2 indicates how many times number 1 appears coupled in the input vector (only 1 as you can see). Column 3 indicates how many times number 1 appears as a triplet (only 1 too) and so on.
Another example with the input vector [0 1 1 0 1 1 0 1 2]. In this case the outpur vectors are:
v0=[3 0 0 0 0 0 0 0 0]
v1=[1 2 0 0 0 0 0 0 0]
v2=[1 0 0 0 0 0 0 0 0]
I hope I expressed myself better.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by