Skip to main content
Library homepage
 
Engineering LibreTexts

13.1: sprintf() and fprintf() Part 1

  • Page ID
    85188
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    This section describes how to use the sprintf() function to write to a string and how to use the fprintf() function to write to the screen.

    The next section describes how to use the fprintf() function to print formatted messages and numbers to a file.

    sprintf() and fprintf() for strings without numbers

    sprintf means string print formatted. What this means, is that it can create a formatted message and store it in a character string variable. It could be used to create a title or part of a title to pass to a routine that makes plots.

    title_str1 = sprintf('MATLAB Homework Plot')

    fprintf means file print formatted. What this means, is that it can create a formatted message and store it in a file. When no file is specified, it prints to the screen, like this:

    fprintf('Hello World\n')

    The \n puts the cursor at the beginning of a new line. Otherwise, the cursor is at the end of the message just printed. A \n is needed for most fprintf() messages.

    sprintf() and fprintf() with scalar numbers, simple formatting

    To create a message with numbers, the numbers need to be converted to strings using one of these format strings:

    Format string options:
    %f = Fixed point notation (decimal)
    %e = Exponential notation
    %d = Decimal, w/out trailing zeros
    %g = General (%f or %e, whichever is shorter)
    %c = Character (one at a time)
    %s = String

    If you want to print the percent sign, you need to use a double percent: %%

    Try these simple examples:

    nbirds = 5;

    str1 = sprintf('There are %d birds in the park.', nbirds)

    fprintf('There are %d birds in the park.\n', nbirds)

    You can output more than one variable in a single line of code. Try this example:

    ncrows = 2;

    nrobins = 4;

    nseagulls = 8;

    str2 = sprintf('There are %d crows, %d robins, and %d sea gulls in the park.\n', ncrows, nrobins, nseagulls )

    fprintf('There are %d crows, %d robins, and %d sea gulls in the park.\n', ncrows, nrobins, nseagulls )

    Note that in each case, there is just 1 message string which has 3 format codes.

    sprintf and fprintf() are functions with multiple inputs.

    The first of input of sprintf is the message character string, including any format codes. This is followed by any number inputs.

    When printing to the screen, the first input of fprintf is also the message character string, including any format codes. This is followed by any number inputs.

    In the following, the uses of fprintf() can be changed to sprintf() by adding a variable to store the result.

    Example \(\PageIndex{1}\) fprintf of 1000*pi with multiple formats

    Run these lines of code:

    fprintf('%%f format: 1000*pi = %f \n', 1000*pi)
    fprintf('%%e format: 1000*pi = %e \n', 1000*pi)
    fprintf('%%g format: 1000*pi = %g \n', 1000*pi)

    They should produce the output lines shown in the solution:

    Solution

    %f format: 1000*pi = 3141.592654
    %e format: 1000*pi = 3.141593e+03
    %g format: 1000*pi = 3141.59

    .

    Exercise \(\PageIndex{1}\) fprintf() of the speed of light

    Write code similar to the above example that prints the speed of light with the same 3 formats as above.

    Start by setting this variable:

    c = 2.998e8 % Speed of light in a vacuum

    The first fprintf statement should be:

    fprintf('%%f format: c = %f \n', c)

    Also, print c with the %e and % g formats, as in the example above.

    Answer

    The answer is not given here.

    .

    A single fprintf() statement can print more than one variable. It can also have a combination of words and numbers, as shown in this example:

    Example \(\PageIndex{2}\) fprintf() with both words and numbers

    % Example fprintf() with both words and numbers 
    % https://en.wikipedia.org/wiki/Denise_Curry#UCLA_statistics
    name1 = 'Denise'
    name2 = 'Curry'
    points = 3198
    FG_pct = 60.7 %
    fprintf('UCLA Star %s %s scored %4.1f%% of her shots with a 4-year total of %d points\n', ...
             name1, name2, FG_pct, points)

    Solution

    Output:

    UCLA Star Denise Curry scored 60.7% of her shots with a 4-year total of 3198 points

    .

    Exercise \(\PageIndex{2}\) fprintf() mean and standard deviation, simple formatting

    Compute these variables:

    data1 = 3*(rand(1,10) - 0.5);
    data1_mean = mean(data1);
    data1_std = std(data1);

    A. Use fprintf, a %f format string, and the computed value of data1_mean to print a message like this:
    data1 mean = 0.531842, where the printed number will be your value of data1_mean.

    B. Use fprintf, 2 %f format strings, and the computed values of data1_mean and data1_std to print a message like this:

    data1 mean = 0.531842, data1_std= 1.027824

    where the printed numbers will be your values of data1_mean and data1_std.

    Answer

    The answer is not given here.

    .

    sprintf() and fprintf() specifying the number of digits

    The format strings can also specify the number of total digits and decimal places.

    format string %8.2f means: 8 total characters, 2 decimal places, floating point format

    The 8 total characters include a negative sign, if appropriate, and the decimal point, in addition to the digits before and after the decimal point. For numbers in scientific notation, it also needs to include characters for the "e", and exponent sign, and 2 exponent digits.

    The total characters value should be at least the number of decimal places + 3 for the decimal point, a negative sign, and at least one leading digit.

    Example \(\PageIndex{2}\) Specify total number of characters and decimal places

    Try these lines of code:

    fprintf(' %%8.2f format: pi =%8.2f \n', pi)
    fprintf('%%11.8f format: pi =%11.8f \n', pi)
    fprintf(' %%9.2g format: pi =%9.2g \n', pi)
    fprintf(' %%9.2e format: pi =%9.2e \n', pi)
    fprintf('%%10.2e format: pi =%10.2e \n', pi)

    Solution

    %8.2f format: pi = 3.14
    %11.8f format: pi = 3.14159265
    %9.2g format: pi = 3.1
    %9.2e format: pi = 3.14e+00
    %10.2e format: pi = 3.14e+00

    .

    Exercise \(\PageIndex{3}\) fprintf() mean and standard deviation, specify digits

    Compute these variables:

    data1 = 10*randn(1,10)
    data1_mean = mean(data1);
    data1_std = std(data1);

    Use fprintf to print to the screen the computed value of data1_mean with 6 total characters and 3 decimal places, and the computed value of data1_std with 5 total characters and 2 decimal places. The result should look similar to this, but with your values:

    data1 mean = 0.532, data1_std= 1.03

    Answer

    Hint: Your format string should include these 2 formats:  %6.3f and %6.2f

    .

    Exercise \(\PageIndex{4}\) Mimic dice rolls

    x = randi(6,1,36); % Create a vector with uniform random integers between 0 and 6.

    2. Compute the mean and standard deviation of the vector.

    3. Display the mean and standard deviation values to the screen using fprint( ) with a %f format code (with 2 decimal places) to create a string like:

    “The mean= x.xx, and the std. dev.= y.yy”

    where x.xx and y.yy will be replaced with your values.

    Hint: a number like 1.34 needs 4 characters, so use %4.2f

    You need to use 2 proper %f format strings. No credit if you you just type in the values.

    4. Make a similar output using disp( ) and num2str( ) functions with a single disp() function.

    No credit if you you just type in the values.

    This video explains how to display a number with the disp() command:

    Creating formatted outputs using the disp() command in MATLAB. (Links to an external site.)

    Hint: num2str() lets you specify the number of significant digits, as opposed to the number of decimal places. Since both the mean and the standard deviation are between 1 and 10, we want 3 significant digits to get 2 decimal places. So, you can use num2str(std_x, 3)

    Answer

    The answer is not given here.

    .

    fprintf() with a Matrix

    One way to print the values of a matrix is to use nested for loops and print one value at a time. With this approach, you would only use the \n for the last element of a row.

    However, fprintf() can print all of the values with a single instruction. If your message has a single format string, they will be printed as a column. If you have more than one format string, it will print as many values as there are format strings, then cycle back to the beginning of the format string to continue printing the remaining characters. This can result in printing the transpose of a square matrix. Consider this example of a square matrix.:

    S = [1 2 3;
    4 5 6;
    7 8 9];

    % Since there are 3 elements in each row, we try 3 %d format strings.

    fprintf('%d %d %d\n',S)
    % Result:
    % 1 4 7
    % 2 5 8
    % 3 6 9
    We see that it read the 3 values in the first column, but printed them in the first row. The printed matrix is the transpose of matrix S.

    % This can be fixed by putting the transpose, S' in the fprintf statement:
    fprintf('%d %d %d\n',S')
    % Result is correct:
    % 1 2 3
    % 4 5 6
    % 7 8 9

    Consider this 2x4 matrix:

    A = [ 1 2 3 4
    5 6 7 8]

    % Since there are 4 elements in each row, we try 4 %d format strings.

    fprintf('%d %d %d %d\n', A)

    % Result:
    % 1 5 2 6
    % 3 7 4 8

    We see that it read the 2 values in the first column and then the 2 values in the second column and printed them in the first row. This is scrambled.
    % This can be fixed by putting the transpose, A' in the fprintf statement:
    fprintf('%d %d %d %d\n', A')
    % Result:
    % 1 2 3 4
    % 5 6 7 8
    .

    Exercise \(\PageIndex{5}\) fprintf 4x4 magic square

    M4 = magic(4)
    % 16 2 3 13
    % 5 11 10 8
    % 9 7 6 12
    % 4 14 15 1
    % Use fprintf() to print this matrix to the screen. Use 4 %d format strings and \n (newline) in the message argument. Use M4' for the numerical data.

    Answer

    Submit your code.

    .


    This page titled 13.1: sprintf() and fprintf() Part 1 is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Carey Smith.