0
votes

Suppose I have a vector which contains person_ids like this :

x = [1,1,1,2,2,3,3,3,3,4]

so the first 3 items are for person 1. How can I find the vector indices that a new person starts?

i.e. my function should return

f(x) = [1,4,6,10];

is there a MATLAB way for this?

2

2 Answers

4
votes

Assuming the person IDs are sorted, and the IDs cannot be negative, you can do this using

>> x = [1,1,1,2,2,3,3,3,3,4];
>> find(diff([-1 x]))
ans =

    1    4    6   10
2
votes

Praetorian's answer is quite nice, but if you want another alternative, you can use the second output of unique. The second output determines the locations of the first unique value for a particular input sequence.

Also assuming that the person IDs are sorted, you can simply do this:

[~,y,~] = unique(x)

y =

 1
 4
 6
10

Minor Note

If you look at the unique documentation, before version R2013a, it used to find the location the last unique value for an input sequence in your array. This has now changed to the first location as of R2013a... which is the version I have. As such, should you have a version of MATLAB that is before R2013a, you need to add the 'first' flag as a second parameter to unique. Therefore:

[~,y,~] = unique(x, 'first');

If you have R2013a or higher, then you don't need to worry about this... but it's something to remember should you have something older.