Octave: How to print a string or number to the terminal

In order to print a string to the terminal in GNU Octave use

disp_example.m
disp("Hello world");

This prints:

example.txt
>> disp("Hello world");
Hello world

If you want to display a number/variable in addition to the string, use this snippet:

example.txt
mynumber = 5;
disp("Hello world, mynumber="), disp(mynumber);

This prints:

example.txt
>> mynumber = 5;
>> disp("Hello world, mynumber="), disp(mynumber);
Hello world, mynumber=
 5

Alternatively, you can use printf, which I recommend for all but the most simple cases:

example.txt
>> printf ("Hello world, mynumber=%d\n", mynumber);
Hello world, mynumber=5

Don’t forget to add \n to the end of the printf format string to end the line, and use the correct format specifier (e.g. %d in this case for integers - see the printf docs for details).


Check out similar posts by category: Octave