How to modify decimal places when exporting data with fprintf

4 Ansichten (letzte 30 Tage)
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 Kommentare
Adam Danz
Adam Danz am 28 Mai 2020
Bearbeitet: Adam Danz am 28 Mai 2020
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 am 28 Mai 2020
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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 28 Mai 2020
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 Kommentare
Blue
Blue am 28 Mai 2020
Thank you for your answer.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov am 28 Mai 2020
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);

Kategorien

Mehr zu Numeric Types finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by