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

1 view (last 30 days)
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!

Accepted Answer

Stephen23
Stephen23 on 26 Nov 2018
Edited: Stephen23 on 26 Nov 2018
>> 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

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!