function Tdummy = dummytable(T)
narginchk(1,1)
validateattributes(T,{'categorical', 'table'},{},mfilename,'T',1);
if iscategorical(T)
cname = inputname(1);
if isempty(cname)
cname = 'Var1';
end
T = table(T,'VariableNames',{cname});
end
cats = varfun(@iscategorical,T,'OutputFormat','uniform');
if ~any(cats)
Tdummy = T;
return
end
w = nnz(~cats)+sum(varfun(@(x)numel(categories(x)),T(:,cats),'OutputFormat','uniform'));
datastorage = cell(1,w);
namestorage = cell(1,w);
idx = 0;
for ii = 1:width(T)
idx = idx+1;
if cats(ii)
Tii = T{:,ii};
categoriesii = categories(Tii)';
ncatii = numel(categoriesii);
dvii = num2cell(dummyvar(Tii), 1);
namesii = strcat(T.Properties.VariableNames{ii}, '_', categoriesii);
datastorage(idx:(idx+ncatii-1)) = dvii;
namestorage(idx:(idx+ncatii-1)) = namesii;
idx = idx+ncatii-1;
else
datastorage{idx} = T{:,ii};
namestorage(idx) = T.Properties.VariableNames(ii);
end
end
Tdummy = table(datastorage{:},'VariableNames',matlab.lang.makeValidName(namestorage));
end
Best Answer