Change table variable data type
376 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
採用された回答
Sean de Wolski
2017 年 7 月 7 日
Change it before reading it in by modifying the options passed to readtable.
Or
t.Var1 = num2str(t.Var1)
2 件のコメント
Peter Perkins
2017 年 7 月 7 日
Without meaning to contradict Sean, num2str is almost certainly not what you want, at least not by itself. It is a very old function that creates a char matrix, which will likely be pretty awkward to work with. One possibility is to apply cellstr to that char matrix, another (if you're using a recent version of MATLAB) would be to convert using the string function (as in, string, the new class).
その他の回答 (2 件)
Jeffrey Daniels
2020 年 6 月 4 日
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);
Peter Perkins
2017 年 7 月 7 日
readtable also accepts a Format parameter that would allow you to override the automatic type detection.
4 件のコメント
Walter Roberson
2017 年 8 月 29 日
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) );
参考
カテゴリ
Help Center および File Exchange で Tables についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!