Calculating the averages of different groups of values
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Thishan Dharshana Karandana Gamalathge
le 25 Avr 2015
Modifié(e) : Mohammad Abouali
le 25 Avr 2015
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.
0 commentaires
Réponse acceptée
Mohammad Abouali
le 25 Avr 2015
Modifié(e) : Mohammad Abouali
le 25 Avr 2015
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!