<html lang="en"> <head> <title>Defining Functions - Untitled</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Untitled"> <meta name="generator" content="makeinfo 4.13"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Functions-and-Scripts.html#Functions-and-Scripts" title="Functions and Scripts"> <link rel="next" href="Multiple-Return-Values.html#Multiple-Return-Values" title="Multiple Return Values"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <a name="Defining-Functions"></a> <p> Next: <a rel="next" accesskey="n" href="Multiple-Return-Values.html#Multiple-Return-Values">Multiple Return Values</a>, Up: <a rel="up" accesskey="u" href="Functions-and-Scripts.html#Functions-and-Scripts">Functions and Scripts</a> <hr> </div> <h3 class="section">11.1 Defining Functions</h3> <p><a name="index-g_t_0040code_007bfunction_007d-statement-588"></a><a name="index-g_t_0040code_007bendfunction_007d-statement-589"></a> In its simplest form, the definition of a function named <var>name</var> looks like this: <pre class="example"> function <var>name</var> <var>body</var> endfunction </pre> <p class="noindent">A valid function name is like a valid variable name: a sequence of letters, digits and underscores, not starting with a digit. Functions share the same pool of names as variables. <p>The function <var>body</var> consists of Octave statements. It is the most important part of the definition, because it says what the function should actually <em>do</em>. <p>For example, here is a function that, when executed, will ring the bell on your terminal (assuming that it is possible to do so): <pre class="example"> function wakeup printf ("\a"); endfunction </pre> <p>The <code>printf</code> statement (see <a href="Input-and-Output.html#Input-and-Output">Input and Output</a>) simply tells Octave to print the string <code>"\a"</code>. The special character ‘<samp><span class="samp">\a</span></samp>’ stands for the alert character (ASCII 7). See <a href="Strings.html#Strings">Strings</a>. <p>Once this function is defined, you can ask Octave to evaluate it by typing the name of the function. <p>Normally, you will want to pass some information to the functions you define. The syntax for passing parameters to a function in Octave is <pre class="example"> function <var>name</var> (<var>arg-list</var>) <var>body</var> endfunction </pre> <p class="noindent">where <var>arg-list</var> is a comma-separated list of the function's arguments. When the function is called, the argument names are used to hold the argument values given in the call. The list of arguments may be empty, in which case this form is equivalent to the one shown above. <p>To print a message along with ringing the bell, you might modify the <code>wakeup</code> to look like this: <pre class="example"> function wakeup (message) printf ("\a%s\n", message); endfunction </pre> <p>Calling this function using a statement like this <pre class="example"> wakeup ("Rise and shine!"); </pre> <p class="noindent">will cause Octave to ring your terminal's bell and print the message ‘<samp><span class="samp">Rise and shine!</span></samp>’, followed by a newline character (the ‘<samp><span class="samp">\n</span></samp>’ in the first argument to the <code>printf</code> statement). <p>In most cases, you will also want to get some information back from the functions you define. Here is the syntax for writing a function that returns a single value: <pre class="example"> function <var>ret-var</var> = <var>name</var> (<var>arg-list</var>) <var>body</var> endfunction </pre> <p class="noindent">The symbol <var>ret-var</var> is the name of the variable that will hold the value to be returned by the function. This variable must be defined before the end of the function body in order for the function to return a value. <p>Variables used in the body of a function are local to the function. Variables named in <var>arg-list</var> and <var>ret-var</var> are also local to the function. See <a href="Global-Variables.html#Global-Variables">Global Variables</a>, for information about how to access global variables inside a function. <p>For example, here is a function that computes the average of the elements of a vector: <pre class="example"> function retval = avg (v) retval = sum (v) / length (v); endfunction </pre> <p>If we had written <code>avg</code> like this instead, <pre class="example"> function retval = avg (v) if (isvector (v)) retval = sum (v) / length (v); endif endfunction </pre> <p class="noindent">and then called the function with a matrix instead of a vector as the argument, Octave would have printed an error message like this: <pre class="example"> error: value on right hand side of assignment is undefined </pre> <p class="noindent">because the body of the <code>if</code> statement was never executed, and <code>retval</code> was never defined. To prevent obscure errors like this, it is a good idea to always make sure that the return variables will always have values, and to produce meaningful error messages when problems are encountered. For example, <code>avg</code> could have been written like this: <pre class="example"> function retval = avg (v) retval = 0; if (isvector (v)) retval = sum (v) / length (v); else error ("avg: expecting vector argument"); endif endfunction </pre> <p>There is still one additional problem with this function. What if it is called without an argument? Without additional error checking, Octave will probably print an error message that won't really help you track down the source of the error. To allow you to catch errors like this, Octave provides each function with an automatic variable called <code>nargin</code>. Each time a function is called, <code>nargin</code> is automatically initialized to the number of arguments that have actually been passed to the function. For example, we might rewrite the <code>avg</code> function like this: <pre class="example"> function retval = avg (v) retval = 0; if (nargin != 1) usage ("avg (vector)"); endif if (isvector (v)) retval = sum (v) / length (v); else error ("avg: expecting vector argument"); endif endfunction </pre> <p>Although Octave does not automatically report an error if you call a function with more arguments than expected, doing so probably indicates that something is wrong. Octave also does not automatically report an error if a function is called with too few arguments, but any attempt to use a variable that has not been given a value will result in an error. To avoid such problems and to provide useful messages, we check for both possibilities and issue our own error message. <!-- ov-usr-fcn.cc --> <p><a name="doc_002dnargin"></a> <div class="defun"> — Built-in Function: <b>nargin</b> ()<var><a name="index-nargin-590"></a></var><br> — Built-in Function: <b>nargin</b> (<var>fcn_name</var>)<var><a name="index-nargin-591"></a></var><br> <blockquote><p>Within a function, return the number of arguments passed to the function. At the top level, return the number of command line arguments passed to Octave. If called with the optional argument <var>fcn_name</var>, return the maximum number of arguments the named function can accept, or -1 if the function accepts a variable number of arguments. <!-- Texinfo @sp should work but in practice produces ugly results for HTML. --> <!-- A simple blank line produces the correct behavior. --> <!-- @sp 1 --> <p class="noindent"><strong>See also:</strong> <a href="doc_002dnargout.html#doc_002dnargout">nargout</a>, <a href="doc_002dvarargin.html#doc_002dvarargin">varargin</a>, <a href="doc_002dvarargout.html#doc_002dvarargout">varargout</a>. </p></blockquote></div> <!-- ./miscellaneous/inputname.m --> <p><a name="doc_002dinputname"></a> <div class="defun"> — Function File: <b>inputname</b> (<var>n</var>)<var><a name="index-inputname-592"></a></var><br> <blockquote><p>Return the text defining <var>n</var>-th input to the function. </p></blockquote></div> <!-- pt-eval.cc --> <p><a name="doc_002dsilent_005ffunctions"></a> <div class="defun"> — Built-in Function: <var>val</var> = <b>silent_functions</b> ()<var><a name="index-silent_005ffunctions-593"></a></var><br> — Built-in Function: <var>old_val</var> = <b>silent_functions</b> (<var>new_val</var>)<var><a name="index-silent_005ffunctions-594"></a></var><br> <blockquote><p>Query or set the internal variable that controls whether internal output from a function is suppressed. If this option is disabled, Octave will display the results produced by evaluating expressions within a function body that are not terminated with a semicolon. </p></blockquote></div> </body></html>