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!
댓글 수: 0
채택된 답변
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
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)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!