Parametrize return arguments in fprintf

1 回表示 (過去 30 日間)
fsgeek
fsgeek 2016 年 2 月 14 日
コメント済み: fsgeek 2016 年 2 月 15 日
Dear all,
I have a line of code which outputs a string to a file:
fprintf(fid, '\r\nSomething\r\n')
I would like to echo this string to the command window, which I achieve with the following:
fprintf(1.0, '\nSomething\n')
However, I don't want to have to write the same fprintf statement twice, so I tried this:
location = [fid, 1.0];
conversion = {'\r\n', '\n'};
for i = 1:2
fprintf(location(i), '%sSomething%s', conversion{i}, conversion{i})
end
The problem is that I see the following in the command window:
\nSomething\n>>
Instead of:
Something
>>
How can I format the string so that '\n' is recognised as a return, rather than a plain string?
Many thanks,
Louis Vallance

採用された回答

Star Strider
Star Strider 2016 年 2 月 14 日
You’re passing the control sequences as strings. You need to concatenate them instead.
This works:
fprintf(location(i), [conversion{i} 'Something' conversion{i}])
  4 件のコメント
Image Analyst
Image Analyst 2016 年 2 月 14 日
Personally, I think, as a non-author of the code, that it would be so much easier to understand and follow the code if you had just called fprintf() twice like you said, instead of doing this more complicated thing.
fsgeek
fsgeek 2016 年 2 月 15 日
Fair point, but I have over 300 of these statements so this solution is much more practical, especially if I want to change any of the strings later. It's also not difficult to understand provided the code is well-commented.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by