How to get max of repeated values?

8 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

the cyclist
the cyclist il 24 Ott 2022
Modificato: the cyclist il 24 Ott 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]
D = 2×5
0.5000 1.0000 0.8000 0.7000 0.3000 0.4000 0.6000 0.8000 1.0000 1.2000
  1 Commento
Conner Carriere
Conner Carriere il 24 Ott 2022
Wow that works perfect! thanks for your quick input, now I am going to try and understand it.

Accedi per commentare.

Più risposte (2)

Paul
Paul il 24 Ott 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]
D = 2×5
0.5000 1.0000 0.8000 0.7000 0.3000 0.4000 0.6000 0.8000 1.0000 1.2000

John D'Errico
John D'Errico il 24 Ott 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]
Cfinal = 2×5
0.5000 1.0000 0.8000 0.7000 0.3000 0.4000 0.6000 0.8000 1.0000 1.2000

Community Treasure Hunt

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

Start Hunting!

Translated by