美文网首页
How to Rank Same Values with Sam

How to Rank Same Values with Sam

作者: 7912a5518547 | 来源:发表于2016-04-22 00:54 被阅读25次

    Reference: http://www.ilovematlab.cn/thread-448152-1-1.html
    Language: Matlab

    We enter into array A some students' grades

    A = [85 90 92 91 85 83 75 90 92 98 85 87]

    A =
    85 90 92 91 85 83 75 90 92 98 85 87

    and sort A by descend.

    [B,I] = sort(A,'descend');
    I(I) = (1:numel(A))'; % very cool code
    ranking1 = sortrows([A;I]',2)

    ranking1 =
    98 1
    92 2
    92 3
    91 4
    90 5
    90 6
    87 7
    85 8
    85 9
    85 10
    83 11
    75 12

    Here the ranking I ranks all same grade with various ranking (e.g. 85 marks has No.8 and No.9), thus we need take the first rankings to the same grades.
    Now we firstly get unique elements from array A.

    [C,ia,ic] = unique(A);
    % here C = A(ia) and A = C(ic).
    % by default, C is sorted by ascend
    C

    C =
    75 83 85 87 90 91 92 98

    C is the unique grades among original grades, each unique grade need share same ranking.

    ia

    ia =
    7 6 1 12 2 4 3 10

    ia is the index of elements of C in A, which corresponds to the most left of the elements if any element in C is repeated in A.

    ic

    ic =
    3 5 7 6 3 2 1 5 7 8 3 4

    ic stores indices of each element of A in C.
    And ia(ic) (right column below) is taking the first ranking if repeated.

    [A',I',ia(ic)]

    ans =
    85 8 1
    90 5 2
    92 2 3
    91 4 4
    85 9 1
    83 11 6
    75 12 7
    90 6 2
    92 3 3
    98 1 10
    85 10 1
    87 7 12

    So, ranking same value same rank is shown below

    ranking2 = sortrows([A;I(ia(ic))]',2)

    ranking2 =
    98 1
    92 2
    92 2
    91 4
    90 5
    90 5
    87 7
    85 8
    85 8
    85 8
    83 11
    75 12

    That's it.

    相关文章

      网友评论

          本文标题:How to Rank Same Values with Sam

          本文链接:https://www.haomeiwen.com/subject/whtxrttx.html