Finding indexes of maximum values of an array

后端 未结 3 1358
鱼传尺愫
鱼传尺愫 2021-01-22 11:00

How do I find the index of the 2 maximum values of a 1D array in MATLAB? Mine is an array with a list of different scores, and I want to print the 2 highest scores.

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-22 11:02

    I'll go for an O(k*n) solution, where k is the number of maximum values you're looking for, rather than O(n log n):

    x = [3 2 5 4 7 3 2 6 4];
    y = x; %// make a copy of x because we're going to modify it
    [~, m(1)] = max(y);
    y(m(1)) = -Inf;
    [~, m(2)] = max(y);
    
    m =
    
       5   8
    

    This is only practical if k is less than log n. In fact, if k>=3 I would put it in a loops, which may offend the sensibilities of some. ;)

提交回复
热议问题