New lines in matlab, figure legends and elsewhere

Alec Jacobson

November 16, 2011

weblog/

I tried naively to use \n in a matlab string hoping that it would come out as the newline character:
a = 'first\nsecond'
But you just get literally the 2 characters, \ and n in your string.
a =

first\nsecond
You code filter your string through sprintf:
b = sprintf('first\nsecond')
which gives you the newline:
b =

first
second
But this would cause problems if your string happened to contain any of the other sprintf symbols, like %, resulting in missing characters or errors:
sprintf('percentage\n90%')
Puts in the newline but removes the % sign:
ans =

percentage
90
Instead, it's best to use the character code for the new line directly:
c = ['first' char(10) 'second'];
Concatenating strings in matlab is clunky but the newline shows up correctly without any side effects:
c =

first
second
You could easily make a simple replacement function that finds any \n sequences and replaces them with char(10)s with the following:
nl = @(s) strrep(s,'\n',char(10));
Then use your new function nl on your original string with \n to get the newline without worrying about concatenating:
d = nl('first\nsecond');
producing
d =

first
second