Given a couple of vectors with priorities, is there a fast built-in function to find the index of the largest value?

1 Ansicht (letzte 30 Tage)
Consider that there exist three 10-dimensional vectors p1, p2, and p3, and the priority is given in order p1>p2>p3.
I want to find an index that is the largest in p1, the largest in p2 in case of a tie in p1, the largest in p3 in case of a tie in both p1 and p2, and randomly selected in case of a tie in all p1, p2, and p3.
That is, the code can be constructed as follows for given p1, p2, p3.
p1 = [1, 9, 3, 8, 4, 9, 1, 9, 5, 9]; % given
p2 = [5, 15, 6, 7, 10, 10, 5, 15, 1, 15]; % given
p3 = [1, 25, 3, 4, 11, 4, 1, 25, 99, 15]; % given
ind_p1 = (p1 == max(p1)); % Output: ind_p1 = [0, 1, 0, 0, 0, 1, 0, 1, 0, 1]
p2_prime = p2.*ind_p1; % Output: p2_prime = [0, 15, 0, 0, 0, 10, 0, 15, 0, 15]
ind_p2 = (p2_prime == max(p2_prime)); % ind_p2 = [0, 1, 0, 0, 0, 0, 0, 1, 0, 1]
p3_prime = p3.*ind_p2; % p3_prime = [0, 25, 0, 0, 0, 0, 0, 25, 0, 15]
ind_p3 = find(p3_prime == max(p3_prime)); % ind_p3 = [2, 8]
ind = ind_p3(randi(length(ind_p3))); % ind = 2 or 8
result = [ind, p1(ind), p2(ind), p3(ind)]; % result = [2, 9, 15, 25] or [8, 9, 15, 25]
I think the code for the above purpose will be used a lot in a wide variety of places.
Are there any quick (or code-readable) built-in MATLAB functions to produce the above results?

Antworten (1)

Bruno Luong
Bruno Luong am 15 Aug. 2020
Bearbeitet: Bruno Luong am 15 Aug. 2020
p1 = [1, 9, 3, 8, 4, 9, 1, 9, 5, 9]; % given
p2 = [5, 15, 6, 7, 10, 10, 5, 15, 1, 15]; % given
p3 = [1, 25, 3, 4, 11, 4, 1, 25, 99, 15]; % given
[pmax,loc] = sortrows([p1;p2;p3]');
result = [loc(end),pmax(end,:)]

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by