I have vector with values between 1
and N > 1
. Some values COULD occur multiple times consecutively. Now I want to have a second row which counts the consecutively entries and remove all those consecutively occuring entries, e.g.:
A = [1 2 1 1 3 2 4 4 1 1 1 2]'
would lead to:
B = [1 1;
2 1;
1 2;
3 1;
2 1;
4 2;
1 3;
2 1]
(you see, the second column contains the number of consecutively entries!
I came across accumarray()
in MATLAB recently but I can't find any solution with it for this task since it always regards the whole vector and not only consecutively entries.
Any idea?
This probably isn't the most readable or elegant way of doing it, but if you have large vectors and speed is an issue, this vectorisation may help...
First I'm going to pad A with a leading and trailing zero to capture the first and final transitions
The transition locations can be found where the difference between neighbouring values is not equal to zero:
But because we padded the start of A with a zero, the first transition is nonsensical, so we only take the locations from 2:end. The values in A of these are the value of each segment:
That's the first colomn - now to find the count of each number. This can be found from the difference in locations. This is where padding A at both ends becomes important:
Finally combining:
This can all be combined into one less-readable line: