Convert some Table Variables from Cell to Double

53 vues (au cours des 30 derniers jours)
Smithy
Smithy le 9 Août 2022
Réponse apportée : Lei Hou le 31 Août 2022
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'}

Réponse acceptée

Walter Roberson
Walter Roberson le 9 Août 2022
for i = 1 : length(holdNames)
thisname = holdNames{i};
T.(thisname) = str2double(T.(thisname));
end
  1 commentaire
Smithy
Smithy le 9 Août 2022
Thank you very much. It works really well.

Connectez-vous pour commenter.

Plus de réponses (1)

Lei Hou
Lei Hou le 31 Août 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' }

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by