问题
I have a vector like this :
>> 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
The vector is sorted. There can be any number of each values. I need to find the index of the last occurence of each value. In this case, it would return this :
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"
回答1:
Thanks to @trumpetlicks, the answer is 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
[EDIT]
In more recente version of the MCR (R2013 ?), the behavior of unique
has changed. To get the same result, you must use unique(v, 'legacy');
回答2:
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
the 1 gives the number of occurrences you want to return, and 'first'
or 'last'
may be specified
回答3:
Try this
[find(diff(v')) length(v)]
You should be able to figure it out yourself.
来源:https://stackoverflow.com/questions/11364920/find-index-of-last-occurrence-for-each-value