Default Arguments (GNU Octave (version 5.1.90))

Next: Function Files, Previous: Returning from a Function, Up: Functions and Scripts [Contents][Index]

### 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!