| MATLAB Function Reference | Search  Help Desk |
| fprintf | Examples See Also |
Syntax
count = fprintf(fid,format,A,...) fprintf(format,A,...)
Description
count = fprintf(fid,format,A,...)
formats the data in the real part of matrix A (and in any additional matrix arguments) under control of the specified format string, and writes it to the file associated with file identifier fid. fprintf returns a count of the number of bytes written.
Argument fid is an integer file identifier obtained from fopen. (It may also be 1 for standard output (the screen) or 2 for standard error. See fopen for more information.) Omitting fid from fprintf's argument list causes output to appear on the screen, and is the same as writing to standard output (fid = 1).
fprintf(format,A,...)
writes to standard output, the screen.
The format string specifies notation, alignment, significant digits, field width, and other aspects of output format. It can contain ordinary alphanumeric characters, along with escape characters, conversion specifiers, and other characters, organized as shown below.
Remarks
Thefprintf function behaves like its ANSI C language fprintf() namesake with certain exceptions and extensions, including:Escape Characters
Character
Description
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tHorizontal tab
\\Backslash
\'' or ''(two single quotes)Single quotation mark
%%Percent character
Conversion Specifiers
Conversion characters specify the notation of the output.Other Characters
Other characters can be inserted into the conversion specifier between the% and the conversion character.printf() and fprintf() routines in the documents listed in "References".
Examples
The statementsx = 0:.1:1;
y = [x; exp(x)];
fid = fopen('exp.txt','w');
fprintf(fid,'%6.2f %12.8f\n',y);
fclose(fid)
create a text file called exp.txt containing a short table of the exponential function:
0.00 1.00000000 0.10 1.10517092 ... 1.00 2.71828183The command
fprintf('A unit circle has circumference %g.\n',2*pi)
displays a line on the screen:
A unit circle has circumference 6.283186.To insert a single quotation mark in a string, use two single quotation marks together. For example,
displays on the screen:fprintf(1,'It''sFriday.\n')
The commandsIt'sFriday.
B = [8.8 7.7; 8800 7700] fprintf(1,'X is %6.2f meters or %8.3f mm\n',9.9,9900,B)display the lines:
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 mmExplicitly convert MATLAB double-precision variables to integral values for use with an integral conversion specifier. For instance, to convert signed 32-bit data to hexadecimal format:
a = [6 10 14 44];
fprintf('%9X\n',a + (a<0)*2^32)
6
A
E
2C
See Also
fclose, ferror, fopen, fread, fscanf, fseek, ftell, fwrite
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.