In MATLAB, you go to the next line primarily by including a newline character within your text output or strings. The recommended way to insert a newline character is using the newline
constant.
Based on the reference, c = newline
creates a newline character. The newline
constant is equivalent to char(10)
or the escape sequence \n
used within sprintf
. You insert this character where you want the line break to occur.
Using the newline
Character
The newline
constant is the most readable and platform-independent way to insert a line break in recent MATLAB versions.
Syntax:
Simply use newline
within your string or command.
Examples:
Here are common ways to use newline
or its equivalents:
-
With
disp
: Thedisp
function automatically interprets newline characters.disp(['This is the first line.', newline, 'This is the second line.']);
Output:
This is the first line. This is the second line.
-
With
fprintf
: Thefprintf
function is often used for formatted output to the Command Window or files. You can use the%s
format specifier withnewline
or directly use the\n
escape sequence.fprintf('First line here.%sSecond line starts.\n', newline); fprintf('Another way using just \\n.\nThird line.\n');
Output:
First line here. Second line starts. Another way using just \n. Third line.
Note:
\n
inside single quotes' '
requiresfprintf
to interpret it as an escape sequence.newline
is a character array, so%s
is suitable withfprintf
. -
Building String Variables: You can concatenate strings with
newline
to create multiline strings.myString = ['Line A', newline, 'Line B', newline, 'Line C']; disp(myString);
Output:
Line A Line B Line C
Alternatively, using
sprintf
to build the string:myString_sprintf = sprintf('Line A\nLine B\nLine C'); disp(myString_sprintf);
Equivalent Methods (char(10)
and \n
)
As stated by the reference, newline
is equivalent to char(10)
and sprintf('\n')
.
-
char(10)
: This creates the ASCII character for line feed (LF), which is the standard newline character on Unix-like systems and interpreted as a newline by MATLAB functions.disp(['Using char(10): Line 1', char(10), 'Line 2']);
-
\n
: This is an escape sequence representing the newline character, typically used withinsprintf
format strings or string literals interpreted bysprintf
.fprintf('Using \\n in fprintf: Line 1\nLine 2\n');
Comparison Table
Method | Description | Common Usage | Notes |
---|---|---|---|
newline |
Standard, platform-independent newline constant | disp , String concatenation |
Recommended method |
char(10) |
ASCII Line Feed character | disp , String concatenation |
Works but newline is more explicit |
\n |
Escape sequence for newline | fprintf , sprintf |
Used within format strings or interpreted literals |
Using newline
is generally preferred for clarity and robustness across different operating systems and MATLAB versions.