Search code examples
stringmatlabuniqueenumeration

How to enumerate a cell of strings with unique numbers?


Let's say I have an N x 1 cell (let's set N = 5) where each element is a string that can be repeated. So an example would be this:

x = {'x', 'b', 'c', 'x', 'd'}

I want to determine the unique strings and obtain an N x 1 identifier vector, which, for this case, is:

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

No alphabetical ordering is required, I just want each integer in y correspond to a unique string in x. Is there an easy way to do this in MATLAB?

Thanks for any help,


Solution

  • Yes: use the third output of unique with the 'stable' input flag:

    [~, ~, result] = unique(x, 'stable');