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

7 views (last 30 days)
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.

Accepted Answer

Torsten
Torsten on 28 Aug 2022
Edited: Torsten on 28 Aug 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 Comment
Torsten
Torsten on 28 Aug 2022
Edited: Torsten on 28 Aug 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.

Sign in to comment.

More Answers (1)

Paul
Paul on 28 Aug 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 Comment
Torsten
Torsten on 28 Aug 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]

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!