Reputation: 787
I have a vector of nondecreasing data. Here is a sample:
1
1
1
2
2
2
2
2
2
2
2
3
3
4
4
6
Clearly there are duplicates and missing numbers. I can remove the duplicates using unique
, so my unique values are:
uniqueVals = unique(sortedData);
So far, so good. Now, I want to change the data so that the values in sortedData
are replaced with their index number in uniqueVals
. For instance, uniqueVals
first 5 elements would be 1,2,3,4,6
, with indices 1,2,3,4,5
. I want to change sortedData
so that 1 maps to 1, 2 maps to 2, 3 to 3, 4 to 4, 6 to 5 and so on.
I know I can create a "map" object, but that seems to just be used to map uniqueVals
to its index. How do I apply that mapping so that the entries in sortedData
are changed?
I have no need for this to be a particularly fast operation. sortedData
contains only a few hundred thousand rows and it only needs to be done once.
Upvotes: 2
Views: 133
Reputation: 30101
You can also use g = findgroups(sortedData);
, which will give you the group index, where there is one group per unique value. The 2nd output of this tells you the value itself
[g, gValue] = findgroups( sortedData );
Upvotes: 3
Reputation: 3511
You can use the third output from unique
[uniqueVals,~,yourOutput] = unique(sortedData);
yourOutput =
1 1 1 2 2 2 2 2 2 2 2 3 3 4 4 5
Upvotes: 3