Export Data via fprintf printing something else besides NaN

Hi, I have a simple export loop that is writing the contents of a matrix to a text file for another system to read. The issue is that the other system doesn't like NaN as part of a numeric array and I need to print a blank space instead. How can I go about doing this?
On occasion my MacroData matrix Contains NaN's. Is there a way for me to do a find replace while I'm in the file itself, or simple replace the NaN output with a blank?
f_format = '%s%f%f\r\n';
count = 1;
for i = 1:length(UniqueDates)
fprintf(ftemp,f_format,datestr(UniqueDates(i,1),'mm/dd/yyyy'),MacroData(i,:));
end
fclose(ftemp);
Thanks a lot, Brian

 채택된 답변

Titus Edelhofer
Titus Edelhofer 2013년 11월 25일
Hi,
a simple solution would be to print first into a string, process the string and then dump to the file, something like
for i = 1:length(UniqueDates)
str = sprintf(f_format,datestr(UniqueDates(i,1),'mm/dd/yyyy'),MacroData(i,:));
str = strrep(str, 'NaN', ' ');
fprintf(f_temp, '%s', str);
end
Titus

댓글 수: 3

Works perfect thanks Titus. I had never used sprintf before so I really wasn't certain of it's use.
Thanks again, Brian
John
John 2026년 3월 18일 15:38
편집: John 2026년 3월 18일 15:44
I realize this is an old thread, but I'll comment here as it seems topical.
I found myself needing to do something, similar but not exactly the same. Essentially I am trying to write out a Matlab array, and automatically generating a c/c++ declaration for the array. But the special floating-point values (i.e., NaN and Inf) are transcribed differently between C/C++ (NAN/INFINITY) and Matlab(NaN/Inf). It would be nice to have some control over the way in which sprintf/fprintf converts these values to text. At present I could do:
  • Use strrep as suggested by Titus above (functional but cumbersome, depending on complexity of exported declarations)
  • Add "#define NaN (NAN)" to the output file (inelegant and a potential source of conflicts).
  • define a variation of fprintf to encapsulate the replacements
Is there any other way to directly adjust how fprintf handles transcription of the special values?
"Is there any other way to directly adjust how fprintf handles transcription of the special values?"
fprintf() has no configurability. Everything is controlled by the conversion flags, and there are no conversion flags that affect special values.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2013년 11월 25일

댓글:

2026년 3월 18일 19:21

Community Treasure Hunt

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

Start Hunting!

Translated by