How to get max of repeated values?
8 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
the cyclist
2022-10-24
编辑:the cyclist
2022-10-24
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]
更多回答(2 个)
Paul
2022-10-24
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 个评论
John D'Errico
2022-10-24
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 个评论
另请参阅
类别
在 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!