MATLAB: How to create an array that counts the number of consecutive repeating numbers in a given array

arrayloopmatrix

For example, if I have a matrix something like this, A = [1;1;1;2;2;2;2;2;3;3;4;4;4;4;4;4;4;5;5;5;5;1;1;1;3;3;3;3;3;3]. How would I create a matrix that looked like this?
B = [1;2;3;1;2;3;4;5;1;2;1;2;3;4;5;6;7;1;2;3;4;1;2;3;1;2;3;4;5;6]. So it counts up to 3 since there are 3 ones. And then up to 5 since there are 5 2s. I was going to use the unique function for this but don't think it'll work because some of the numbers repeat nonconsecutively. Please help!

Best Answer

>> A = [1;1;1;2;2;2;2;2;3;3;4;4;4;4;4;4;4;5;5;5;5;1;1;1;3;3;3;3;3;3];
>> V = diff(find([1;diff(A)~=0;1]));
>> C = arrayfun(@(n)1:n,V,'uni',0);
>> B = [C{:}].'
B =
1
2
3
1
2
3
4
5
1
2
1
2
3
4
5
6
7
1
2
3
4
1
2
3
1
2
3
4
5
6