11.8 Default Arguments

Since Octave supports variable number of input arguments, it is very useful to assign default values to some input arguments. When an input argument is declared in the argument list it is possible to assign a default value to the argument like this

function name (arg1 = val1, …)
  body
endfunction

If no value is assigned to arg1 by the user, it will have the value val1.

As an example, the following function implements a variant of the classic “Hello, World” program.

function hello (who = "World")
  printf ("Hello, %s!\n", who);
endfunction

When called without an input argument the function prints the following

hello ();
     -| Hello, World!

and when it’s called with an input argument it prints the following

hello ("Beautiful World of Free Software");
     -| Hello, Beautiful World of Free Software!

Sometimes it is useful to explicitly tell Octave to use the default value of an input argument. This can be done writing a ‘:’ as the value of the input argument when calling the function.

hello (:);
     -| Hello, World!

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v5.2.0/Default-Arguments.html