MATLAB: Replace column with text element into integers

conversionstrings

Hi all!
I have the matrix below (imported from a .txt file):
'pippo' 1 2
'pluto' 3 4
'minnie' 5 6
'pippo' 7 8
I would like to replace the cells with text into integers, like this:
'pippo' = 1
'pluto' = 2
'minnie' = 3
After looking at other answers in the MATLAB forum I came up with this non-working script:
CARTIS=readtable('try.txt');
a=find(strcmp([CARTIS{:,1}],'pippo'));
CARTIS(a,1)={'1'};
CARTIS(a,1)=table2array(CARTIS(a,1));
CARTIS(a,1)=cell2mat(CARTIS(a,1));
CARTIS(a,1)=str2num(CARTIS(a,1));
Could someone please explain how to fix it, please?
Thank you!

Best Answer

  • T = readtable('try.txt');
    T(:,1) = regexprep(T{:,1},'''','')
    T.Var1 =(strcmp(T{:, 1},'pippo') * 1 + strcmp(T{:, 1},'pluto') * 1 + strcmp(T{:, 1},'minnie') * 3)