Calculating the averages of different groups of values

2 次查看(过去 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 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by