フィルターのクリア

Get maximum values across a cell array with multiple indexing.

2 ビュー (過去 30 日間)
Ajpaezm
Ajpaezm 2021 年 9 月 22 日
コメント済み: dpb 2021 年 9 月 22 日
Perhaps the title of my question isn't phrased at best, but hopefully the description will provide clear insight. I have the following couple of arrays:
idListReq = {'stock.A', 'stock.A', 'stock.A', 'stock.B', 'stock.B', 'stock.B', 'stock.B'};
factorData = [1, 4, 2, 9, 10, 1, 3];
Each element of idListReq has its numerical assignment in factorData. I would like to get the maximum across the groups of values that are tied to a single ID (e.g. values for 'stock.A' are 1, 4 and 2, meaning the max will be 4).
The desired outcome should like this:
idList = {'stock.A', 'stock.B'};
outcome = [4, 10];
What I used at the beginning was cellfun, and it worked, but I want to know if there's a better way for this, without using loops.
fData = cellfun(@(x) max(factorData(strcmp(idListReq, x))), idList);
Best regards and thanks in advance!

採用された回答

dpb
dpb 2021 年 9 月 22 日
編集済み: dpb 2021 年 9 月 22 日
Use grouping variables -- there's still a looping construct inside, of course, but you don't have to write it explicitly...
>> groupsummary(factorData.',idListReq.',"max")
ans =
4.00
10.00
>>
NB: 1. Must use column vectors, hence the ." transpose operator.
2. Looks like the id list variable would be ideal candidate for a categorical variable
  2 件のコメント
Stephen23
Stephen23 2021 年 9 月 22 日
The second output argument is probably also useful:
idListReq = {'stock.A', 'stock.A', 'stock.A', 'stock.B', 'stock.B', 'stock.B', 'stock.B'};
factorData = [1, 4, 2, 9, 10, 1, 3];
[V,C] = groupsummary(factorData(:),idListReq(:),@max)
V = 2×1
4 10
C = 2×1 cell array
{'stock.A'} {'stock.B'}
dpb
dpb 2021 年 9 月 22 日
Good point, @Stephen

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by