Documentation

fprintf

Write data to text file

Syntax

  • fprintf(fileID,formatSpec,A1,...,An) example
  • fprintf(formatSpec,A1,...,An) example

Description

example

fprintf(fileID,formatSpec,A1,...,An) applies the formatSpec to all elements of arrays A1,...An in column order, and writes the data to a text file. fprintf uses the encoding scheme specified in the call to fopen.

example

fprintf(formatSpec,A1,...,An) formats data and displays the results on the screen.

example

nbytes = fprintf(___) returns the number of bytes that fprintf writes, using any of the input arguments in the preceding syntaxes.

Examples

collapse all

Print Literal Text and Array Values

Print multiple numeric values and literal text to the screen.

A1 = [9.9, 9900];
A2 = [8.8,  7.7 ; ...
      8800, 7700];
formatSpec = 'X is %4.2f meters or %8.3f mm\n';
fprintf(formatSpec,A1,A2)
X is 9.90 meters or 9900.000 mm
X is 8.80 meters or 8800.000 mm
X is 7.70 meters or 7700.000 mm

%4.2f in the formatSpec input specifies that the first value in each line of output is a floating-point number with a field width of four digits, including two digits after the decimal point. %8.3f in the formatSpec input specifies that the second value in each line of output is a floating-point number with a field width of eight digits, including three digits after the decimal point. \n is a control character that starts a new line.

Print Double-Precision Values as Integers

Explicitly convert double-precision values with fractions to integer values.

a = [1.02, 3.04, 5.06];
fprintf('%d\n',round(a));
1
3
5

%d in the formatSpec input prints each value in the vector, round(a), as a signed integer. \n is a control character that starts a new line.

Write Tabular Data to Text File

Write a short table of the exponential function to a text file called exp.txt.

x = 0:.1:1;
A = [x; exp(x)];

fileID = fopen('exp.txt','w');
fprintf(fileID,'%6s %12s\n','x','exp(x)');
fprintf(fileID,'%6.2f %12.8f\n',A);
fclose(fileID);

The first call to fprintf prints header text x and exp(x), and the second call prints the values from variable A.

If you plan to read the file with Microsoft® Notepad, use '\r\n' instead of '\n' to move to a new line. For example, replace the calls to fprintf with the following:

fprintf(fileID,'%6s %12s\r\n','x','exp(x)');
fprintf(fileID,'%6.2f %12.8f\r\n',A);

MATLAB® import functions, all UNIX® applications, and Microsoft Word and WordPad recognize '\n' as a newline indicator.

View the contents of the file with the type command.

type exp.txt
     x       exp(x)
  0.00   1.00000000
  0.10   1.10517092
  0.20   1.22140276
  0.30   1.34985881
  0.40   1.49182470
  0.50   1.64872127
  0.60   1.82211880
  0.70   2.01375271
  0.80   2.22554093
  0.90   2.45960311
  1.00   2.71828183

Get Number of Bytes Written to File

Write data to a file and return the number of bytes written.

Write an array of data, A, to a file and get the number of bytes that fprintf writes.

A = magic(4);

fileID = fopen('myfile.txt','w');
nbytes = fprintf(fileID,'%5d %5d %5d %5d\n',A)
nbytes =

    96

The fprintf function wrote 96 bytes to the file.

Close the file.

fclose(fileID);

View the contents of the file with the type command.

type('myfile.txt')
   16     5     9     4
    2    11     7    14
    3    10     6    15
   13     8    12     1

Display Hyperlinks in Command Window

Display a hyperlink (The MathWorks Web Site) on the screen.

site = 'http://www.mathworks.com';
title = 'The MathWorks Web Site';

fprintf('<a href = "%s">%s</a>\n',site,title)

%s in the formatSpec input indicates that the values of the variables site and title, should be printed as strings.

Related Examples

Input Arguments

collapse all

fileID — File identifier1 (default) | 2 | scalar

File identifier, specified as one of the following:

  • A file identifier obtained from fopen.

  • 1 for standard output (the screen).

  • 2 for standard error.

Data Types: double

formatSpec — Format of output fieldsstring containing formatting operators

Format of the output fields, specified as a string containing formatting operators. formatSpec also can include ordinary text and special characters.

Formatting Operator

A formatting operator starts with a percent sign, %, and ends with a conversion character. The conversion character is required. Optionally, you can specify identifier, flags, field width, precision, and subtype operators between % and the conversion character. (Spaces are invalid between operators and are shown here only for readability).

Conversion Character

This table shows conversion characters to format numeric and character data as strings.

Value TypeConversionDetails

Integer, signed

%d or %i

Base 10

Integer, unsigned

%u

Base 10

%o

Base 8 (octal)

%x

Base 16 (hexadecimal), lowercase letters af

%X

Same as %x, uppercase letters AF

Floating-point number

%f

Fixed-point notation (Use a precision operator to specify the number of digits after the decimal point.)

%e

Exponential notation, such as 3.141593e+00 (Use a precision operator to specify the number of digits after the decimal point.)

%E

Same as %e, but uppercase, such as 3.141593E+00 (Use a precision operator to specify the number of digits after the decimal point.)

%g

The more compact of %e or %f, with no trailing zeros (Use a precision operator to specify the number of significant digits.)

%G

The more compact of %E or %f, with no trailing zeros (Use a precision operator to specify the number of significant digits.)

Characters

%c

Single character

%s

String of characters

Optional Operators

The optional identifier, flags, field width, precision, and subtype operators further define the format of the output string.

  • Identifier

    Order for processing values from the input list. Use the syntax n$, where n represents the position of the value in the input list.

    Example: '%3$s %2$s %1$s %2$s' prints inputs 'A', 'B', 'C' as follows: C B A B.

  • Flags

    '–'

    Left-justify.
    Example: %-5.2f

    '+'

    Always print a sign character (+ or –) for any value.
    Example: %+5.2f

    ' '

    Insert a space before the value.
    Example: % 5.2f

    '0'

    Pad to field width with zeros before the value.
    Example: %05.2f

    '#'

    Modify selected numeric conversions:

    • For %o, %x, or %X, print 0, 0x, or 0X prefix.

    • For %f, %e, or %E, print decimal point even when precision is 0.

    • For %g or %G, do not remove trailing zeros or decimal point.

    Example: %#5.0f

  • Field Width

    Minimum number of characters to print. The field width operator can be a number, or an asterisk (*) to refer to an argument in the input list.

    Example: The input list ('%12d',intmax) is equivalent to ('%*d', 12, intmax).

    The function pads to field width with spaces before the value unless otherwise specified by flags.

  • Precision

    For %f, %e, or %E

    Number of digits to the right of the decimal point
    Example: '%.4f' prints pi as '3.1416'

    For %g or %G

    Number of significant digits
    Example: '%.4g' prints pi as ' 3.142'

    The precision operator can be a number, or an asterisk (*) to refer to an argument in the input list.

    Example: The input list ('%6.4f', pi) is equivalent to ('%*.*f', 6, 4, pi).

      Note:   If you specify a precision operator for floating-point values that exceeds the precision of the input numeric data type, the results might not match the input values to the precision you specified. The result depends on your computer hardware and operating system.

  • Subtypes

    Certain conversion characters can support a subtype. The subtype operator immediately precedes the conversion character. This table shows the conversions that can use subtypes.

    Input Value Type

    Subtype and Conversion Character

    Output Value Type

    Floating-point number

    %bx or %bX
    %bo
    %bu

    Double-precision hexadecimal, octal, or decimal value
    Example: %bx prints pi as 400921fb54442d18

    %tx or %tX
    %to
    %tu

    Single-precision hexadecimal, octal, or decimal value
    Example: %tx prints pi as 40490fdb

    Integer

    %ld or %li
    %lo
    %lu
    %lx or %lX

    64-bit value

    Integer

    %hd or %hi
    %ho
    %hu
    %hx or %hX

    16-bit value

Text Before or After Formatting Operators

formatSpec can also include additional text before a percent sign, %, or after a conversion character. The text can be:

  • Ordinary text to print.

  • Special characters that you cannot enter as ordinary text. This table shows how to represent special characters in formatSpec.

    Special Character

    Representation

    Single quotation mark

    ''

    Percent character

    %%

    Backslash

    \\

    Alarm

    \a

    Backspace

    \b

    Form feed

    \f

    New line

    \n

    Carriage return

    \r

    Horizontal tab

    \t

    Vertical tab

    \v

    Character whose ASCII code is the hexadecimal number, N

    \xN

    Character whose ASCII code is the octal number, N

    \N

Notable Behavior of Conversions with Formatting Operators

  • Numeric conversions print only the real component of complex numbers.

  • If you specify a conversion that does not fit the data, such as a string conversion for a numeric value, MATLAB overrides the specified conversion, and uses %e.

    Example: '%s' converts pi to 3.141593e+00.

  • If you apply a string conversion (%s) to integer values, MATLAB converts values that correspond to valid character codes to characters.

    Example: '%s' converts [65 66 67] to ABC.

A1,...,An — Numeric or character arraysscalar | vector | matrix | multidimensional array

Numeric or character arrays, specified as a scalar, vector, matrix, or multidimensional array.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char

Output Arguments

collapse all

nbytes — Number of bytesscalar

Number of bytes that fprintf writes, returned as a scalar. When writing to a file, nbytes is determined by the character encoding. When printing data to the screen, nbytes is the number of characters displayed on the screen.

More About

collapse all

Tips

  • Format specifiers for the reading functions sscanf and fscanf differ from the formats for the writing functions sprintf and fprintf. The reading functions do not support a precision field. The width field specifies a minimum for writing but a maximum for reading.

References

[1] Kernighan, B. W., and D. M. Ritchie, The C Programming Language, Second Edition, Prentice-Hall, Inc., 1988.

[2] ANSI specification X3.159-1989: "Programming Language C," ANSI, 1430 Broadway, New York, NY 10018.

See Also

| | | | | | | | |

Introduced before R2006a

Was this topic helpful?