How to read in binary file data as something other than double datatype?

4 views (last 30 days)
I am trying to read in data from a binary file using the fread function (see example below). No matter what precision I specify, the output is always of the datatype 'double'. I want the output to be int16 datatype. I do not want to simply convert the output from a double to int16 - the reason I want to read in the data as int16 is to minimize memory usage. I'm using MATLAB 2020a
fileID = fopen('nine.bin','w');
fwrite(fileID,[1:9],'int16');
fclose(fileID);
fileID = fopen('nine.bin');
A = fread(fileID,[3,2],'int16') %A comes out as 'double' datatype here. I need int16

Accepted Answer

Steven Lord
Steven Lord on 1 Sep 2020
From the description of the precision input on the documentation page for the fread function, specifying the precision as *source means "The input values and the output matrix, A, are of the class specified by source."
A = fread(fileID, [3 2], '*int16');
  2 Comments
Scott Kilianski
Scott Kilianski on 1 Sep 2020
Ahhhhh, simple as that. I should've given it a closer read. Thank you very much Steven.
Scott Kilianski
Scott Kilianski on 1 Sep 2020
Just an update on this. I am also skipping some data when reading it in which means I need to use the N*source syntax (where N is the number of values before skipping occurs). This prevents me from simply using the following:
A = fread(fileID,[3,2],'2*int16') %using '2*int16' as the precision reads in 2 values from
%the binary file, and A becomes a double datatype again
Instead, I use:
A = fread(fileID, [3 2], '2*int16=>int16'); %=> specifies the that the output should be 'int16'

Sign in to comment.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!