Get maximum values across a cell array with multiple indexing.

4 Ansichten (letzte 30 Tage)
Ajpaezm
Ajpaezm am 22 Sep. 2021
Kommentiert: dpb am 22 Sep. 2021
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!

Akzeptierte Antwort

dpb
dpb am 22 Sep. 2021
Bearbeitet: dpb am 22 Sep. 2021
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 Kommentare
Stephen23
Stephen23 am 22 Sep. 2021
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'}

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by