How can I typecast a column in a table to a particular data type in MATLAB ?

16 次查看(过去 30 天)
I have a table named 'T' which is an  5 x 4 table. This table is created using the code in the first example in the documentation for the 'table' function. I wish to typecast the data type of the third column to INT8. Initially the entire data is numeric and the datatype is double. How can I change the datatype of the third column?

采纳的回答

MathWorks Support Team
编辑:MathWorks Support Team 2021-2-25
One possible way to cast the data in a particular column to INT8 is mentioned below. Assume that the variable name for the 3rd column in the table 'T' is named 'Weight'. You can typecast this column using the following command:
T.Weight = int8(T.Weight);
Now considering the size of the table, it is generally cumbersome to remember each of the variable names. In addition the above command does not allow for flexibility. To work around this issue, you can perform the following steps:
a) Obtain the list of variable names for the table. This can be done in the following way:
variableNames = T.Properties.VariableNames;
In the above line, 'variableNames' is a cell array of strings. The 3rd string is the name of the 3rd variable in the table 'T'
b) Using the variable names and the 'dot parenthesis' notation shown below, typecast the 3rd column, by accessing the 3rd variable:
T.(variableNames{3}) = int8(T.(variableNames{3}));
If you then access the 3rd column, you will notice that the data type is now INT8:
A1 = table2array(T(:,3)); %A1 is INT8
The above code utilizes a particular method to access data in a table. The methods to access data in a table are discussed at the following documentation page:
An example is attached which demonstrates how a particular column can be typecasted into INT8. The example is in a MATLAB file called TSExample.mWhen you want to change the datatype of mulitple columns at once, the best way is a for loop.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by