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

3 次查看(过去 30 天)
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.

采纳的回答

Torsten
Torsten 2022-8-28
编辑:Torsten 2022-8-28
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 个评论
Torsten
Torsten 2022-8-28
编辑:Torsten 2022-8-28
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.

请先登录,再进行评论。

更多回答(1 个)

Paul
Paul 2022-8-28
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 个评论
Torsten
Torsten 2022-8-28
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]

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by