Convert some Table Variables from Cell to Double
86 次查看(过去 30 天)
显示 更早的评论
Hello everybody,
I have a table with many variables of mixed types (some strings, some numbers).
and I would like to convert some of them as double/numeric type. Based on HoldNames.
I hope to make the HoldNames' columns to double in the table. Please some helps.
I tried with for loop. But I think there might be more matlab-like way (fancy) to do it.
% Create table of cells
var = num2cell(rand(4,3));
Names = {'Steve';'John';'Paul';'Evan'};
var = [var,Names];
T = splitvars(table(var));
% Below code to verify the Data Type
varfun(@class,T,'OutputFormat','cell') % {'cell'} {'cell'} {'cell'} {'cell'}
% Convert Var_2 and Var_3 to double
HoldNames={'var_2','var_3'};
% Below Code is working. But I think there might be more matlab-like way to do it.
for i = 1:length(HoldNames)
val(i) = find(strcmpi(T.Properties.VariableNames,HoldNames(i)));
end
for i = 1:length(HoldNames)
if iscell(T.(val(i)))
T.(val(i)) = str2double(T.(val(i)));
end
end
% Below code to verify the Data Type. Now converted Var_2 and Var_3 to double
varfun(@class,T,'OutputFormat','cell') % {'cell'} {'double'} {'double'} {'cell'}
0 个评论
采纳的回答
Walter Roberson
2022-8-9
for i = 1 : length(holdNames)
thisname = holdNames{i};
T.(thisname) = str2double(T.(thisname));
end
更多回答(1 个)
Lei Hou
2022-8-31
The funciton 'convertvars' is designed to be a convenient way to type conversion of table variable. Regarding your use case, you can do
>> T = convertvars(T,{'var_2','var_3'},'cell2mat')
T =
4×4 table
var_1 var_2 var_3 var_4
__________ _______ _______ _________
{[0.4088]} 0.48851 0.19976 {'Steve'}
{[0.1418]} 0.46403 0.31925 {'John' }
{[0.5649]} 0.9611 0.62927 {'Paul' }
{[0.2521]} 0.12603 0.12671 {'Evan' }
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!