MATLAB: How to read a binary file containing records with multiple formats in MATLAB 7.9 (R2009b)

binarybitsbytecharacterfloatingintegerMATLABpointstring

I have a binary file that contains records with varying formats. I would like to be able to specify the format of the records in a single call to FREAD, and have it return the correctly formated values.
For example, I might have a record that consists of a 16-bit integer and a 32-bit float created as follows:
% Create binary file with 16-bit integers and floats
fid = fopen('mybytestream','w');
intstowrite = [50 100 150];
floatstowrite = [111.2984 222.4589 333.4985];
for k = 1:length(intstowrite)
fwrite(fid,intstowrite(k),'int16');
fwrite(fid,floatstowrite(k),'float');
end
fclose(fid);
I'd like to read the file as follows:
fid = fopen('mybytestream');
out = fread(fid,inf,'int16+float');
fclose(fid);
where 'int16+float' is a format string specifying that the first 2 bytes are int16 and the next 4 bytes are float.

Best Answer

FREAD supports a single format string. To interpret a file with multiple formats, read the first format type, rewind to the beginning of the file, and then read the second format type. Use the 'Skip' parameter to skip the format that is not being read. As an example:
% Read the file first looking for int16 and then looking for floats
fid = fopen('mybytestream');
intreads = fread(fid,inf,'int16',4); %Read 2 bytes of int16, then skip 4 bytes
fseek(fid,2,'bof'); %Return to 2 bytes after Beginning Of File
floatreads = fread(fid,inf,'float',2); %Read 4 bytes of float, then skip 2 bytes
fclose(fid);