Can I specify the numeric precision for each column when exporting the table data using writetable?

I would like to specify the numeric precision for each column when exporting the table data using writetable function.
For example, in the following dataset, I would like to set A column to the last one digit and B column to the last three digits.
>> data = [(1:3)', rand(3,1)];
>> T = array2table(data,'VariableName',{'A','B'})
T =
A B
_ _______
1 0.81472
2 0.90579
3 0.12699
>> writetable(T,'mydata.csv','WriteRowNames',true)

 采纳的回答

There is no ability to specify the numeric precision for writetable. "writetable" outputs numeric variables using long g format.
To workaround, you can use num2str function to convert a numeric value to a character string.
>> T.A = num2str(T.A,'%1.1f\n');
>> T.B = num2str(T.B,'%1.3f\n');
>> T
T =
A B
___ _____
1.0 0.815
2.0 0.906
3.0 0.127
>> writetable(T,'mydata.csv','WriteRowNames',true)
>> type mydata.csv
A,B
1.0,0.815
2.0,0.906
3.0,0.127

2 个评论

The above has a disadvantage in that it changes the actual table data itself which may be undesireable and requires modifying each column independently.
Beginning with R2017a, one could create the rounded text on the fly as a temporary using the vectorized compose function to format and writecell beginning with R2019a to output the file.
AB=[1 0.81472
2 0.90579
3 0.12699];
T=array2table(AB,'VariableNames',{'A','B'});
writecell(compose('%0.1f,%0.3f',T.A,T.B),'AB.csv','QuoteStrings',0)
type AB.csv
1.0,0.815 2.0,0.906 3.0,0.127
Just a little more modern syntax, maybe, as another route to consider...but certainly the ability to specify a display/output format for table variables would be a most welcome enhancement....as another use case/justification, I've been dealing with a lot of financial data for local community college foundation last several years and while format bank, format compact is helpful for the financial columns, it is painful that 8-digit integer IDs then are also forced to have ".00" appended to them.
To play fair, using writetable does get the variable names to come along for the ride if needed/wanted while it takes a little more effort to do them this way to format them and add to the cell array before writing it out.
ADDENDUM
Adding the variable names and also referring to the whole table as an array -- since the variable names are returned as a cellstr array, simply JOINing them with the delimiter suffices.
writecell([join(T.Properties.VariableNames,',');compose('%0.1f,%0.3f',T{:,:})],'AB.csv','QuoteStrings',0)
type AB.csv
A,B 1.0,0.815 2.0,0.906 3.0,0.127
varfun can come in handy for converting all numeric variables in a table to desired format(s).

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Tables 的更多信息

产品

版本

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by