count = fprintf(fid,'format',A,...)
fprintf('format',A,...)
count = fprintf(fid,'format',A,...)
formats the data in 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
. count
is the integer number of bytes written.
fid
is an integer file identifier obtained from fopen
. It can also be 1 for standard output (the screen) or 2 for standard error. On some computers, fopen
can be used with device names. For example, in an MS-DOS environment, COM1
might be defined as a serial port leading to a modem. In that case, use fopen('COM1')
and fprintf
to send characters to the modem.
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
).
format
is a string containing ordinary characters and/or conversion specifications. Ordinary characters include the normal alphanumeric characters, and escape characters. Escape characters include
------------------ \n new line \t horizontal tab \b backspace \r carriage return \f form feed \ backslash ------------------Conversion specifications involve the character
%
, optional width fields, and conversion characters. Legal conversion characters are
------------------------------------------------------------- %e exponential notation %f fixed point notation %gBetween the%e
or%f
, whichever is shorter; (insignificant zeros do not print) -------------------------------------------------------------
%
and the conversion character (e
, f
, or g)
, you can add one or more of the following characters:
printf()
and fprintf()
routines in a C language reference manual.
fprintf
differs from its C language fprintf()
namesake in an important respect - it is vectorized for the case when input matrix A
is nonscalar. The format string is recycled through the elements of A
(columnwise) until all the elements are used up. It is then recycled in a similar manner, without reinitializing, through any additional matrix arguments.
create a text file calledx = 0:.1:1;
y = [x; exp(x)];
fid = fopen('exp.txt','w');
fprintf(fid,'%6.2f %12.8f\n',y);
fclose(fid)
exp.txt
containing a short table of the exponential function:
The command0.00 1.00000000
0.10 1.10517092
...
1.00 2.71828183
displays a line on the screen:fprintf('A unit
circle
has
circumference %g.\n',2*pi)
A unit circle has circumference 6.283186.
To insert a single quote in a string (the format
command), use two single quotes together. For example,
fprint(1,'It''s Friday\n')
displays the following line on the screen:
It's Friday
The command
displays the lines:B = [8.8 7.7; 8800 7700]
fprintf(1,'X
is %6.2f meters or %8.3f mm\n',9.9,9900,B)
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
fclose
,ferror
,fopen
,fread
,fscanf
,fseek
,ftell
,fwrite
,sprintf
(c) Copyright 1994 by The MathWorks, Inc.