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

18 views (last 30 days)
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?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 25 Feb 2021
Edited: MathWorks Support Team on 25 Feb 2021
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.

More Answers (0)

Categories

Find more on Tables in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!