Convert some Table Variables from Cell to Double

76 ビュー (過去 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 件のコメント
Smithy
Smithy 2022 年 8 月 9 日
Thank you very much. It works really well.

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeTables についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by