How to get max of repeated values?
8 views (last 30 days)
Show older comments
Conner Carriere
on 24 Oct 2022
Answered: John D'Errico
on 24 Oct 2022
I have a matrix
C =
0.5000 0.5000 0.3000 1.0000 0.8000 0.3000 0.7000 0.7000 0.3000
0.4000 0.6000 0.8000 0.6000 0.8000 1.0000 0.8000 1.0000 1.2000
I am looking at the C(2,:) row, everytime there is a repeated instance, I need to take the values from C(1,instance) look at them and max them
The end matrix should look like this
D =
0.5000 1.0000 0.8000 0.7000 0.3000
0.4000 0.6000 0.8000 1.0000 1.2000
Trying to explain better
look at C(2,:)
only 1 value of 0.4, so max of it is 0.5
2 values of 0.6, these are .5 and 1.0, max of these is 1
3 values of 0.8, these are .3 .8 and .7, max of these is .8
so on so forth
0 Comments
Accepted Answer
the cyclist
on 24 Oct 2022
Edited: the cyclist
on 24 Oct 2022
Here is one way;
% Input
C = [0.5000 0.5000 0.3000 1.0000 0.8000 0.3000 0.7000 0.7000 0.3000
0.4000 0.6000 0.8000 0.6000 0.8000 1.0000 0.8000 1.0000 1.2000];
% Identify the unique values of the second row of C, along with the index to where
% each of those values appear
[uniqueC,~,indexFromUniqueCBackToAll] = unique(C(2,:));
% For convenience, define the number of unique values
numberUniqueC = numel(uniqueC);
% Preallocate the matrix where the max values are stored
maxRow1 = zeros(1,numberUniqueC);
% For each unique value, in order, find the max of the corresponding values
% in row 1
for nc = 1:numberUniqueC
indexToThisCValue = (indexFromUniqueCBackToAll==nc);
maxRow1(nc) = max(C(1,indexToThisCValue));
end
% Append the max values to the unique values to create the output
D = [maxRow1; uniqueC]
More Answers (2)
Paul
on 24 Oct 2022
Can use splitapply
C = [0.5000 0.5000 0.3000 1.0000 0.8000 0.3000 0.7000 0.7000 0.3000
0.4000 0.6000 0.8000 0.6000 0.8000 1.0000 0.8000 1.0000 1.2000];
[G,ID] = findgroups(C(2,:));
D = [splitapply(@max,C(1,:),G) ; ID]
0 Comments
John D'Errico
on 24 Oct 2022
Easy enough. Use unique, then it is just a call to accumarray.
C = [0.5000 0.5000 0.3000 1.0000 0.8000 0.3000 0.7000 0.7000 0.3000
0.4000 0.6000 0.8000 0.6000 0.8000 1.0000 0.8000 1.0000 1.2000];
% First, match the second row with a set of indices. unique does this.
[C2unique,~,Uind] = unique(C(2,:));
% next, use accumarray to find the group maxima, for each repeated element,
% as identified by Uind
C1max = accumarray(Uind,C(1,:)',[numel(C2unique),1],@max);
Cfinal = [C1max';C2unique]
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!