MATLAB Programming/Inserting Newlines into Disp Warn and Error

The functions warning, error, sprintf and fprintf will interpret '\n' as a newline character. For example

>> error('This error\nhas a newline.')
??? This error
has a newline.

Though previous versions of this wiki claimed this functionality was introduced in MATLAB 6.5 (R13), it doesn't work in 7.4.0 (2007a). The explanation that this change happened when formatted error strings were introduced in the Release Notes for that release was unhelpful.

To add a newline character in versions where the above example doesn't work, use SPRINTF or CHAR(10):

>> error(sprintf('This error\nhas a newline.'))
??? This error
has a newline.
>> disp(['abcd' char(10) 'efgh'])
abcd
efgh

This works as well:

>> disp(['abcd', 10,  'efgh'])
abcd
efgh

In MATLAB versions 2016b and newer the function NEWLINE is recommended instead, for code clarity

>> disp(['abcd' newline 'efgh'])
abcd
efgh