0
votes

I am doing some data analysis using Matlab and working with txt files. I have some data of a matrix saved in a text file for example:

1.0,1.1,1.2,1.3

1.4,1.5,1.6,1.7

1.8,1.9,2.0,2.1

3.3,3.0,4.0,5.0

and I am using csvread/dlmread to read the data into Matlab as a matrix. Then I am using csvwrite/dlmwrite to write the data to a separate txt file as comma separated values.

The problem is when I write the matrix to another file, if the last digit of a value is a zero, it gets eliminated. I got the following data in the new file instead of the original matrix.

1,1.1,1.2,1.3

1.4,1.5,1.6,1.7

1.8,1.9,2,2.1

3.3,3,4,5

I am kind of losing precision. Is there a way to tell Matlab to keep exactly the same data as the original?

1

1 Answers

2
votes

That's pretty easy. dlmwrite has a 'precision' flag that you can use to specify how many digits of precision you want for the output file. If we are assuming that your data consists of just a single digit of precision, you can do the following, assuming your matrix is stored in M and that your values are exactly like what we see in your sample data and you want to write to a file called output.txt:

dlmwrite('output.txt', M, 'precision', '%.1f');

This will print out each number with a single digit of precision. The format specifier %.1f means to print out a floating point representation of your number to a single digit of precision. If you omit .1 and just do %f, the default is 5 digits of precision.

As a reproducible example, I've placed your data into a file called testdata.txt, then resaved it using dlmwrite like I did before:

>> in = dlmread('testdata.txt');
>> in
in =

    1.0000    1.1000    1.2000    1.3000
    1.4000    1.5000    1.6000    1.7000
    1.8000    1.9000    2.0000    2.1000
    3.3000    3.0000    4.0000    5.0000
>> dlmwrite('output.txt', in, 'precision', '%.1f');

... and this is what I get for the output in the file:

1.0,1.1,1.2,1.3
1.4,1.5,1.6,1.7
1.8,1.9,2.0,2.1
3.3,3.0,4.0,5.0

FWIW, you're not "losing any precision". 3 and 3.0 are pretty much the same number... what you're more concerned about is formatting preference, not precision. If you re-read that output file that truncates the decimal places for whole numbers back into MATLAB, you would see that it's still interpreting those numbers that truncate out the trailing zeroes as valid floating point numbers... i.e. 3 --> 3.0.