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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by