increasing precison using fprintf for text file
조회 수: 1 (최근 30일)
이전 댓글 표시
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
2015년 4월 23일
편집: 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
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
Star Strider
2015년 4월 23일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!