File: Defining-Functions.html

package info (click to toggle)
octave 10.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 145,388 kB
  • sloc: cpp: 335,976; ansic: 82,241; fortran: 20,963; objc: 9,402; sh: 8,756; yacc: 4,392; lex: 4,333; perl: 1,544; java: 1,366; awk: 1,259; makefile: 659; xml: 192
file content (298 lines) | stat: -rw-r--r-- 15,578 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
<!DOCTYPE html>
<html>
<!-- Created by GNU Texinfo 7.1.1, https://www.gnu.org/software/texinfo/ -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Defining Functions (GNU Octave (version 10.3.0))</title>

<meta name="description" content="Defining Functions (GNU Octave (version 10.3.0))">
<meta name="keywords" content="Defining Functions (GNU Octave (version 10.3.0))">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta name="viewport" content="width=device-width,initial-scale=1">

<link href="index.html" rel="start" title="Top">
<link href="Concept-Index.html" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Functions-and-Scripts.html" rel="up" title="Functions and Scripts">
<link href="Returning-from-a-Function.html" rel="next" title="Returning from a Function">
<link href="Introduction-to-Function-and-Script-Files.html" rel="prev" title="Introduction to Function and Script Files">
<style type="text/css">
<!--
a.copiable-link {visibility: hidden; text-decoration: none; line-height: 0em}
div.example {margin-left: 3.2em}
span:hover a.copiable-link {visibility: visible}
strong.def-name {font-family: monospace; font-weight: bold; font-size: larger}
-->
</style>
<link rel="stylesheet" type="text/css" href="octave.css">


</head>

<body lang="en">
<div class="section-level-extent" id="Defining-Functions">
<div class="nav-panel">
<p>
Next: <a href="Returning-from-a-Function.html" accesskey="n" rel="next">Returning from a Function</a>, Previous: <a href="Introduction-to-Function-and-Script-Files.html" accesskey="p" rel="prev">Introduction to Function and Script Files</a>, Up: <a href="Functions-and-Scripts.html" accesskey="u" rel="up">Functions and Scripts</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<h3 class="section" id="Defining-Functions-1"><span>11.2 Defining Functions<a class="copiable-link" href="#Defining-Functions-1"> &para;</a></span></h3>
<a class="index-entry-id" id="index-function-statement"></a>
<a class="index-entry-id" id="index-endfunction-statement"></a>

<p>In its simplest form, the definition of a function named <var class="var">name</var>
looks like this:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">function <var class="var">name</var>
  <var class="var">body</var>
endfunction
</pre></div></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 class="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 class="emph">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">
<div class="group"><pre class="example-preformatted">function wakeup
  printf (&quot;\a&quot;);
endfunction
</pre></div></div>

<p>The <code class="code">printf</code> statement (see <a class="pxref" href="Input-and-Output.html">Input and Output</a>) simply tells
Octave to print the string <code class="code">&quot;\a&quot;</code>.  The special character
&lsquo;<samp class="samp">\a</samp>&rsquo; stands for the alert character (ASCII 7).  See <a class="xref" href="Strings.html">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">
<div class="group"><pre class="example-preformatted">function <var class="var">name</var> (<var class="var">arg-list</var>)
  <var class="var">body</var>
endfunction
</pre></div></div>

<p>where <var class="var">arg-list</var> is a comma-separated list of the function&rsquo;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 class="code">wakeup</code> to look like this:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">function wakeup (message)
  printf (&quot;\a%s\n&quot;, message);
endfunction
</pre></div></div>

<p>Calling this function using a statement like this
</p>
<div class="example">
<pre class="example-preformatted">wakeup (&quot;Rise and shine!&quot;);
</pre></div>

<p>will cause Octave to ring your terminal&rsquo;s bell and print the message
&lsquo;<samp class="samp">Rise and shine!</samp>&rsquo;, followed by a newline character (the &lsquo;<samp class="samp">\n</samp>&rsquo;
in the first argument to the <code class="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">
<div class="group"><pre class="example-preformatted">function <var class="var">ret-var</var> = <var class="var">name</var> (<var class="var">arg-list</var>)
  <var class="var">body</var>
endfunction
</pre></div></div>

<p>The symbol <var class="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 class="var">arg-list</var> and <var class="var">ret-var</var> are also
local to the function.  See <a class="xref" href="Global-Variables.html">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">
<div class="group"><pre class="example-preformatted">function retval = avg (v)
  retval = sum (v) / length (v);
endfunction
</pre></div></div>

<p>If we had written <code class="code">avg</code> like this instead,
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">function retval = avg (v)
  if (isvector (v))
    retval = sum (v) / length (v);
  endif
endfunction
</pre></div></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">
<div class="group"><pre class="example-preformatted">error: value on right hand side of assignment is undefined
</pre></div></div>

<p>because the body of the <code class="code">if</code> statement was never executed, and
<code class="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 class="code">avg</code> could have been
written like this:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">function retval = avg (v)
  retval = 0;
  if (isvector (v))
    retval = sum (v) / length (v);
  else
    error (&quot;avg: expecting vector argument&quot;);
  endif
endfunction
</pre></div></div>

<p>There is still one remaining 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&rsquo;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 class="code">nargin</code>.  Each time a function is called, <code class="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 class="code">avg</code> function like this:
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">function retval = avg (v)
  retval = 0;
  if (nargin != 1)
    usage (&quot;avg (vector)&quot;);
  endif
  if (isvector (v))
    retval = sum (v) / length (v);
  else
    error (&quot;avg: expecting vector argument&quot;);
  endif
endfunction
</pre></div></div>

<p>Octave automatically reports an error for functions written in .m file code
if they are called with more arguments than expected.  Octave does not
automatically report an error if a function is called with too few arguments,
since functions in general may have default arguments, but any attempt to use
a variable that has not been given a value will result in an error.
Functions can check the arguments they are called with to avoid such problems
and to provide more context-specific error messages.
</p>
<a class="anchor" id="XREFnargin"></a><span style="display:block; margin-top:-4.5ex;">&nbsp;</span>


<dl class="first-deftypefn">
<dt class="deftypefn" id="index-nargin"><span><code class="def-type"><var class="var">n</var> =</code> <strong class="def-name">nargin</strong> <code class="def-code-arguments">()</code><a class="copiable-link" href="#index-nargin"> &para;</a></span></dt>
<dt class="deftypefnx def-cmd-deftypefn" id="index-nargin-1"><span><code class="def-type"><var class="var">n</var> =</code> <strong class="def-name">nargin</strong> <code class="def-code-arguments">(<var class="var">fcn</var>)</code><a class="copiable-link" href="#index-nargin-1"> &para;</a></span></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 class="var">fcn</var>&mdash;a function name or
handle&mdash;return the declared number of arguments that the function can
accept.
</p>
<p>If the last argument to <var class="var">fcn</var> is <var class="var">varargin</var> the returned value is
negative.  For example, the function <code class="code">union</code> for sets is declared as
</p>
<div class="example">
<div class="group"><pre class="example-preformatted">function [y, ia, ib] = union (a, b, varargin)

and

nargin (&quot;union&quot;)
&rArr; -3
</pre></div></div>

<p>Programming Note: <code class="code">nargin</code> does not work on compiled functions
(<samp class="file">.oct</samp> files) such as built-in or dynamically loaded functions.
</p>
<p><strong class="strong">See also:</strong> <a class="ref" href="Multiple-Return-Values.html#XREFnargout">nargout</a>, <a class="ref" href="Validating-the-number-of-Arguments.html#XREFnarginchk">narginchk</a>, <a class="ref" href="Variable_002dlength-Argument-Lists.html#XREFvarargin">varargin</a>, <a class="ref" href="#XREFinputname">inputname</a>.
</p></dd></dl>


<a class="anchor" id="XREFinputname"></a><span style="display:block; margin-top:-4.5ex;">&nbsp;</span>


<dl class="first-deftypefn">
<dt class="deftypefn" id="index-inputname"><span><code class="def-type"><var class="var">namestr</var> =</code> <strong class="def-name">inputname</strong> <code class="def-code-arguments">(<var class="var">n</var>)</code><a class="copiable-link" href="#index-inputname"> &para;</a></span></dt>
<dt class="deftypefnx def-cmd-deftypefn" id="index-inputname-1"><span><code class="def-type"><var class="var">namestr</var> =</code> <strong class="def-name">inputname</strong> <code class="def-code-arguments">(<var class="var">n</var>, <var class="var">ids_only</var>)</code><a class="copiable-link" href="#index-inputname-1"> &para;</a></span></dt>
<dd><p>Return the name of the <var class="var">n</var>-th argument to the calling function.
</p>
<p>If the argument is not a simple variable name, return an empty string.
Examples which will return <code class="code">&quot;&quot;</code> are numbers (<code class="code">5.1</code>), expressions
(<code class="code"><var class="var">y</var>/2</code>), and cell or structure indexing (<code class="code"><var class="var">c</var>{1}</code> or
<code class="code"><var class="var">s</var>.<var class="var">field</var></code>).
</p>
<p><code class="code">inputname</code> is only useful within a function.  When used at the command
line or within a script it always returns an empty string.
</p>
<p>By default, return an empty string if the <var class="var">n</var>-th argument is not a valid
variable name.  If the optional argument <var class="var">ids_only</var> is false, return the
text of the argument even if it is not a valid variable name.  This is an
Octave extension that allows the programmer to view exactly how the function
was invoked even when the inputs are complex expressions.
</p>
<p><strong class="strong">See also:</strong> <a class="ref" href="#XREFnargin">nargin</a>, <a class="ref" href="Validating-the-number-of-Arguments.html#XREFnarginchk">narginchk</a>.
</p></dd></dl>


<a class="anchor" id="XREFsilent_005ffunctions"></a><span style="display:block; margin-top:-4.5ex;">&nbsp;</span>


<dl class="first-deftypefn">
<dt class="deftypefn" id="index-silent_005ffunctions"><span><code class="def-type"><var class="var">val</var> =</code> <strong class="def-name">silent_functions</strong> <code class="def-code-arguments">()</code><a class="copiable-link" href="#index-silent_005ffunctions"> &para;</a></span></dt>
<dt class="deftypefnx def-cmd-deftypefn" id="index-silent_005ffunctions-1"><span><code class="def-type"><var class="var">old_val</var> =</code> <strong class="def-name">silent_functions</strong> <code class="def-code-arguments">(<var class="var">new_val</var>)</code><a class="copiable-link" href="#index-silent_005ffunctions-1"> &para;</a></span></dt>
<dt class="deftypefnx def-cmd-deftypefn" id="index-silent_005ffunctions-2"><span><code class="def-type"><var class="var">old_val</var> =</code> <strong class="def-name">silent_functions</strong> <code class="def-code-arguments">(<var class="var">new_val</var>, &quot;local&quot;)</code><a class="copiable-link" href="#index-silent_005ffunctions-2"> &para;</a></span></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 class="code">&quot;local&quot;</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>


</div>
<hr>
<div class="nav-panel">
<p>
Next: <a href="Returning-from-a-Function.html">Returning from a Function</a>, Previous: <a href="Introduction-to-Function-and-Script-Files.html">Introduction to Function and Script Files</a>, Up: <a href="Functions-and-Scripts.html">Functions and Scripts</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html" title="Index" rel="index">Index</a>]</p>
</div>



</body>
</html>