Grouping items with the same identifier and detecting the maximum value, as well as its location

I have two vectors of length 16. The first one r, for example:

r = [1;3;5;7;1;3;6;7;9;11;13;16;9;11;13;16];

rcontains a list of identifiers. I want to collect indexes of duplicate identifiers in rso that each group is a list of indexes for a single ID. Then I used these indices to access the second vector aand would find the maximum value that falls on the indices for each group.

Therefore, I would like to create an output vector using rand aso that:

max(a(1),a(5)), max(a(2),a(6)), a(3), a(7), max(a(4),a(8)), max(a(9),a(13)), max(a(10),a(14)), max(a(11),a(15)), max(a(12),a(16))

I also want to keep the indexes of the maximum values. How can I effectively implement this in MATLAB?

+4
source share
1 answer

You can use the third pin uniqueto assign each unique number to a runique identifier. Then you can combine all numbers that have the same identifier with a call accumarraywhere the key is a unique identifier and the value is the actual value afor the corresponding key position in this unique array of identifiers. After you have collected all these values, use accumarrayso that you can use these values ​​for each unique value in rto reference aand select the maximum element:

%// Define r and a
r = [1;3;5;7;1;3;6;7;9;11;13;16;9;11;13;16];
a = [...];

%// Relevant code
[~,~,id] = unique(r, 'stable');
out = accumarray(id(:), a(:), [], @max);

'stable' unique , . , r , , .

. 16 , a, . r:

rng(123);
a = rand(16,1);
r = [1;3;5;7;1;3;6;7;9;11;13;16;9;11;13;16];

a:

>> a

a =

    0.6965
    0.2861
    0.2269
    0.5513
    0.7195
    0.4231
    0.9808
    0.6848
    0.4809
    0.3921
    0.3432
    0.7290
    0.4386
    0.0597
    0.3980
    0.7380

:

out =

    0.7195
    0.4231
    0.2269
    0.6848
    0.9808
    0.4809
    0.3921
    0.3980
    0.7380

, . , a(1) a(5), 0,6965 0,7195 , - 0,7195. , a(2) a(6), 0.2861 0.4231, - 0.4231 ..


, , . accumarray, a, . max, . max max max ( , ... Python NumPy, numpy.argmax), (.. @(x) ...), .

maxmod maxmod.m. :

function p = maxmod(vals, ind)
    [~,ii] = max(vals(ind));
    p = ind(ii);

, vals. , , .

accumarray :

%// Define r and a
r = [1;3;5;7;1;3;6;7;9;11;13;16;9;11;13;16];
a = [...];

%// Relevant code
[~,~,id] = unique(r, 'stable');
out = accumarray(id(:), (1:numel(r)).', [], @(x) maxmod(a,x));

, :

>> out

out =

     5
     6
     3
     8
     7
     9
    10
    15
    16

, , a, .

+6

Source: https://habr.com/ru/post/1610022/


All Articles