Randal
Randal

Reputation: 25

Determining run-lengths of the elements of a vector

I am attempting to count the number of times each number in a vector occurrs contiguously in the vector.

For example, given

vector = [8 8 8 7 6 6 5 5 5 5 5 5 5 5 5 5 4 4 3 5 3 2 2];

I want an output which will tell me two dimensional matrix where the first row contains the value of the vector, and the second row contains the run length for that value:

8   7   6   5   4   3   5   3   2
3   1   2   10  2   1   1   1   2

The actual matrix is larger in size. Is there a specific function which returns such values or are there any other ways I can resolve this challenge?

Upvotes: 1

Views: 67

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112699

Try this:

ind = [find(diff(vector)) numel(vector)];
result = [vector(ind); ind(1) diff(ind)];

Upvotes: 1

Related Questions