increasing precison using fprintf for text file

1 view (last 30 days)
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 Comments
sermet
sermet on 23 Apr 2015
I see but how can I apply this for cellfun?
per isakson
per isakson on 23 Apr 2015
Edited: per isakson on 23 Apr 2015
Replace
@num2str
by
@(str) num2str( str, format_specifier )
or better
>> cellfun( @num2str, {123,34567/3}, {'%d','%18.12f'}, 'uni', false )
ans =
'123' '11522.333333333334'

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 23 Apr 2015
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 Comments
Star Strider
Star Strider on 23 Apr 2015
No worries.
The only change I suggested is to use this assignment for ‘form’:
form = '%5d %23.15E %23.15E %23.15E\n';
Experiment with it to see if it works to your satisfaction.
sermet
sermet on 23 Apr 2015
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!