How to combining repeating groups of elements of an array while preserving order?

5 views (last 30 days)
I am having trouble combining repeated elements of my Matlab "data" variable. I can easily combine the values using unique and sort.
[sorted,idx] = sort(data);
[~,ij] = unique(sorted,'first');
Indx = (sort(idx(ij)));
However, by doing this I am combining ALL repeated values. What I really want to do is combine only groups of repeating elements. For example take this:
data = [1;1;1;2;2;2;3;3;3;4;4;4;4;4;3;3;2;2;2;2;1;1;1;1;4;4;4;4;]
Combine duplicate groups of elements:
data = [1;2;3;4;3;2;1;4;]
I need to combine the groups of repeating elements wile still preserving the order. It would also be helpful to return the index because I need to average data in another variable based on the index of combination.
For example:
data = [1;1;1;2;2;2;3;3;3;4;4;4;4;4;3;3;2;2;2;2;1;1;1;1;4;4;4;4;]
data2 = [7;2;4;5;3;4;6;8;5;3;5;7;4;2;4;6;8;4;3;6;7;8;4;2;9;3;2;0;]
dataCombined = [1; 2; 3; 4; 3; 2; 1; 4; ]
data2average = [4.33; 4; 6.33 4.2 5; 5.25; 5.25; 3.5; ]
Can anyone give suggestions?

Accepted Answer

the cyclist
the cyclist on 9 Sep 2013
data = [1;1;1;2;2;2;3;3;3;4;4;4;4;4;3;3;2;2;2;2;1;1;1;1;4;4;4;4;];
data2 = [7;2;4;5;3;4;6;8;5;3;5;7;4;2;4;6;8;4;3;6;7;8;4;2;9;3;2;0;];
groupIndex = cumsum(abs(diff([nan;data]))~=0);
dataCombined = accumarray(groupIndex,data,[],@mean)
data2average = accumarray(groupIndex,data2,[],@mean)

More Answers (0)

Categories

Find more on Structures 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!