Clear Filters
Clear Filters

Preserving decimal places when exporting data

9 views (last 30 days)
S.K.
S.K. on 17 Apr 2016
Commented: Star Strider on 17 Apr 2016
Hello,
I am trying to export a matrix as a text file. One of the columns in the matrix represents time in seconds, but with millisecond resolution, so that that the entries look like 1.001,1.002, ... , 300.271 and so on.
Is there a way to export this data while keeping the number of decimal places (in this case 3) constant? I don't want to have the precision of all columns be some set number, I just want the exported data to have the exact same entries as my file - for some reason this is proving difficult.
Would be very grateful for any solutions you might propose. Thank you!

Answers (1)

Star Strider
Star Strider on 17 Apr 2016
You can create a delimited file with fixed formats for each field easily using fprintf.
I used sprintf here to check the output without actually writing the file. The only change needs to be the function and anything else it requires (such as a fileID number):
Data = [1+[0:10]'*1E-3, rand(11, 3)];
File = sprintf('\t%.3f\t%.5f\t%.2f\t%.9f\n', Data');
You can of course change the delimiter. I used a tab here.
  2 Comments
Image Analyst
Image Analyst on 17 Apr 2016
To be clear, the number of numbers to the right of the decimal point is the number between the %. and the f. So %.5f would give 5 decimal places to the right of the decimal point. If it's 3, there would be 3, and so on.
Star Strider
Star Strider on 17 Apr 2016
Thank you Image Analyst. I definitely should have provided a few more details.
Also, note the transpose (') (specifically Data') in the sprintf call. That is necessary to write a matrix with fprintf and sprintf correctly because of the way those functions use their input arguments. If you used a for loop to print the ‘Data’ matrix line-by-line, that would not be necessary. However, using the loop would be much less efficient than using the transposed matrix for this particular problem.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!