MATLAB: Input of linebreak into sprintf

formatspecfprintflinebreakMATLABsprintf

Hello,
i want to input a linebreak ( via '\n' ) into a string. I mean something like this:
a =sprintf('A%sA', '\n');
%this produces
a =
A\nA
%but i want it to produce
a =
A
A
How would I do that?
/edit: this is a minimal example just to show my point, of course. The case i want to work with has multiple inputs and a more complex formatSpec..

Best Answer

a = sprintf('A\nA')
% Or
a = sprintf('A%cA', char(10)) % %s would work also
% Use |newline| instead of char(10) in modern Matlab versions
Your code is the correct method to insert tha characters '\n' directly:
a = sprintf('A%sA', '\n');
% Equivalent to:
a = sprintf('A\\nA');
This is useful, if a file name is printed with path, because this is not reliable:
sprintf(['File: ', filename, '\n'])
If filename contains a control character as \n, \t, \c or e.g. a %s, the output will be confusing. The same must be considered for warnings and errors:
error(['Failing: ', filename])
A clean way without danger of confusing output:
error('Failing: %s', filename)
Related Question