How to modify decimal places when exporting data with fprintf

조회 수: 4 (최근 30일)
Blue
Blue 2020년 5월 28일
댓글: Ameer Hamza 2020년 5월 28일
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
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
Blue
Blue 2020년 5월 28일
Hi Adam,
I agree with you but the output of the sql query used to generate this table is 'cells', not double, and it is easier to leave them as cells if I dont need to modify those variables.
Thanks for the comment thought.

댓글을 달려면 로그인하십시오.

채택된 답변

Ameer Hamza
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);
  댓글 수: 3
Blue
Blue 2020년 5월 28일
Thank you for your answer.
Ameer Hamza
Ameer Hamza 2020년 5월 28일
I am glad to be of help!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sulaymon Eshkabilov
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);

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by