Update multiple columns in table without loop, dot vs curly braces

3 次查看(过去 30 天)
Hi all,
I'd like to convert multiple columns (Variables) in a table object to another class like categorical or double. So far I have to use a loop, could this be simplified:
t = table(string(rand(3,1)),{'a';'b';'c'},{'aa';'bb';'cc'},...
'VariableNames',{'shallBeDouble', 'shallBeCategorical1', 'shallBeCategorical2'});
tBak = t;
catVars = {'shallBeCategorical1','shallBeCategorical2'};
for field = each(catVars)
t.(field) = categorical(t.(field));
end
doubleVars = {'shallBeDouble'};
for field = each(doubleVars)
t.(field) = double(t.(field));
end
disp(tBak)
disp(t)
output:
shallBeDouble shallBeCategorical1 shallBeCategorical2
_____________ ___________________ ___________________
"0.85303" 'a' 'aa'
"0.62206" 'b' 'bb'
"0.35095" 'c' 'cc'
shallBeDouble shallBeCategorical1 shallBeCategorical2
_____________ ___________________ ___________________
0.85303 a aa
0.62206 b bb
0.35095 c cc
I could use varfun to create a table or a cell of categorical values, but I can't assign them simultaneously:
t = table(string(rand(3,1)),{'a';'b';'c'},{'aa';'bb';'cc'},...
'VariableNames',{'shallBeDouble', 'shallBeCategorical1', 'shallBeCategorical2'});
catVars = {'shallBeCategorical1','shallBeCategorical2'};
t(:,catVars) = varfun(@categorical, t(:,catVars))
results in
The following error occurred converting from categorical to cell:
Conversion to cell from categorical is not possible.
Can the content of a column only be changed using the dot operator? I thought this would be equal: t.{:,'var1'} and t.var1?
Thanks!

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Categorical Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by