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

조회 수: 6 (최근 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