MATLAB: How to assign integers to each element in a table that has repeated elements

arrayassigning integersstrings

So say i have an array
x = ['Jake' ; 'Josh' ; 'Adams' ; 'Jake' ; 'Adams' ; 'Henry' ; 'Henry']
How would i go about assigning each string an integer starting from 1 while ignoring repetitions?
e.g Jake = 1, Josh = 2, Adams = 3, Henry = 4

Best Answer

Kevin, you really don't want to make a char array to store those names. Unless you have a pretty old version of MATLAB, use a string array (use a cell array of char vectors otherwise):
>> names = ["Jake"; "Josh"; "Adams"; "Jake"; "Adams"; "Henry"; "Henry"];
Put those names in a table, and use findgroups to get the unique numbers:
>> t = table(names)
t =
7×1 table
names
_______
"Jake"
"Josh"
"Adams"
"Jake"
"Adams"
"Henry"
"Henry"
>> t.numbers = findgroups(t.names)
t =
7×2 table
names numbers
_______ _______
"Jake" 3
"Josh" 4
"Adams" 1
"Jake" 3
"Adams" 1
"Henry" 2
"Henry" 2
But here's the thing: you have not said what you are doing, but usually the reason why people want to turn names into integers is because text is sometime awkward to work with. That's where categorical arrays come in. Depending on what you are doing, this is probably the way to go:
>> names = categorical(names)
names =
7×1 categorical array
Jake
Josh
Adams
Jake
Adams
Henry
Henry