1

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?

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
Randal
  • 25
  • 4

1 Answers1

1

Try this:

ind = [find(diff(vector)) numel(vector)];
result = [vector(ind); ind(1) diff(ind)];
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • thanks, If using 'unique' then the result is not the same as the example above. 'unique' will count the number of each vector so that the result is not the same as the example above – Randal Feb 27 '15 at 21:31
  • Sorry. Your title was confusing. What you want is not what the title says. You want run-length encoding. I'll rewrite my answer – Luis Mendo Feb 27 '15 at 21:46
  • Try now. I suggest you rephrase the title to something like "Determining run-lengths in a vector" – Luis Mendo Feb 27 '15 at 21:50