Matlab fwrite精度转换

Matlab fwrite precision conversion

我想以 single 的精度将一些数据写入二进制文件。数据最初是 double 精度。通过在 fwrite 之前调用 single 命令将数据转换为 single 和让 Matlab 在 fwrite 调用中进行转换之间有什么区别吗?

案例一

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

案例二

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

在第二种情况下,Matlab 是否在写入 data2 之前对其进行了任何修改,因为它已经是 single 格式?写入两个文件的数据会有什么不同吗?

您应该使用formatSpec来指定格式:

像这样

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

让我们试试这个:

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

针对您的问题:

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

我不这么认为,但如果不知道 fwrite 的幕后情况,我就无法自信。

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

根据上面的测试我不相信,