60
Exporting to Text Data Files
use the low-level
fprintf
function. For more information, see the following
sections:
• “Opening the File” on page 3-13
• “Describing the Output” on page 3-13
• “Appending or Overwriting Existing Files” on page 3-15
• “Opening Files with Different Character Encodings” on page 3-18
Note
fprintf
is based on its namesake in the ANSI Standard C Library.
However, MATLAB uses a vectorized version of
fprintf
that writes data from
an array with minimal control loops.
Opening the File
As with any of the low-level I/O functions, before exporting, open or create
afile with
fopen
,and obtain a file identifier. By default,
fopen
opens a file
for read-only access, so you must specify the permission to write or append,
such as
'w'
or
'a'
.
When you finish processing the file, close it with
fclose(fid)
.
Describing the Output
fprintf
accepts arrays as inputs, and converts the numbers or characters in
the arrays to text according to your specifications.
For example, to print floating-point numbers, specify
'%f'
.Other common
conversion specifiers include
'%d'
for integers or
'%s'
for strings. For a
complete list of conversion specifiers, see the
fprintf
reference page.
To move to a new line in the file, use
'\n'
.
Note Some Windows text editors, including Microsoft Notepad, require
anewline character sequence of
'\r\n'
instead of
'\n'
. However,
'\n'
is
sufficient for Microsoft Word or WordPad.
3-13