Preserving decimal places when exporting data

9 次查看(过去 30 天)
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!

回答(1 个)

Star Strider
Star Strider 2016-4-17
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 个评论
Image Analyst
Image Analyst 2016-4-17
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 2016-4-17
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Workspace Variables and MAT-Files 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by