How can I read a binary file containing records with multiple formats in MATLAB 7.9 (R2009b)?

6 views (last 30 days)
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.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 3 Dec 2009
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);

More Answers (0)

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Products


Release

R2009b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!