File: Defining-Functions.html

package info (click to toggle)
octave3.2 3.2.4-8
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 62,936 kB
  • ctags: 37,353
  • sloc: cpp: 219,497; fortran: 116,336; ansic: 10,264; sh: 5,508; makefile: 4,245; lex: 3,573; yacc: 3,062; objc: 2,042; lisp: 1,692; awk: 860; perl: 844
file content (215 lines) | stat: -rw-r--r-- 9,787 bytes parent folder | download
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
<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.11">
<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">
<p>
<a name="Defining-Functions"></a>
Next:&nbsp;<a rel="next" accesskey="n" href="Multiple-Return-Values.html#Multiple-Return-Values">Multiple Return Values</a>,
Up:&nbsp;<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 &lsquo;<samp><span class="samp">\a</span></samp>&rsquo;
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
&lsquo;<samp><span class="samp">Rise and shine!</span></samp>&rsquo;, followed by a newline character (the &lsquo;<samp><span class="samp">\n</span></samp>&rsquo;
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">
&mdash; Built-in Function:  <b>nargin</b> ()<var><a name="index-nargin-590"></a></var><br>
&mdash; 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">
&mdash; 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">
&mdash; Built-in Function: <var>val</var> = <b>silent_functions</b> ()<var><a name="index-silent_005ffunctions-593"></a></var><br>
&mdash; 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>