Unique ID Min and Max with multiple values per Unique ID
19 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
Fabio Freschi
el 15 de Oct. de 2019
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 comentarios
Star Strider
el 15 de Oct. de 2019
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
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!