increasing precison using fprintf for text file

4 ビュー (過去 30 日間)
sermet
sermet 2015 年 4 月 23 日
編集済み: per isakson 2015 年 4 月 23 日
cellArray =
[ 334] [38.141794059793398] [31.983184186130529] [1.751451095529832e+03]
[ 352] [38.094455446389709] [31.940682658186898] [1.779530219110660e+03]
[ 404] [38.162956465159276] [32.019563510560964] [1.542875077314675e+03]
[ 414] [38.176654734516106] [32.068817577008474] [1.389497182917781e+03]
[ 476] [38.075635175382899] [32.027977260576755] [1.994276513063349e+03]
[2729] [38.229399882994215] [31.934421897750756] [1.167495300253853e+03]
[2730] [38.205404821919039] [31.911611428797361] [1.291408437962644e+03]
[2742] [38.104502101643973] [31.931891003528762] [1.774978352412581e+03]
Name Size Bytes Class Attributes
cellArray 8x4 3840 cell global
% I use below codes to write cellArray into txt file
startingFolder='C:\Program Files\MATLAB';
if ~exist(startingFolder, 'dir');
startingFolder = pwd;
end
defaultFileName=fullfile(startingFolder, '*.txt');
[baseFileName, folder]=uiputfile(defaultFileName, 'Select a file');
if baseFileName == 0
return
end
fullFileName = fullfile(folder, baseFileName);
c=cellfun(@num2str,cellArray,'un',0);
[n,m]=size(c);
form=[repmat('%s ',1,m) ' \r\n'];
fid = fopen(fullFileName, 'w');
for k=1:n
fprintf(fid, form, c{k,:});
end
fclose(fid);
% but data (2-3-4rd columns) are written only 4 numbers after the comma (like, 38.1418). I need to write the data into txt file without rounding.
  3 件のコメント
per isakson
per isakson 2015 年 4 月 23 日
Replace
@num2str
by
@(str) num2str( str, format_specifier )
or better
>> cellfun( @num2str, {123,34567/3}, {'%d','%18.12f'}, 'uni', false )
ans =
'123' '11522.333333333334'

サインインしてコメントする。

採用された回答

Star Strider
Star Strider 2015 年 4 月 23 日
If you need full precision on all numeric variables and want to use repmat to create your ‘form’ format descriptors, instead of %s, I would use %23.15E. That will print all of them out to full precision.
  7 件のコメント
sermet
sermet 2015 年 4 月 23 日
c=cellfun(@num2str,cellArray,'un',0);
[n,m]=size(c);
form = '%5d %23.15E %23.15E %23.15E\n'
fid = fopen(fullFileName, 'w');
for k=1:n
fprintf(fid, form, c{k,:});
end
fclose(fid);
%when I apply these codes as you suggested (if I got it correct), it produces the attached text file.

サインインしてコメントする。

その他の回答 (0 件)

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by