MATLAB: Extract very small numbers from a .DAT file with all its decimals and export them to an excel file

data exportdecimalsfile extraction

Hello everybody,
I'm very desperate already since I've been browsing through the community for days without finding a solution for my problem.
I want to only import the marked numbers (see attached png) from a .dat file (which I can't upload here). This means I need to get rid of the 16 headlines before the data and the first column of the data. The second column (red framed on png) is supposed to be turned into a cell array containing the numbers with all its decimals and export it to an excel spreadsheet.
The main problem I have is that matlab rounds a number like -3.999999999999999819e-06 to -4.000000…e-06 instead of keeping all its decimals. Find the code I've been using so far in the attached .m file.
I would appreciate a lot if you guys could help me out with the coding. I am not experienced but I need to automize this data extraction.
Thanks a lot!
Cheers,
Sven

Best Answer

This issue is related to the finite precision of how the floating-point numbers are represented in computers. The double type in MATLAB can only hold numbers to 16 decimal places. Anything beyond that is theoretically impossible to store in a double variable accurately. In such a case, you can use variable precision arithmetic. Note that this can be many times slowers as compared to the numeric datatype, but if you want this level of accuracy, then variable precision is the only solution.
file = fopen('filename.dat');
data = textscan(file, '%s %s', 'HeaderLines', 16);
fclose(file);
result = vpa(data{2});
Related Question