Convert multiple Table Variables from Cell to Double
34 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Cris LaPierre
2021-1-27
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 个评论
Cris LaPierre
2021-1-27
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!