Convert some Table Variables from Cell to Double

조회 수: 82 (최근 30일)
Smithy
Smithy 2022년 8월 9일
답변: Lei Hou 2022년 8월 31일
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'}

채택된 답변

Walter Roberson
Walter Roberson 2022년 8월 9일
for i = 1 : length(holdNames)
thisname = holdNames{i};
T.(thisname) = str2double(T.(thisname));
end

추가 답변 (1개)

Lei Hou
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' }

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by