Change table variable data type
Afficher commentaires plus anciens
I used readtable() to read a text file into a table. One of the columns of the table was read (by default) as a double rather than a string. How does one change a columns datatype within a table?
Réponse acceptée
Plus de réponses (2)
Jeffrey Daniels
le 4 Juin 2020
6 votes
fileName = table.xlsx;
opts = detectImportOptions(fileName);
opts.VariableTypes{15} = 'char'; % This will change column 15 from 'double' or whatever it is to 'char', which is what you want.
new_table = readtable(fileName,opts);
1 commentaire
yunyu Hu
le 5 Nov 2020
This is a simple and clean solution.
Peter Perkins
le 7 Juil 2017
0 votes
readtable also accepts a Format parameter that would allow you to override the automatic type detection.
4 commentaires
Nikhil Tawakley
le 15 Août 2017
Peter Perkins
le 16 Août 2017
I don't know what this means. Tables don't have formats.
Nikhil Tawakley
le 29 Août 2017
Walter Roberson
le 29 Août 2017
No, it is not possible to copy-paste datatypes. However, you could use
old_class = arrayfun(@class, OldTable.VariableName, 'Uniform', 0);
new_variable = arrayfun(@(value, newclass) cast(value, newclass), NewTable.VariableName, old_class, 'uniform', 0);
NewTable.VariableName = new_variable;
This assumes that each entry in the variable is a potentially different type -- which would not be the case for numeric entries for example. If you have numeric entries, then
NewTable.VariableName = cast( NewTable.VariableName, class(OldTable.VariableName) );
Catégories
En savoir plus sur Tables dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!