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) endfunction
This can be called from the shell with
mysin.m 1.5
or from Octave with
mysin (1.5)
© 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/v6.3.0/Dual_002dPurpose-Executable-Scripts-and-Octave-Functions.html