Preserving decimal places when exporting data

5 ビュー (過去 30 日間)
S.K.
S.K. 2016 年 4 月 17 日
コメント済み: Star Strider 2016 年 4 月 17 日
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 Center および File ExchangeLow-Level File I/O についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by