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

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

Risposta accettata

Guillaume
Guillaume il 6 Feb 2020
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

Più risposte (0)

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by