Calculating the averages of different groups of values

2 ビュー (過去 30 日間)
Thishan Dharshana Karandana Gamalathge
編集済み: Mohammad Abouali 2015 年 4 月 25 日
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 Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by