Development Environment    

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

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