PROBLEM IN WRITING A text in MATLAB

2 views (last 30 days)
Dear All,
Well I have a text that I have to fprintf it into a text file using my matlab code. But I cannot figure what the output is not what I expect. Is there anything wrong with my code?
Here is the text I need to be written in my output file:
dump_modify 1 format "%5d %5d %25.10g %25.10g %25.10g"
dump_modify 1 sort id
Here is my code:
fprintf(fid,'dump_modify 1 format "%5d %5d %25.10g %25.10g %25.10g" \n\')
fprintf(fid,'dump_modify 1 sort id\n\n')
but the output is something strange!
dump_modify 1 format "dump_modify 1 sort id
Thanks so much for helping me.

Accepted Answer

Walter Roberson
Walter Roberson on 13 Sep 2015
fprintf(fid,'%s\n', 'dump_modify 1 format "%5d %5d %25.10g %25.10g %25.10g"');
fprintf(fid,'%s\n\n', 'dump_modify 1 sort id');
  3 Comments
Homayoon
Homayoon on 13 Sep 2015
what was wrong with mine? can you say that please?
Walter Roberson
Walter Roberson on 13 Sep 2015
When you only supply fid and a string, the string is treated as a format. Your string looks like a format so MATLAB tried to use it like that. It got to the first %, tried to use it as a format specification, found there were no input arguments to go with it, and ended processing the string. Then it proceeded to the next fprintf() call, which did not happen to contain any % format characters so it got processed as-is.
When you code as fprintf(fid, '%s', SomeString) then the SomeThing gets copied in exactly without being processed for format characters, as that is what a %s format specification means, to copy the string exactly.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!