Removing trailing end characters in a table
24 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi guys,
I am trying to eliminate last two characters of variable names in a table. This is how my table looks like now (exported table to csv file attached). Couldn't get the csv file to show output here in Matlab live for some reason. But anyways my var name in column looks like for example 'abc_01_1' 'abc_02_1'. What I want to do is eliminate last two charaters which can be '_1' or '_2' or '_3' or '_4' and so on to be able to compare this table with a master variable list which doesn't have those last characters to find any missing and add them to the table with 'NA' as it's value
data = readtable('list.csv','Delimiter',',');
mlist = readtable('masterlist.txt', 'Delimiter',',');
The things that I have tried so far is the erase function like this
match = ["_1","_2","_3","_4"];
sz = size(data);
for idx = 1:sz(1,:)
var = data.Var1(1:idx);
newvar = erase(var,match);
end
data.Var1 = newvar;
%setdiff Error's out because the variable names are not the same
diff = setdiff(mlist,data);
NA_cell = cell(size(diff));
NA_cell(:) = {'NA'};
diff = [diff NA_cell];
%Then use vertcat to add 'diff' and 'data' together which wil be the final table with actual and missing.
But erase function elimitates all the instances of the charaters found in match so that didn't work out. Like if 'abc_01_1' then output of erase will be just 'abc0'.
I was also looking into strip function
newvar = strip(var,'right','_1') %But strip only works on removing one character from right so this didn't work either
Is there any other way to do this?
Thanks,
0 Kommentare
Akzeptierte Antwort
Cris LaPierre
am 6 Jul. 2022
You could use extractBefore and strlength. This works with string data, so I import text as stings.
data = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1056935/list.csv',...
'Delimiter',',','TextType','string')
% Set the position to the length of each string - 1
data.Var1 = extractBefore(data.Var1,strlength(data.Var1)-1)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Cell Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!