Matlab: avoid for loops to find the maximum among values with same labels

后端 未结 2 1086
一个人的身影
一个人的身影 2021-01-22 02:43

I need to find the maximum among values with same labels, in matlab, and I am trying to avoid using for loops.

Specifically, I have an array L of labels and

2条回答
  •  佛祖请我去吃肉
    2021-01-22 03:14

    helper=[L.', V.'];
    helper=sortrows(helper,-2);
    [~,idx,~]=unique(helper(:,1));
    S=helper(idx,2);
    

    What I do is: I join the two arrays as columns. Then I sort them regarding second column with biggest element first. Then I get the idx of the unique Values in L before I return the corresponding Values from V.

    The solution from Luis Mendo is faster. But as far as I see his solution doesn't work if there is a zero,negative value or a noninteger inside L:

    Luis solution: Elapsed time is 0.722189 seconds.
    My solution: Elapsed time is 2.575943 seconds.
    

    I used:

    L= ceil(rand(1,500)*10);
    V= ceil(rand(1,500)*250);
    

    and ran the code 10000 times.

提交回复
热议问题