Skip to main content
Library homepage
Engineering LibreTexts

13.2: fprintf() to a file

  • Page ID
  • \( \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 is excerpted from Beyenir, chapter 4, sections 4.1.5, 4.1.6


    The fopen and fclose Functions

    The fopen command is used to open or create a file. The basic syntax for fopen is as follows:
    fid = fopen(filename, permission)

    For example, fo = fopen('output.txt', 'w'); opens or creates a new file named output.txt and sets the permission for writing. If the file already exists, it discards the existing contents.
    The fclose command is used to close a file. For example, if we type in fclose(fo);, we close the file that
    was created above. (It is necessary to close every file that is opened.)


    The fprintf Function

    The fprintf function writes formatted data to the computer monitor or a file. This command can be used to
    save the results of a calculation to a file. To do this,

    • First we create or open an output file with fopen
    • Second we issue the fprintf command
    • Then we close the output file with fclose.

    The simplified syntax for fprintf is as follows:
    fprintf=(fid, format, variable1, variable 2, ...)

    Example \(\PageIndex{1}\) Bottle Volume

    Start a .m file named AcetyleneBottleInteractiveOutput.m with these lines:

    % This script computes the volume of an acetylene bottle

    % user is prompted to enter
    % a radius r for a hemispherical top
    % a height h for a cylindrical part
    clc % Clear screen
    disp('This script computes the volume of an acetylene bottle:')
    disp(' ') % Display blank line

    r=input('Enter the radius of acetylene bottle in meters ');
    h=input('Enter the height of cylindrical part of acetylene bottle in meters ');
    Vol_top=(2*pi*r^3)/3; % Calculating the volume of hemispherical top [m3]
    Vol_cyl=pi*r^2*h; % Calculating the volume of cylindrical bottom [m3]
    Vol_total=Vol_top+Vol_cyl % Calculating the total volume of acetylene bottle [m3]

    disp(' ') % Display blank line
    str = ['The volume of the acetylene bottle is ', num2str(Vol_total), ' cubic meters.'];

    Add the following lines to your .m file, in order to write to a file:
    fo = fopen('output.txt', 'w');
    fprintf(fo,'The radius of acetylene bottle: %g meters \n', r);
    fprintf(fo,'The height of cylindrical part of acetylene bottle: %g meters \n', h);
    fprintf(fo,'The volume of the acetylene bottle: %g cubic meters. \n', Vol_total);

    Here, we first create the output.txt file that will contain the following three variables r, h and Vol_total. In the fo output file, the variables are formated with %g which automatically uses the shortest display format. You can also use %i or %d for integers and %e for scientific notation. In our script above, the \n (newline) moves the cursor to the next line.


    Upon running the .m file, the output.txt file will display the following. The values will depend on the values you input.

    The radius of acetylene bottle: 0.3 meters
    The height of cylindrical part of acetylene bottle: 1.5 meters
    The volume of the acetylene bottle: 0.480664 cubic meters.


    Example \(\PageIndex{2}\) Write a matrix to a file as a formatted table

    By Carey A. Smith

    %% Create a matrix showing the conversion of feet to inches.
    feet = 0:2:10;
    inches= feet*12;
    matrix_feet_inches = [feet' , inches'];

    % Display it on the screen, 2 methods:

    %% Formatted Table with a header, method 1: for loop
    fprintf('\n') % print a blank line
    disp(' Feet Inches')
    disp(' ----- ------')
    [nrows, ncols] = size(matrix_feet_inches);
    for n = 1:nrows
    fprintf('%8.1f %8.2f \n', matrix_feet_inches(n,:))

    %% Formatted Table with a header, method 2: Print the matrix with a single statement
    fprintf('\n') % print a blank line
    disp(' Feet Inches')
    disp(' ----- ------')
    fprintf('%8.1f %8.2f \n', matrix_feet_inches')
    % The transpose is needed, becuz Matalb reads the data down columns
    % but prints across rows.
    % fprintf statment only 2 prints 2 values at a time.
    % The format string is repeated until all of the data is printed.

    %% Write the matrix to a file as a formatted table:
    file_id1 = fopen('Formatted_Table.txt','wt')
    % fopen() opens a file.
    % file_id1 is the file's handle
    % 'r' = read
    % 'w' = write (Create the file, if it doesn't exist)
    % 'a' = append to the end of the file, leaving any existing data
    % 't' = text format
    cnt1= fprintf(file_id1,' Feet Inches\n')
    % cnt1 = the number of characters written each time.
    cnt2= fprintf(file_id1,' ----- ------\n')
    cnt3= fprintf(file_id1, '%8.1f %8.2f \n', feet, inches)
    fclose(file_id1) % Close the file with finished writing


    Add example text here.

    Exercise \(\PageIndex{1}\) fprintf exponential table

    By Carey A. Smith

    Study example in the attached file fprintf_to_file_exponential_table.m

    Then modify the example in these ways:

    1. In parts A & B change the format strings, so that the x column is printed 1 decimal place instead of 2 and change the exp(x) column to be pprinted with 6 decimal places instead of 8.

    2. In part B, write to the table a file with a name like this: 'exp_table1_YourName.txt'


    Add texts here. Do not delete this text first.

    These videos may be of help:


    More information is at:

    This page titled 13.2: fprintf() to a file is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Carey Smith via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.