How to modify decimal places when exporting data with fprintf
3 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a mixed-type table T that I want to export as a txt file. But I also need to change the number of decimals of T.d to 2 (I dont actually care about the number of decimals of the other variables). How do I do that ?
a = {'C1', 'A1', 'B1'}'
b = {'C', 'A', 'B'}'
c = {1.1, 2.1, 3.1}'
d = {1.16666, 2.16666, 3.16666}'
e = {'C', 'A', 'B'}'
f = {'C', 'A', 'B'}'
g = {1.1, 2.1, 3.1}'
h = {1.16666, 2.16666, 3.16666}'
T = table(a, b, c, d, e, f, g, h)
T_names = T.Properties.VariableNames;
y = table2cell(T);
fid = fopen('test.txt','wt');
fprintf(fid, '%s', T_names);
fprintf(fid, '%s %s %.1f %.2f %s %s %.1f %.5f\n', y);
fclose(fid);
Thank you,
3 个评论
Adam Danz
2020-5-28
编辑:Adam Danz
2020-5-28
The table would be more useful if the numeric values were not within cells.
a = {'C1', 'A1', 'B1'}'
b = {'C', 'A', 'B'}'
c = [1.1, 2.1, 3.1]' % <-- square brackets
d = [1.16666, 2.16666, 3.16666]' % <-- square brackets
e = {'C', 'A', 'B'}'
f = {'C', 'A', 'B'}'
g = [1.1, 2.1, 3.1]' % <-- square brackets
h = [1.16666, 2.16666, 3.16666]' % <-- square brackets
T = table(a, b, c, d, e, f, g, h)
Result
T =
3×8 table
a b c d e f g h
______ _____ ___ ______ _____ _____ ___ ______
{'C1'} {'C'} 1.1 1.1667 {'C'} {'C'} 1.1 1.1667
{'A1'} {'A'} 2.1 2.1667 {'A'} {'A'} 2.1 2.1667
{'B1'} {'B'} 3.1 3.1667 {'B'} {'B'} 3.1 3.1667
采纳的回答
Ameer Hamza
2020-5-28
Try this code
a = {'C1', 'A1', 'B1'}'
b = {'C', 'A', 'B'}'
c = {1.1, 2.1, 3.1}'
d = {1.16666, 2.16666, 3.16666}'
e = {'C', 'A', 'B'}'
f = {'C', 'A', 'B'}'
g = {1.1, 2.1, 3.1}'
h = {1.16666, 2.16666, 3.16666}'
T = table(a, b, c, d, e, f, g, h)
T_names = T.Properties.VariableNames;
y = table2cell(T).';
fid = fopen('test.txt','wt');
fprintf(fid, '%s ', T_names{:});
fprintf(fid, newline);
fprintf(fid, '%s %s %.1f %.2f %s %s %.1f %.5f\n', y{:});
fclose(fid);
更多回答(1 个)
Sulaymon Eshkabilov
2020-5-28
Hi,
Here is an easy solution with round():
a = {'C1', 'A1', 'B1'}'
b = {'C', 'A', 'B'}'
c = {1.1, 2.1, 3.1}'
d = {1.16666, 2.16666, 3.16666}'
DD=cell2mat(d);
dD=round(DD, 2);
d=num2cell(dD);
e = {'C', 'A', 'B'}'
f = {'C', 'A', 'B'}'
g = {1.1, 2.1, 3.1}'
h = {1.16666, 2.16666, 3.16666}'
T = table(a, b, c, d, e, f, g, h);
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!