<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Created by GNU Texinfo 6.5, http://www.gnu.org/software/texinfo/ --> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Defining Functions (GNU Octave (version 5.1.0))</title> <meta name="description" content="Defining Functions (GNU Octave (version 5.1.0))"> <meta name="keywords" content="Defining Functions (GNU Octave (version 5.1.0))"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="makeinfo"> <link href="index.html#Top" rel="start" title="Top"> <link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index"> <link href="index.html#SEC_Contents" rel="contents" title="Table of Contents"> <link href="Functions-and-Scripts.html#Functions-and-Scripts" rel="up" title="Functions and Scripts"> <link href="Multiple-Return-Values.html#Multiple-Return-Values" rel="next" title="Multiple Return Values"> <link href="Introduction-to-Function-and-Script-Files.html#Introduction-to-Function-and-Script-Files" rel="prev" title="Introduction to Function and Script Files"> <style type="text/css"> <!-- a.summary-letter {text-decoration: none} blockquote.indentedblock {margin-right: 0em} blockquote.smallindentedblock {margin-right: 0em; font-size: smaller} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smalllisp {margin-left: 3.2em} kbd {font-style: oblique} pre.display {font-family: inherit} pre.format {font-family: inherit} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: inherit; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: inherit; font-size: smaller} pre.smalllisp {font-size: smaller} span.nolinebreak {white-space: nowrap} span.roman {font-family: initial; font-weight: normal} span.sansserif {font-family: sans-serif; font-weight: normal} ul.no-bullet {list-style: none} --> </style> <link rel="stylesheet" type="text/css" href="octave.css"> </head> <body lang="en"> <a name="Defining-Functions"></a> <div class="header"> <p> Next: <a href="Multiple-Return-Values.html#Multiple-Return-Values" accesskey="n" rel="next">Multiple Return Values</a>, Previous: <a href="Introduction-to-Function-and-Script-Files.html#Introduction-to-Function-and-Script-Files" accesskey="p" rel="prev">Introduction to Function and Script Files</a>, Up: <a href="Functions-and-Scripts.html#Functions-and-Scripts" accesskey="u" rel="up">Functions and Scripts</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p> </div> <hr> <a name="Defining-Functions-1"></a> <h3 class="section">11.2 Defining Functions</h3> <a name="index-function-statement"></a> <a name="index-endfunction-statement"></a> <p>In its simplest form, the definition of a function named <var>name</var> looks like this: </p> <div class="example"> <pre class="example">function <var>name</var> <var>body</var> endfunction </pre></div> <p>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> <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> <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): </p> <div class="example"> <pre class="example">function wakeup printf ("\a"); endfunction </pre></div> <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>\a</samp>’ stands for the alert character (ASCII 7). See <a href="Strings.html#Strings">Strings</a>. </p> <p>Once this function is defined, you can ask Octave to evaluate it by typing the name of the function. </p> <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 </p> <div class="example"> <pre class="example">function <var>name</var> (<var>arg-list</var>) <var>body</var> endfunction </pre></div> <p>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> <p>To print a message along with ringing the bell, you might modify the <code>wakeup</code> to look like this: </p> <div class="example"> <pre class="example">function wakeup (message) printf ("\a%s\n", message); endfunction </pre></div> <p>Calling this function using a statement like this </p> <div class="example"> <pre class="example">wakeup ("Rise and shine!"); </pre></div> <p>will cause Octave to ring your terminal’s bell and print the message ‘<samp>Rise and shine!</samp>’, followed by a newline character (the ‘<samp>\n</samp>’ in the first argument to the <code>printf</code> statement). </p> <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: </p> <div class="example"> <pre class="example">function <var>ret-var</var> = <var>name</var> (<var>arg-list</var>) <var>body</var> endfunction </pre></div> <p>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> <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> <p>For example, here is a function that computes the average of the elements of a vector: </p> <div class="example"> <pre class="example">function retval = avg (v) retval = sum (v) / length (v); endfunction </pre></div> <p>If we had written <code>avg</code> like this instead, </p> <div class="example"> <pre class="example">function retval = avg (v) if (isvector (v)) retval = sum (v) / length (v); endif endfunction </pre></div> <p>and then called the function with a matrix instead of a vector as the argument, Octave would have printed an error message like this: </p> <div class="example"> <pre class="example">error: value on right hand side of assignment is undefined </pre></div> <p>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: </p> <div class="example"> <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></div> <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: </p> <div class="example"> <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></div> <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. </p> <a name="XREFnargin"></a><dl> <dt><a name="index-nargin"></a><em></em> <strong>nargin</strong> <em>()</em></dt> <dt><a name="index-nargin-1"></a><em></em> <strong>nargin</strong> <em>(<var>fcn</var>)</em></dt> <dd><p>Report the number of input arguments to a function. </p> <p>Called from 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. </p> <p>If called with the optional argument <var>fcn</var>—a function name or handle—return the declared number of arguments that the function can accept. </p> <p>If the last argument to <var>fcn</var> is <var>varargin</var> the returned value is negative. For example, the function <code>union</code> for sets is declared as </p> <div class="example"> <pre class="example">function [y, ia, ib] = union (a, b, varargin) and nargin ("union") ⇒ -3 </pre></div> <p>Programming Note: <code>nargin</code> does not work on compiled functions (<samp>.oct</samp> files) such as built-in or dynamically loaded functions. </p> <p><strong>See also:</strong> <a href="Multiple-Return-Values.html#XREFnargout">nargout</a>, <a href="Multiple-Return-Values.html#XREFnarginchk">narginchk</a>, <a href="Multiple-Return-Values.html#XREFvarargin">varargin</a>, <a href="#XREFinputname">inputname</a>. </p></dd></dl> <a name="XREFinputname"></a><dl> <dt><a name="index-inputname"></a><em></em> <strong>inputname</strong> <em>(<var>n</var>)</em></dt> <dt><a name="index-inputname-1"></a><em></em> <strong>inputname</strong> <em>(<var>n</var>, <var>ids_only</var>)</em></dt> <dd><p>Return the name of the <var>n</var>-th argument to the calling function. </p> <p>If the argument is not a simple variable name, return an empty string. As an example, a reference to a field in a structure such as <code>s.field</code> is not a simple name and will return <code>""</code>. </p> <p><code>inputname</code> is only useful within a function. When used at the command line it always returns an empty string. </p> <p>By default, return an empty string if the <var>n</var>-th argument is not a valid variable name. If the optional argument <var>ids_only</var> is false, return the text of the argument even if it is not a valid variable name. </p> <p><strong>See also:</strong> <a href="#XREFnargin">nargin</a>, <a href="Multiple-Return-Values.html#XREFnthargout">nthargout</a>. </p></dd></dl> <a name="XREFsilent_005ffunctions"></a><dl> <dt><a name="index-silent_005ffunctions"></a><em><var>val</var> =</em> <strong>silent_functions</strong> <em>()</em></dt> <dt><a name="index-silent_005ffunctions-1"></a><em><var>old_val</var> =</em> <strong>silent_functions</strong> <em>(<var>new_val</var>)</em></dt> <dt><a name="index-silent_005ffunctions-2"></a><em></em> <strong>silent_functions</strong> <em>(<var>new_val</var>, "local")</em></dt> <dd><p>Query or set the internal variable that controls whether internal output from a function is suppressed. </p> <p>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> <p>When called from inside a function with the <code>"local"</code> option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. </p></dd></dl> <hr> <div class="header"> <p> Next: <a href="Multiple-Return-Values.html#Multiple-Return-Values" accesskey="n" rel="next">Multiple Return Values</a>, Previous: <a href="Introduction-to-Function-and-Script-Files.html#Introduction-to-Function-and-Script-Files" accesskey="p" rel="prev">Introduction to Function and Script Files</a>, Up: <a href="Functions-and-Scripts.html#Functions-and-Scripts" accesskey="u" rel="up">Functions and Scripts</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p> </div> </body> </html>