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

8 ビュー (過去 30 日間)
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?

採用された回答

the cyclist
the cyclist 2013 年 9 月 9 日
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)

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by