3

我有一个这样的向量:

>> v = [1 1 1 2 2 3 4 4 4 4 4 5 5]'

v =

     1
     1
     1
     2
     2
     3
     4
     4
     4
     4
     4
     5
     5

向量已排序。每个值可以有任意数量。我需要找到每个值最后出现的索引。在这种情况下,它会返回这个:

answer =

     3    % index of the last occurence of "1"
     5    % index of the last occurence of "2"
     6    % index of the last occurence of "3"
    11    % index of the last occurence of "4"
    13    % index of the last occurence of "5"
4

3 回答 3

5

感谢@trumpetlicks,答案是unique

>> v = [1 1 1 2 2 3 4 4 4 4 4 5 5 6]'

v =

     1
     1
     1
     2
     2
     3
     4
     4
     4
     4
     4
     5
     5
     6

>> [~, answer] = unique(v)

answer =

     3
     5
     6
    11
    13
    14

[编辑] 在 MCR 的更新版本(R2013 ?)中, 的行为发生unique了变化。要获得相同的结果,您必须使用unique(v, 'legacy');

于 2012-07-06T16:16:28.460 回答
5
v = [1 1 1 2 2 3 4 4 4 4 4 5 5];
find(v==1,1,'last')
 % returns ans = 3
find(v==2,1,'last')
 % returns ans = 5

1 给出了你想要返回的出现次数,'first'或者'last'可以指定

于 2012-07-06T18:20:10.303 回答
1

尝试这个

[find(diff(v')) length(v)]

你应该能够自己弄清楚。

于 2012-07-06T15:18:32.457 回答