# Unique ID Min and Max with multiple values per Unique ID

12 ビュー (過去 30 日間)
Tessa Aus 2019 年 10 月 15 日

I need to find the min and max of each unique ID in a matrix. I have a unique ID X:1 matrix such as for example [10 17 201 333 1000]' (This matrix will always be the smaller of the two)
My second matrix is a Nx2 matrix where the first column is a series of uniq IDs and the second column the values
ex [10 10 17 17 17 201 1000; 0.1 69 1.7 33 55 67 0.99]
The output would be two matrixes both of the size X:1 where one would be the min and the other the max such as 0.1 being th minimum for ID 10 and maximum for ID 10 would be 69 and then on to the next unique ID until completed. If in the case where there is no Unique ID in the NX2 matching to X:1 Matrix the value outputed for it would be a 0. For that Unique ID.
I am assuming a imbedded for loop with indexing but Ive been getting nowhere.

#### 2 件のコメント

Walter Roberson 2019 年 10 月 15 日
findgroups() and splitapply()
Tessa Aus 2019 年 10 月 15 日
Could you give an example? Not sure how to structure the code as I do not know either of these. Thank you so much!

### 回答 (2 件)

Fabio Freschi 2019 年 10 月 15 日
Tessa, look if this fits your problem
% col vector
M1 = [10 17 201 333 1000].';
M2 = [10 10 17 17 17 201 1000; 0.1 69 1.7 33 55 67 0.99].';
% remove the entry in M1 that does not have a matching in M2(:,1)
ikeep = find(ismember(M1,M2(:,1)));
M1 = M1(ikeep);
% find entries in M2 for each entry in M1 and put them in a cella array
idx = arrayfun(@(M)find(M2(:,1) == M),M1,'UniformOutput',false);
% find minimum values
minVal = zeros(size(M1,1),1);
minVal(ikeep) = cellfun(@(i)min(M2(i,2)),idx);
% find maximum values
maxVal = zeros(size(M1,1),1);
maxVal(ikeep) = cellfun(@(i)max(M2(i,2)),idx);

#### 0 件のコメント

Star Strider 2019 年 10 月 15 日
One approach:
M = [10 10 17 17 17 201 1000; 0.1 69 1.7 33 55 67 0.99].';
[UM1, ia,ic] = unique(M(:,1), 'stable');
Vmx = accumarray(ic, M(:,2), [], @(x)max(x));
Vmn = accumarray(ic, M(:,2), [], @(x)min(x));
Out = [UM1, Vmn, Vmx];
T = array2table(Out, 'VariableNames',{'ID','Min','Max'})
producing:
T =
4×3 table
ID Min Max
____ ____ ____
10 0.1 69
17 1.7 55
201 67 67
1000 0.99 0.99