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
.