How do I find the location of the max value of a nd matrix efficiently?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Shep Bryan
am 22 Feb. 2020
Beantwortet: Walter Roberson
am 22 Feb. 2020
How do I find the location of the maximum value of a nd matrix efficiently? Right now I am hard coding my search for up to 5 dimensions:
function out = maxi(X)
Ndim = length(size(X));
if Ndim == 2
[a,b] = ind2sub(size(X), find(X==max(X,[],'all')));
out = [a,b];
elseif Ndim == 3
[a,b,c] = ind2sub(size(X), find(X==max(X,[],'all')));
out = [a,b,c];
elseif Ndim == 4
[a,b,c,d] = ind2sub(size(X), find(X==max(X,[],'all')));
out = [a,b,c,d];
elseif Ndim == 5
[a,b,c,d,e] = ind2sub(size(X), find(X==max(X,[],'all')));
out = [a,b,c,d,e];
end
end
Is there a way to do this more efficiently and for arbitrary number of dimensions?
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 22 Feb. 2020
[L{1:ndims(X)}] = ind2sub(size(X), max(X, [], 'all')) ;
out = cell2mat(L);
However if you want all the duplicates to show up then you would still use find()
0 Kommentare
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!