Skip to main content

Section 3.4 Formatted output

We have been using disp command to display some number or text. But we may want to display a sentence with some numbers included in it. And we may want to show more (or fewer) digits than disp does. For this, the command fprintf is useful: it produces an interpolated string which combines text and numeric data according to some formatting codes. For example,

fprintf('The number pi is %.15f and its cube is %.3f\n', pi, pi^3)

displays “The number pi is 3.141592653589793 and its cube is 31.006”. Explanation:

  • The first argument of fprintf is a string, the other arguments are numbers which will be inserted into the string. Here the numbers are pi and pi cubed.
  • The formatting code %.15f says: insert a number with 15 digits after decimal point. This is the first formatting code, so it uses the first number provided after the string, which is pi.
  • The formatting code %.3f says: insert a number with 3 digits after decimal point. Since this is the second formatting code in the string, it will use the second of the numbers after the string, which is pi cubed.
  • The string ends with new line character \n, which is a good idea in general. Without it, subsequent output would appear on the same line, and would be hard to read.

Note that 15-16 decimal digits is about the limit of precision in Matlab computations. If we try fprintf('The number pi is %.20f\n', pi) the output is “The number pi is 3.14159265358979310000” which looks suspicious, and for a good reason: the zeros at the end are not correct digits of pi.

For very large or very small numbers we need exponential notation. For example, if you ask Matlab to compute pi^100 it will display the answer as 5.1878e+49. This means \(5.1878 \cdot 10^{49}\text{.}\) The number after the letter e is the power of 10 by which we should multiply the number before “e”. The letter “e” stands for “exponential” not for the mathematical constant e. To use exponential notation in formatted strings, replace letter f in formatting codes by e. To remember these, note that f means Fixed decimal point, and e means Exponential notation.

fprintf('The 100th power of pi is %.6e\n', pi^100)

displays the result as “The 100th power of pi is 5.187848e+49”.

Often it is easiest to the formatting code g which lets Matlab decide between fixed point and exponential notation on its own, based on the size of the number. Here is an example.

x = 111.111
fprintf('The first four powers of %.6g are %.6g, %.6g, %.6g, %.6g\n', x, x, x^2, x^3, x^4)

The output is “The first four powers of 111.111 are 111.111, 12345.7, 1.37174e+06, 1.52415e+08”

There is also a formatting code %d to be used for integers, when you do not want a decimal dot at all.