Find that max and its index for data with multiple data values per index

조회 수: 3 (최근 30일)
Hello,
I looked around and found similar questions that have been answered (here 1 and here 2) but not sure how to find the max y value at each x value and its index. It might contain ore than an index of there is two max values.
so, I need to find the max, its index so I can create related to the original data in Sorted_ENP
Thanks in advance.
x = round(Sorted_ENP(:,end),1);
y = Sorted_ENP(:,end-1);
[uv,~,idx] = unique(x);
ymax = accumarray(idx,y,[],@max)
ymax_idx = accumarray(idx,y,[],@(x) maxidx(x))
% how can i find the index of ymax
All_data = Sorted_ENP(ymax_idx,:) % i want the matrix after the max values have been selected.
function ymax_idx = maxidx(x)
[~, ymax_idx] = max(x);
end

채택된 답변

Guillaume
Guillaume 2020년 2월 6일
There a many functions you can use for this (accumarray, splitapply, etc.) but with any of them you're going to have to build a vector of row index to your grouping function.
[group, value] = findgroup(round(Sorted_ENP(:,end),1));
rows = (1:size(Sorted_ENP, 1))';
max_idx = splitapply(@custom_max, Sorted_ENP(:,end-1), rows, group)
%for pretty display
array2table([value, max_idx], 'VariableName', {'x', 'max', 'max_idx'})
With
function max_idx = custom_max(vector, rowindices)
%takes a column vector and a vector of the same length indicating which rows of the original matrix, the values of the vector come form
%return a 2 element row vector, the max value, and the location with regards to the original row index of that max value
[maxval, loc] = max(vector);
max_idx = [maxval, rowindices(loc)];
end
  댓글 수: 1
Yaser Khojah
Yaser Khojah 2020년 2월 6일
thank you so much for your help. It is finally working. I truely appericate your help.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by