MATLAB: Converting a vector of stings into a numerical vector

classificationclasslablesMATLABstring to intstring to numstring to numericalvector

Hi, I have a vectro of Strings like v =['def', 'def', 'def', 'atq', 'atq', 'dex', 'dex',….] How can I get a numerical vector like v_num =[1, 1, 1, 2, 2, 3, 3, …] So I want all "classlables" to be converted into a numerical "classlable". E.g all 'def's become 1 and all 'atq' become 2 and so on Thanks Tris

Best Answer

The third output of the unique function will do what you want:
v = {'def', 'def', 'def', 'atq', 'atq', 'dex', 'dex'};
[uv,~,ic] = unique(v, 'stable')
Classes = {uv(ic), ic};
for k1 = 1:length(v)
fprintf(1, '\t%s\t%d\n', char(v(k1)), ic(k1))
end
def 1
def 1
def 1
atq 2
atq 2
dex 3
dex 3
EDIT — Added print loop and output.