Formatted output
The function
fprintf(fstr, variable_list)
prints out the values of the variables in variable_list according to the format described in the string fstr.
The format conventions follow the C language function fprintf. The format string fstr should contain a format descriptor for each variable in variable_list. A format descriptor starts with the special character %, followed by an integer giving the width of the field to be printed and a format descriptor. The most common ones are:
Operation | Symbol | Example | Result | ||
Decimal integers | %d | fprintf('%5d', -32) | -32 | ||
Floating point | %f | fprintf('%12.6f', -1/pi) | -0.318310 | ||
Scientific notation | %e | fprintf('%14.6e', -1/pi) | -3.183099e-01 | ||
Strings | %s | fprintf('%14s', 'Hello world') | Hello world | ||
Percentage | %% | fprintf('Return = %5.2f%%', 6.8) | Return = 6.80% | ||
Newline | \n | fprintf('\nBHP $%5.2f\n', 40.93) |
|
Notes:
- A newline \n character must be explicitly included at the end of a line of output. Otherwise the next fprintf continues exactly where the last one finished (which can be very useful).
- If you do not specify the field width, MATLAB tries to choose a sensible value.
- If the value being printed requires a wider field then MATLAB will automatically increase the width of the field. For example the scientific notation %14.6f requires at least 7 (8 on some systems) characters in addition to the number after the decimal point for the sign, the digit to the left of the decimal point, the decimal point, the exponent which is e-01 or e-001 depending on the operating system.
- Use %% if you actually want to print a percent character.
Run = 3,
Mass = 1.23e+07 tonnes,
Time = 6.45 secs.
using fprintf and the values of the variables, making sure the prompt is at the beginning of a new line after printing.
Define the variable run.
Define the variable mass.
Define the variable tr.
Print text and value of run.
Print text and value of mass.
Print text and value of tr, end with a newline.
Numbers and strings
Frequently we want plot titles, axis labels or legends that include the value of a variable, yet the arguments to these functions must be strings. One way around this problem is to convert a number to a string using the MATLAB function num2str.
num2str(run) converts the value of the variable run to a string, which is then combined with the other string using square brackets [ ].
You can also specify the format of the number. See help num2str for more information.
Output to strings
Matching the command fprintf there is a command sprintf which puts the results in a string, rather than printing it to the command window (or a file - see below).
The format descriptors for sprintf are exactly the same as for fprintf.
Output to files
You may well want to capture all the results of a MATLAB session in a file. One way of doing this is to use the command
diary my_file_name
at the beginning of the session, use whatever MATLAB commands you require, then use the command
diary off
at the end of the session. Everything printed in the command window will also be recorded in the file specified.
An alternative is to produce all your output using the fprintf command and write the output directly to a file. This requires three steps:
- Open a file with the appropriate name and permissions. This is done using
fid = fopen(my_file_name, 'w');
which opens the file specified in the string my_file_name and discards any existing contents already in that file. - Use the fprintf with an extra argument
at the beginning specifying the file to write to. That is use
fprintf(fid, fstr, variable_list);
as required to write information to the file with identifier fid. - At the end of your program, close the file using
fclose(fid);
Warning
Can you remember the commands you used yesterday or last week? The best strategy is to always write (small) M-files using the MATLAB editor and a suitable file name and comments in the file to describe its purpose. Then you can re-run the commands whenever you need simply by typing the name of the M-file in the MATLAB command window.
Self-test Exercise
Create the variables x = -3 and y = ex. Print x as a decimal integer and y both as a float with 6 digits after the decimal point and in scientific notation with 6 digits after the decimal point.Answer:
x = -3;
y = exp(x);
fprintf('x = %d\n', x)
fprintf('y = %.6f\n', y)
fprintf('y = %.6e\n', y)
Use the mouse to select the text between the word "Answer" and here to see the answer.
Summary
The MATLAB function fprintf produces formatted output on the screen or in a file. The function sprintf puts the formatted output in a string.
Formatting is specified by a string containing text, format descriptors which start with the % character, and special characters such as \n for a newline.