MATLAB: How to export data from MatLab to a .txt file without loosing precision

matlab precision txt export data computations

Hello. I would like to know how can export data from MatLab to a .txt file without loosing precision. I would like to export this data so I can do some computations using a C++ code I have. I've done some research, and I have found out that MatLab's double type (default type) has around 16 decimal digits of precision. Here is the code I've written:
x = rand(4,1);
file = fopen('file.txt', 'w');
fprintf(file, '%.15f\n', x);
fclose(file);
I would like to know if this code is correct or if there is something I can improve. Thank you very much for your help!

Best Answer

Not only Matlab's double type uses about 16 digits, but this is the IEEE754 standard, which is available in all numerical software and usual processors. Besides Walter's suggestion to use '%.16g', which is more suitable e.g. for pi*1e14, the conversion to the decimal number as an ASCII file must reduce the precision. Example:
a = pi * 1e16;
fid = fopen('test.txt', 'w');
fprintf(fid, '%.16g', a);
fclose(fid);
fid = fopen('test.txt', 'r');
b = fscanf(fid, '%g');
fclose(fid);
a - b
>> 4
The conversion from the binary double format to the decimal text format includes a certain loss of precision already. When you want to deliver the values accurately, store them in binary format:
fid = fopen('test.bin', 'w');
fwrite(fid, a, 'double);
fclose(fid);
fid = fopen('test.bin', 'r');
b = fread(fid, 1, 'double);
fclose(fid);
a - b
>> 0
You can read the binary format from the C++ function also. And the import is faster than the conversion from the string.