Get maximum values across a cell array with multiple indexing.

2 次查看(过去 30 天)
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'}

请先登录,再进行评论。

更多回答(0 个)

类别

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

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by