Programming |
Reading Binary Data
The fread
function reads all or part of a binary file (as specified by a file identifier) and stores it in a matrix. In its simplest form, it reads an entire file and interprets each byte of input as the next element of the matrix. For example, the following code reads the data from a file named nickel.dat
into matrix A
:
To echo the data to the screen after reading it, use char
to display the contents of A
as characters, transposing the data so it is displayed horizontally:
The char
function causes MATLAB to interpret the contents of A
as characters instead of as numbers. Transposing A
displays it in its more natural horizontal format.
Controlling the Number of Values Read
fread
accepts an optional second argument that controls the number of values read (if unspecified, the default is the entire file). For example, this statement reads the first 100 data values of the file specified by fid
into the column vector A
.
Replacing the number 100
with the matrix dimensions [10 10]
reads the same 100 elements into a 10-by-10 array.
Controlling the Data Type of Each Value
An optional third argument to fread
controls the data type of the input. The data type argument controls both the number of bits read for each value and the interpretation of those bits as character, integer, or floating-point values. MATLAB supports a wide range of precisions, which you can specify with MATLAB specific strings or their C or Fortran equivalents.
Some common precisions include
char
'
and 'uchar
'
for signed and unsigned characters (usually 8 bits)
'short'
and 'long'
for short
and long integers (usually 16 and 32 bits, respectively)
'float'
and 'double'
for single- and double-precision floating-point values (usually 32 and 64 bits, respectively)
Note
The meaning of a given precision can vary across different hardware platforms. For example, a 'uchar' is not always 8 bits. fread also provides a number of more specific precisions, such as 'int8' and 'float32' . If in doubt, use precisions that are not platform dependent. See fread for a complete list of precisions.
|
For example, if fid
refers to an open file containing single-precision floating-point values, then the following command reads the next 10 floating-point values into a column vector A
:
Opening Files | Writing Binary Data |
© 1994-2005 The MathWorks, Inc.