Convert multiple Table Variables from Cell to Double
35 views (last 30 days)
Show older comments
I have a table with many variables of mixed types (some strings, some numbers). The first X variables should be double/numeric, but they are cell arrays and in each cell the number is bounded by single quotes ({'2.496' }, {'6.675' } ,{'9.644' }, etc). I can convert the X columns to double one at at time.
T.bin1 = str2double(T.bin1);
T.bin2 = str2double(T.bin2);
...
T.binX = str2double(T.binX);
I checked the output: T.bin1 is a 167x1 cell array. str2double turns it into a 167x1 double. This single command methods works fine. But, I'm having trouble generalizing the code to a situation where I saved table names: HoldNames = T.Properties.VariableNames([1:X]);
This will work, but it's one at a time:
T.bin1 = str2double(table2cell(T(:,HoldNames(:,1)))) %a 167x1 double assigned into a 167 x1 Table
T.bin2 = str2double(table2cell(T(:,HoldNames(:,2))))
...
T.binX = str2double(table2cell(T(:,HoldNames(:,X))))
However, these do not work:
%a 167xX double assigned into a 167xX Table
T(:,HoldNames) = str2double(table2cell(T(:,HoldNames))) %Right hand side of an assignment into a table must be another table or a cell array.
%a 167xX double assigned into a 167xX cell array
T{:,HoldNames} = str2double(table2cell(T(:,HoldNames))) %Conversion to cell from double is not possible.
0 Comments
Answers (1)
Cris LaPierre
on 27 Jan 2021
I was able to get the following dummy example to work.
% Create table of cells
var = num2cell(rand(4,3));
var = cellfun(@num2str,var,'UniformOutput',false);
T = splitvars(table(var))
% Convert Var_2 and Var_3 to double (still cells)
HoldNames=["var_2","var_3"];
T{:,HoldNames} = table2cell(varfun(@str2double,T,'InputVariables',HoldNames))
1 Comment
Cris LaPierre
on 27 Jan 2021
I don't like that they are still cells. This approach isn't pretty, but it's the first way I found to change that.
% Create table of cells
var = num2cell(rand(4,3));
var = cellfun(@num2str,var,'UniformOutput',false);
T = splitvars(table(var))
% Convert Var_2 and Var_3 to double (as arrays)
HoldNames=["var_2","var_3"];
T_temp = varfun(@str2double,(varfun(@string,T(:,HoldNames))));
T(:,HoldNames)=[];
T(:,HoldNames)=T_temp
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!