Convert some Table Variables from Cell to Double

69 views (last 30 days)
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'}

Accepted Answer

Walter Roberson
Walter Roberson on 9 Aug 2022
for i = 1 : length(holdNames)
thisname = holdNames{i};
T.(thisname) = str2double(T.(thisname));
end

More Answers (1)

Lei Hou
Lei Hou on 31 Aug 2022
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' }

Categories

Find more on Tables in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!