MATLAB: How to tranfer the data types of the selected columns of the table from cell string to numeric

convertdata typenumericstringtable

I want to tranfer the data type of the selected columns of the table from cellstring to numeric.
However, I am stuck by this error: cannot convert from double to cell
selected_cols={'Dailypeakwindspeed', 'Dailyprecip', ...
'Dailysnowdepth', 'Dailysnowfall'};
% tb_daily is my table
tb_daily(:,selected_cols)= varfun( @str2double, tb_daily,...
'InputVariables', selected_cols); % this line errors
I found out that tb.Var is not equivalent with tb{:,'Var'}, which is shown by the example below.
tb=table({'1';'2'});
tb(:,'Var1')= table([1;2]) % this gives error: cannot convert from double to cell

tb{:,'Var1'}= [1;2] % this gives error: cannot convert from double to cell
tb.Var1= [1;2] % this is successful! Weird!!!
Too weird!
One solution would be to use the dot syntax, but that means I have to repeat this for every selected column, therefore not satisfied.

Best Answer

What you're seeing is because parenthesis and brace assignments are into, while dot assignments replace. To see why, consider tbl(2:end-1,'Var1') = value -- you wouldn't want that to be able to change Var1's type.
There are two options:
1) Write a loop like this:
for i = 1:length(selectedVars)
varName = selectedVars{i};
tbl.(varName) = str2double(t.(varName));
end
If you want to convert all the cellstrs to numeric, you could also write the loop like this:
for i = 1:width(tbl)
var = tbl.(i);
if iscellstr(var)
tbl.(i) = str2double(var);
end
end
2) Horzontally concatenate the output from varfun with the remaining part of tbl, and rearrange the variables afterwards. Something like this:
origVarOrder = tbl.Properties.VariableNames;
selectedVars = varfun(@isnumeric,tbl,'UniformOutput',true);
tbl1 = tbl(~selectedVars);
tbl2 = varfun(@str2double,tbl,'InputVariables',selectedVars);
tbl = [tbl1 tbl2];
tbl = tbl(:,origVarOrder);
Hope this helps.