Effacer les filtres
Effacer les filtres

How do I take the average of elements of a vector depending on the values of another vector?

7 vues (au cours des 30 derniers jours)
Given two vectors, how do I take the average of values in one vector depending on what the value is in the second vector?
For example:
A = [2 3 2 2 3 4 3 3];
B = [0.1 0.2 0.22 0.13 0.07 0.88 0.3 0.5];
Here, I'd want to take the average of elements 1, 3, and 4 in B because they correspond to A = 2, and then similarly elements 2, 5, 7, and 8 in B that correspond to A = 3, and then element 6 corresponding tto A = 4.

Réponse acceptée

Torsten
Torsten le 28 Août 2022
Modifié(e) : Torsten le 28 Août 2022
A = [2 3 2 2 3 4 3 3];
B = [0.1 0.2 0.22 0.13 0.07 0.88 0.3 0.5];
Au = unique(A,'stable');
C = arrayfun(@(i)mean(B(A==Au(i))),1:numel(Au))
C = 1×3
0.1500 0.2675 0.8800
  1 commentaire
Torsten
Torsten le 28 Août 2022
Modifié(e) : Torsten le 28 Août 2022
I modified the answer from
Au = unique(A);
to
Au = unique(A,'stable');
for that the mean values are sorted according to the values appearing in A.
I don't know if this is important for your application.

Connectez-vous pour commenter.

Plus de réponses (1)

Paul
Paul le 28 Août 2022
This common workflow is discussed here: splitapply
A = [2 3 2 2 3 4 3 3];
B = [0.1 0.2 0.22 0.13 0.07 0.88 0.3 0.5];
[G,ID]=findgroups(A);
groupmean = splitapply(@mean,B,G);
table(ID.',groupmean.','VariableNames',{'ID' , 'GroupMean'})
ans = 3×2 table
ID GroupMean __ _________ 2 0.15 3 0.2675 4 0.88
  1 commentaire
Torsten
Torsten le 28 Août 2022
It might be necessary to order the groups according to the occurence of the elements in A.
Thus
findgroups([4 2 3 2 2 3 7 5 3 3])
should produce
[1 2 3 2 2 3 4 5 3 3 ]
not
[3 1 2 1 1 2 5 4 2 2]

Connectez-vous pour commenter.

Catégories

En savoir plus sur Graphics Object Programming dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by