Previous: , Up: Executable Octave Programs   [Contents][Index]

2.6.2 Dual-Purpose Executable Scripts and Octave Functions

To write m-files that can act as executable programs when called from the shell or as normal functions when called from within Octave, use default input arguments initialized with the argv function.

If a function is called from the shell Octave will not pass any input parameters to the function and therefore the default argument is used. But when a function is called from the interpreter any arguments are passed to the function and these override the default.

Additionally, the file must end with the extension .m so that the interpreter will recognize it as an Octave function. Finally, the output from argv is a cell array of strings. It may be necessary to convert this to a numeric value with str2double or str2num before processing.

As a complete example, consider the following code located in the file mysin.m.

#! /bin/octave -qf
function retval = mysin (x = str2double (argv(){end}))
  retval = sin (x)

This can be called from the shell with

mysin.m 1.5

or from Octave with

mysin (1.5)