MATLAB: Sprintf format specifiers won’t print newline

emptyformat specifierformatspecfprintfnewlinesprintfstring

I'm trying to create a string that has a newline in it. My problem is with sprintf. I'm trying to put a newline (\n) character in my string, and it's behaviour is very strange… sometimes sprintf returns an empty string, and sometimes it just prints '\n' as part of the text. I want it to actually insert a line.
This is sort of what my string looks like, but with some variables inserted between the angle brackets:
entry = '% * < >\n';
I tried going straight ahead with sprintf:
sprintf(entry)
This produces
Empty string: 1-by-0
I tried accounting for the newline:
sprintf('\n', entry)
This seems to produce just a newline. I then thought maybe the percent sign was special, so I tried the 'escape character' syntax which is mentioned on the sprintf reference page but not really explained:
sprintf('%%', entry)
This produces just a percent sign. Next I tried using the string specifier %s. I found that
sprintf('%s', entry)
produced
% * < >\n
and that
sprintf('%s\n', entry)
produced the same thing but with a newline after the string, but not where my actually '\n' is. Whenever I add '%%' in there, it just prints out a percent sign. Can anyone tell me what I'm doing wrong? This is puzzling because simply doing sprintf(string) works for me with other strings that have newlines in them.

Best Answer

It turns out that '%' needs to be written as '%%' in the string (thank you Honglei Chen), and that was somehow interfering with my newline working as well. In the end I used
entry = sprintf('%%* < >\n');
which produces
% * < >
plus a newline. If you use '%s', I guess it interprets every character as itself:
entry = sprintf('%s', '%%* < >\n');
ans =
%%* < >\n