Home > database >  Replace the values in a vector with the keys from a map in MATLAB?
Replace the values in a vector with the keys from a map in MATLAB?

Time:10-26

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.

CodePudding user response:

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
  • Related