Get maximum values across a cell array with multiple indexing.

2 visualizaciones (últimos 30 días)
Ajpaezm
Ajpaezm el 22 de Sept. de 2021
Comentada: dpb el 22 de Sept. de 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!

Respuesta aceptada

dpb
dpb el 22 de Sept. de 2021
Editada: dpb el 22 de Sept. de 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 comentarios
Stephen23
Stephen23 el 22 de Sept. de 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'}

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by