Using fprintf to create a table of values

49 visualizaciones (últimos 30 días)
Britnie Carpentier
Britnie Carpentier el 9 de Feb. de 2019
Comentada: Stephen23 el 18 de Feb. de 2021
I am trying to get a table that looks like this while using fprintf. It is supposed to be left justified and the first column with no decimal places and the 2nd column 6 decimal places.
n h
------------
1.0000 1.0000
2.0000 1.5000
3.0000 1.8333
4.0000 2.0833
5.0000 2.2833
6.0000 2.4500
7.0000 2.5929
8.0000 2.7179
9.0000 2.8290
10.0000 2.9290
11.0000 3.0199
12.0000 3.1032
13.0000 3.1801
14.0000 3.2516
15.0000 3.3182
16.0000 3.3807
17.0000 3.4396
18.0000 3.4951
19.0000 3.5477
20.0000 3.5977
i tried this code but the columns and rows keep messing up
N = 20;
n = (1:1:20)';
h = cumsum(1./n);
m = [n h]
fprintf(' n h\n')
fprintf('----------\n')
fprintf('%-2.0f %-9.6f\n',m)
and i keep getting this as a result
n h
------------
1 2.000000
3 4.000000
5 6.000000
7 8.000000
9 10.000000
11 12.000000
13 14.000000
15 16.000000
17 18.000000
19 20.000000
1 1.500000
2 2.083333
2 2.450000
3 2.717857
3 2.928968
3 3.103211
3 3.251562
3 3.380729
3 3.495108
4 3.597740
>> how can I change this to look like the first table?

Respuestas (1)

Stephen23
Stephen23 el 9 de Feb. de 2019
Editada: Stephen23 el 9 de Feb. de 2019
Remember that MATLAB is column-major, so it works down the columns first. Pay careful attention to the orientation of the vectors:
n = 1:20;
h = cumsum(1./n);
m = [n;h];
fprintf(' n h\n')
fprintf('----------\n')
fprintf('%-2.0f %-9.6f\n',m)
giving:
n h
----------
1 1.000000
2 1.500000
3 1.833333
4 2.083333
5 2.283333
6 2.450000
7 2.592857
8 2.717857
9 2.828968
10 2.928968
11 3.019877
12 3.103211
13 3.180134
14 3.251562
15 3.318229
16 3.380729
17 3.439553
18 3.495108
19 3.547740
20 3.597740
  2 comentarios
James Thorpe
James Thorpe el 17 de Feb. de 2021
If you wanted to print the table in scientific notation with 4 significant digits, how would you go about it?
Stephen23
Stephen23 el 18 de Feb. de 2021
@James Thorpe:
fprintf('%.3e',pi)
3.142e+00

Iniciar sesión para comentar.

Categorías

Más información sobre Tables en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by