フィルターのクリア

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 Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by