MATLAB Lesson 7 - Strings

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)
 
BHP $40.93

Notes:

Define the variables run with value 3, mass with value 1.23 x 107 tonnes and tr with value 6.45 seconds without echoing them to the screen. Create the following output
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.

>>  run = 3;
>>  mass = 1.23e7;
>>  tr = 6.45;
>>  fprintf('Run = %2d,\n', run);
>>  fprintf('Mass = %10.2e tonnes,\n', mass);
>>  fprintf('Time = %4.2f secs.\n', tr);

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.

Create the string ts with the text 'Results for run ' followed by the value of the variable run.

num2str(run) converts the value of the variable run to a string, which is then combined with the other string using square brackets [   ].

>>  ts = ['Results for run ' num2str(run)]



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).

Repeat the previous example using sprintf

The format descriptors for sprintf are exactly the same as for fprintf.

>>  ts = sprintf('Results for run %3d', run)

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:

Use MATLAB's help command or the help browser to get more information on these commands.

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.