Matlab fwrite precision conversion

Viewed 169

I want to write some data to a binary file in single precision. The data is originally in double precision. Is there any difference between converting the data to single by calling the single command before fwrite and just letting Matlab do the conversion in the fwrite call?

Case 1

data1 % double precision
fwrite(fid,data1,'single');

Case 2

data2=single(data1);
fwrite(fid,data2,'single');

In the 2nd case, is Matlab doing any modifications to data2 before writing it since it is already in single format ? Will there be any difference in data written to the two files ?

2 Answers

You should use formatSpec to specify the format:

enter image description here

Like this

A = [6.6,1.11111];
formatSpec = '%4.5f'; % modify it accordingly.
fprintf(formatSpec ,A);

Let's try this:

data1 = 1.555555555555555555;
data2 = single(data1);

fid = fopen('C:\Some\Address\data1.bin', 'w');
fwrite(fid, data1, 'single');
fclose(fid);

fid = fopen('C:\Some\Address\data2.bin', 'w');
fwrite(fid, data2, 'single');
fclose(fid);

% Lets read them back (note that MATLAB stores them in a double-precision variable by default)
fid = fopen('C:\Some\Address\data1.bin', 'r');
data1 = fread(fid, 'single');
fclose(fid);
fid = fopen('C:\Some\Address\data2.bin', 'r');
data2 = fread(fid, 'single');
fclose(fid);

format long;
[data1 data2] % or use fprintf to see the values

ans =

   1.555555582046509   1.555555582046509

To your questions:

In the 2nd case, is Matlab doing any modifications to data2 before writing it since it is already in single format ?

I don't think so but cannot be confident without knowing what is going on under the hood of fwrite.

Will there be any difference in data written to the two files ?

According to the test above I don't believe so,

Related