How to modify decimal places when exporting data with fprintf

1 visualizzazione (ultimi 30 giorni)
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 Commenti
Adam Danz
Adam Danz il 28 Mag 2020
Modificato: Adam Danz il 28 Mag 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 il 28 Mag 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.

Accedi per commentare.

Risposta accettata

Ameer Hamza
Ameer Hamza il 28 Mag 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 Commenti

Accedi per commentare.

Più risposte (1)

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

Categorie

Scopri di più su Numeric Types in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by