필터 지우기
필터 지우기

Calculating the averages of different groups of values

조회 수: 3 (최근 30일)
Hi,
I need to get averages of Ys, corresponds to similar groups of Xs separately, without combining the similar groups at two different places. What I mean is, the values of Ys (1,2,4) for the first set of X=3 should not combine with 10 which is Y for X=3 at the end.
Consider two vectors are as follows. Also, it is better if you do not use 'accumarray' command.
x=[3 3 3 4 4 5 5 5 5 3 11];
y=[1 2 4 5 7 1 1 8 10 10 1];
Thanks a lot.

채택된 답변

Mohammad Abouali
Mohammad Abouali 2015년 4월 25일
편집: Mohammad Abouali 2015년 4월 25일
x=[3 3 3 4 4 5 5 5 5 3 11];
y=[1 2 4 5 7 1 1 8 10 10 1];
groupBounds=[0; find(diff([x(:); NaN])~=0)];
groupAverage=arrayfun(@(gID) mean(y( (groupBounds(gID)+1):(groupBounds(gID+1)) )),1:(numel(groupBounds)-1));
fprintf('grpStartIDX grpEndIDX x_new y_new\n');
fprintf('%11d %9d %5d %5.2f\n',...
[(groupBounds(1:end-1)+1)'; ... %grpStartIDX
groupBounds(2:end)'; ... %grpEndIDX
x(groupBounds(2:end)); ... %x_new
groupAverage; ... %y_new
])
when you run it, you will get:
grpStartIDX grpEndIDX x_new y_new
1 3 3 2.33
4 5 4 6.00
6 9 5 5.00
10 10 3 10.00
11 11 11 1.00

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by