Mercurial > octave-antonio
annotate doc/interpreter/func.txi @ 7984:bbaa5d7d0143
Some documentation updates
author | David Bateman <dbateman@free.fr> |
---|---|
date | Mon, 28 Jul 2008 15:47:40 +0200 |
parents | 2df457529cfa |
children | 30629059b72d |
rev | line source |
---|---|
6778 | 1 @c Copyright (C) 1996, 1997, 2007 John W. Eaton |
7018 | 2 @c |
3 @c This file is part of Octave. | |
4 @c | |
5 @c Octave is free software; you can redistribute it and/or modify it | |
6 @c under the terms of the GNU General Public License as published by the | |
7 @c Free Software Foundation; either version 3 of the License, or (at | |
8 @c your option) any later version. | |
9 @c | |
10 @c Octave is distributed in the hope that it will be useful, but WITHOUT | |
11 @c ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | |
12 @c FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | |
13 @c for more details. | |
14 @c | |
15 @c You should have received a copy of the GNU General Public License | |
16 @c along with Octave; see the file COPYING. If not, see | |
17 @c <http://www.gnu.org/licenses/>. | |
3294 | 18 |
4167 | 19 @node Functions and Scripts |
3294 | 20 @chapter Functions and Script Files |
21 @cindex defining functions | |
22 @cindex user-defined functions | |
23 @cindex functions, user-defined | |
24 @cindex script files | |
25 | |
26 Complicated Octave programs can often be simplified by defining | |
27 functions. Functions can be defined directly on the command line during | |
28 interactive Octave sessions, or in external files, and can be called just | |
29 like built-in functions. | |
30 | |
31 @menu | |
32 * Defining Functions:: | |
33 * Multiple Return Values:: | |
34 * Variable-length Argument Lists:: | |
35 * Variable-length Return Lists:: | |
36 * Returning From a Function:: | |
6510 | 37 * Default Arguments:: |
3294 | 38 * Function Files:: |
39 * Script Files:: | |
6638 | 40 * Function Handles Inline Functions and Anonymous Functions:: |
6549 | 41 * Commands:: |
3294 | 42 * Organization of Functions:: |
43 @end menu | |
44 | |
4167 | 45 @node Defining Functions |
3294 | 46 @section Defining Functions |
47 @cindex @code{function} statement | |
48 @cindex @code{endfunction} statement | |
49 | |
50 In its simplest form, the definition of a function named @var{name} | |
51 looks like this: | |
52 | |
53 @example | |
54 @group | |
55 function @var{name} | |
56 @var{body} | |
57 endfunction | |
58 @end group | |
59 @end example | |
60 | |
61 @noindent | |
62 A valid function name is like a valid variable name: a sequence of | |
63 letters, digits and underscores, not starting with a digit. Functions | |
64 share the same pool of names as variables. | |
65 | |
66 The function @var{body} consists of Octave statements. It is the | |
67 most important part of the definition, because it says what the function | |
68 should actually @emph{do}. | |
69 | |
70 For example, here is a function that, when executed, will ring the bell | |
71 on your terminal (assuming that it is possible to do so): | |
72 | |
73 @example | |
74 @group | |
75 function wakeup | |
76 printf ("\a"); | |
77 endfunction | |
78 @end group | |
79 @end example | |
80 | |
81 The @code{printf} statement (@pxref{Input and Output}) simply tells | |
82 Octave to print the string @code{"\a"}. The special character @samp{\a} | |
83 stands for the alert character (ASCII 7). @xref{Strings}. | |
84 | |
85 Once this function is defined, you can ask Octave to evaluate it by | |
86 typing the name of the function. | |
87 | |
88 Normally, you will want to pass some information to the functions you | |
89 define. The syntax for passing parameters to a function in Octave is | |
90 | |
91 @example | |
92 @group | |
93 function @var{name} (@var{arg-list}) | |
94 @var{body} | |
95 endfunction | |
96 @end group | |
97 @end example | |
98 | |
99 @noindent | |
100 where @var{arg-list} is a comma-separated list of the function's | |
101 arguments. When the function is called, the argument names are used to | |
102 hold the argument values given in the call. The list of arguments may | |
103 be empty, in which case this form is equivalent to the one shown above. | |
104 | |
105 To print a message along with ringing the bell, you might modify the | |
6510 | 106 @code{wakeup} to look like this: |
3294 | 107 |
108 @example | |
109 @group | |
110 function wakeup (message) | |
111 printf ("\a%s\n", message); | |
112 endfunction | |
113 @end group | |
114 @end example | |
115 | |
116 Calling this function using a statement like this | |
117 | |
118 @example | |
119 wakeup ("Rise and shine!"); | |
120 @end example | |
121 | |
122 @noindent | |
123 will cause Octave to ring your terminal's bell and print the message | |
124 @samp{Rise and shine!}, followed by a newline character (the @samp{\n} | |
125 in the first argument to the @code{printf} statement). | |
126 | |
127 In most cases, you will also want to get some information back from the | |
128 functions you define. Here is the syntax for writing a function that | |
129 returns a single value: | |
130 | |
131 @example | |
132 @group | |
133 function @var{ret-var} = @var{name} (@var{arg-list}) | |
134 @var{body} | |
135 endfunction | |
136 @end group | |
137 @end example | |
138 | |
139 @noindent | |
140 The symbol @var{ret-var} is the name of the variable that will hold the | |
141 value to be returned by the function. This variable must be defined | |
142 before the end of the function body in order for the function to return | |
143 a value. | |
144 | |
145 Variables used in the body of a function are local to the | |
146 function. Variables named in @var{arg-list} and @var{ret-var} are also | |
147 local to the function. @xref{Global Variables}, for information about | |
148 how to access global variables inside a function. | |
149 | |
150 For example, here is a function that computes the average of the | |
151 elements of a vector: | |
152 | |
153 @example | |
154 @group | |
155 function retval = avg (v) | |
156 retval = sum (v) / length (v); | |
157 endfunction | |
158 @end group | |
159 @end example | |
160 | |
161 If we had written @code{avg} like this instead, | |
162 | |
163 @example | |
164 @group | |
165 function retval = avg (v) | |
4029 | 166 if (isvector (v)) |
3294 | 167 retval = sum (v) / length (v); |
168 endif | |
169 endfunction | |
170 @end group | |
171 @end example | |
172 | |
173 @noindent | |
174 and then called the function with a matrix instead of a vector as the | |
175 argument, Octave would have printed an error message like this: | |
176 | |
177 @example | |
178 @group | |
179 error: `retval' undefined near line 1 column 10 | |
180 error: evaluating index expression near line 7, column 1 | |
181 @end group | |
182 @end example | |
183 | |
184 @noindent | |
185 because the body of the @code{if} statement was never executed, and | |
186 @code{retval} was never defined. To prevent obscure errors like this, | |
187 it is a good idea to always make sure that the return variables will | |
188 always have values, and to produce meaningful error messages when | |
189 problems are encountered. For example, @code{avg} could have been | |
190 written like this: | |
191 | |
192 @example | |
193 @group | |
194 function retval = avg (v) | |
195 retval = 0; | |
4029 | 196 if (isvector (v)) |
3294 | 197 retval = sum (v) / length (v); |
198 else | |
199 error ("avg: expecting vector argument"); | |
200 endif | |
201 endfunction | |
202 @end group | |
203 @end example | |
204 | |
205 There is still one additional problem with this function. What if it is | |
206 called without an argument? Without additional error checking, Octave | |
207 will probably print an error message that won't really help you track | |
208 down the source of the error. To allow you to catch errors like this, | |
209 Octave provides each function with an automatic variable called | |
210 @code{nargin}. Each time a function is called, @code{nargin} is | |
211 automatically initialized to the number of arguments that have actually | |
212 been passed to the function. For example, we might rewrite the | |
213 @code{avg} function like this: | |
214 | |
215 @example | |
216 @group | |
217 function retval = avg (v) | |
218 retval = 0; | |
219 if (nargin != 1) | |
220 usage ("avg (vector)"); | |
221 endif | |
4029 | 222 if (isvector (v)) |
3294 | 223 retval = sum (v) / length (v); |
224 else | |
225 error ("avg: expecting vector argument"); | |
226 endif | |
227 endfunction | |
228 @end group | |
229 @end example | |
230 | |
231 Although Octave does not automatically report an error if you call a | |
232 function with more arguments than expected, doing so probably indicates | |
233 that something is wrong. Octave also does not automatically report an | |
234 error if a function is called with too few arguments, but any attempt to | |
235 use a variable that has not been given a value will result in an error. | |
236 To avoid such problems and to provide useful messages, we check for both | |
237 possibilities and issue our own error message. | |
238 | |
4700 | 239 @DOCSTRING(nargin) |
3294 | 240 |
6558 | 241 @DOCSTRING(inputname) |
242 | |
3371 | 243 @DOCSTRING(silent_functions) |
3294 | 244 |
4167 | 245 @node Multiple Return Values |
3294 | 246 @section Multiple Return Values |
247 | |
248 Unlike many other computer languages, Octave allows you to define | |
249 functions that return more than one value. The syntax for defining | |
250 functions that return multiple values is | |
251 | |
252 @example | |
253 function [@var{ret-list}] = @var{name} (@var{arg-list}) | |
254 @var{body} | |
255 endfunction | |
256 @end example | |
257 | |
258 @noindent | |
259 where @var{name}, @var{arg-list}, and @var{body} have the same meaning | |
260 as before, and @var{ret-list} is a comma-separated list of variable | |
261 names that will hold the values returned from the function. The list of | |
262 return values must have at least one element. If @var{ret-list} has | |
263 only one element, this form of the @code{function} statement is | |
264 equivalent to the form described in the previous section. | |
265 | |
266 Here is an example of a function that returns two values, the maximum | |
267 element of a vector and the index of its first occurrence in the vector. | |
268 | |
269 @example | |
270 @group | |
271 function [max, idx] = vmax (v) | |
272 idx = 1; | |
273 max = v (idx); | |
274 for i = 2:length (v) | |
275 if (v (i) > max) | |
276 max = v (i); | |
277 idx = i; | |
278 endif | |
279 endfor | |
280 endfunction | |
281 @end group | |
282 @end example | |
283 | |
284 In this particular case, the two values could have been returned as | |
285 elements of a single array, but that is not always possible or | |
286 convenient. The values to be returned may not have compatible | |
287 dimensions, and it is often desirable to give the individual return | |
288 values distinct names. | |
289 | |
290 In addition to setting @code{nargin} each time a function is called, | |
291 Octave also automatically initializes @code{nargout} to the number of | |
292 values that are expected to be returned. This allows you to write | |
293 functions that behave differently depending on the number of values that | |
294 the user of the function has requested. The implicit assignment to the | |
295 built-in variable @code{ans} does not figure in the count of output | |
296 arguments, so the value of @code{nargout} may be zero. | |
297 | |
298 The @code{svd} and @code{lu} functions are examples of built-in | |
299 functions that behave differently depending on the value of | |
300 @code{nargout}. | |
301 | |
302 It is possible to write functions that only set some return values. For | |
303 example, calling the function | |
304 | |
305 @example | |
306 function [x, y, z] = f () | |
307 x = 1; | |
308 z = 2; | |
309 endfunction | |
310 @end example | |
311 | |
312 @noindent | |
313 as | |
314 | |
315 @example | |
316 [a, b, c] = f () | |
317 @end example | |
318 | |
319 @noindent | |
320 produces: | |
321 | |
322 @example | |
323 a = 1 | |
324 | |
325 b = [](0x0) | |
326 | |
327 c = 2 | |
328 @end example | |
329 | |
330 @noindent | |
6501 | 331 along with a warning. |
3294 | 332 |
4700 | 333 @DOCSTRING(nargout) |
3294 | 334 |
3371 | 335 @DOCSTRING(nargchk) |
3294 | 336 |
7984
bbaa5d7d0143
Some documentation updates
David Bateman <dbateman@free.fr>
parents:
7638
diff
changeset
|
337 @DOCSTRING(nargoutchk) |
bbaa5d7d0143
Some documentation updates
David Bateman <dbateman@free.fr>
parents:
7638
diff
changeset
|
338 |
4167 | 339 @node Variable-length Argument Lists |
3294 | 340 @section Variable-length Argument Lists |
4933 | 341 @cindex variable-length argument lists |
3294 | 342 @cindex @code{...} |
6510 | 343 Sometimes the number of input arguments is not known when the function |
344 is defined. As an example think of a function that returns the smallest | |
345 of all its input arguments. For example, | |
346 | |
347 @example | |
348 a = smallest (1, 2, 3); | |
349 b = smallest (1, 2, 3, 4); | |
350 @end example | |
351 | |
352 @noindent | |
353 In this example both @code{a} and @code{b} would be 1. One way to write | |
354 the @code{smallest} function is | |
355 | |
356 @example | |
357 function val = smallest (arg1, arg2, arg3, arg4, arg5) | |
358 @var{body} | |
359 endfunction | |
360 @end example | |
361 | |
362 @noindent | |
363 and then use the value of @code{nargin} to determine which of the input | |
364 arguments should be considered. The problem with this approach is | |
365 that it can only handle a limited number of input arguments. | |
366 | |
7588
cbedf652a752
doc fix for varargin and varargout change
John W. Eaton <jwe@octave.org>
parents:
7031
diff
changeset
|
367 If the special parameter name @code{varargin} appears at the end of a |
cbedf652a752
doc fix for varargin and varargout change
John W. Eaton <jwe@octave.org>
parents:
7031
diff
changeset
|
368 function parameter list it indicates that the function takes a variable |
cbedf652a752
doc fix for varargin and varargout change
John W. Eaton <jwe@octave.org>
parents:
7031
diff
changeset
|
369 number of input arguments. Using @code{varargin} the function |
6510 | 370 looks like this |
371 | |
372 @example | |
373 function val = smallest (varargin) | |
374 @var{body} | |
375 endfunction | |
376 @end example | |
377 | |
378 @noindent | |
379 In the function body the input arguments can be accessed through the | |
380 variable @code{varargin}. This variable is a cell array containing | |
381 all the input arguments. @xref{Cell Arrays}, for details on working | |
382 with cell arrays. The @code{smallest} function can now be defined | |
383 like this | |
384 | |
385 @example | |
386 function val = smallest (varargin) | |
387 val = min ([varargin@{:@}]); | |
388 endfunction | |
389 @end example | |
390 | |
391 @noindent | |
392 This implementation handles any number of input arguments, but it's also | |
393 a very simple solution to the problem. | |
394 | |
395 A slightly more complex example of @code{varargin} is a function | |
396 @code{print_arguments} that prints all input arguments. Such a function | |
397 can be defined like this | |
398 | |
399 @example | |
400 function print_arguments (varargin) | |
401 for i = 1:length (varargin) | |
402 printf ("Input argument %d: ", i); | |
403 disp (varargin@{i@}); | |
404 endfor | |
405 endfunction | |
406 @end example | |
407 | |
408 @noindent | |
409 This function produces output like this | |
410 | |
411 @example | |
412 @group | |
413 print_arguments (1, "two", 3); | |
414 @print{} Input argument 1: 1 | |
415 @print{} Input argument 2: two | |
416 @print{} Input argument 3: 3 | |
417 @end group | |
418 @end example | |
3294 | 419 |
6558 | 420 @DOCSTRING(parseparams) |
421 | |
4167 | 422 @node Variable-length Return Lists |
3294 | 423 @section Variable-length Return Lists |
4933 | 424 @cindex variable-length return lists |
6510 | 425 It is possible to return a variable number of output arguments from a |
426 function using a syntax that's similar to the one used with the | |
7588
cbedf652a752
doc fix for varargin and varargout change
John W. Eaton <jwe@octave.org>
parents:
7031
diff
changeset
|
427 special @code{varargin} parameter name. To let a function return a |
cbedf652a752
doc fix for varargin and varargout change
John W. Eaton <jwe@octave.org>
parents:
7031
diff
changeset
|
428 variable number of output arguments the special output parameter name |
cbedf652a752
doc fix for varargin and varargout change
John W. Eaton <jwe@octave.org>
parents:
7031
diff
changeset
|
429 @code{varargout} is used. As with @code{varargin}, @code{varargout} is |
cbedf652a752
doc fix for varargin and varargout change
John W. Eaton <jwe@octave.org>
parents:
7031
diff
changeset
|
430 a cell array that will contain the requested output arguments. |
6510 | 431 |
432 As an example the following function sets the first output argument to | |
433 1, the second to 2, and so on. | |
434 | |
435 @example | |
436 function varargout = one_to_n () | |
437 for i = 1:nargout | |
438 varargout@{i@} = i; | |
439 endfor | |
440 endfunction | |
441 @end example | |
442 | |
443 @noindent | |
444 When called this function returns values like this | |
445 | |
446 @example | |
447 @group | |
448 [a, b, c] = one_to_n () | |
449 @result{} a = 1 | |
450 @result{} b = 2 | |
451 @result{} c = 3 | |
452 @end group | |
453 @end example | |
3294 | 454 |
7588
cbedf652a752
doc fix for varargin and varargout change
John W. Eaton <jwe@octave.org>
parents:
7031
diff
changeset
|
455 If @code{varargin} (@code{varargout}) does not appear as the last |
cbedf652a752
doc fix for varargin and varargout change
John W. Eaton <jwe@octave.org>
parents:
7031
diff
changeset
|
456 element of the input (output) parameter list, then it is not special, |
cbedf652a752
doc fix for varargin and varargout change
John W. Eaton <jwe@octave.org>
parents:
7031
diff
changeset
|
457 and is handled the same as any other parameter name. |
cbedf652a752
doc fix for varargin and varargout change
John W. Eaton <jwe@octave.org>
parents:
7031
diff
changeset
|
458 |
6558 | 459 @DOCSTRING(deal) |
460 | |
4167 | 461 @node Returning From a Function |
3294 | 462 @section Returning From a Function |
463 | |
464 The body of a user-defined function can contain a @code{return} statement. | |
465 This statement returns control to the rest of the Octave program. It | |
466 looks like this: | |
467 | |
468 @example | |
469 return | |
470 @end example | |
471 | |
472 Unlike the @code{return} statement in C, Octave's @code{return} | |
473 statement cannot be used to return a value from a function. Instead, | |
474 you must assign values to the list of return variables that are part of | |
475 the @code{function} statement. The @code{return} statement simply makes | |
476 it easier to exit a function from a deeply nested loop or conditional | |
477 statement. | |
478 | |
479 Here is an example of a function that checks to see if any elements of a | |
480 vector are nonzero. | |
481 | |
482 @example | |
483 @group | |
484 function retval = any_nonzero (v) | |
485 retval = 0; | |
486 for i = 1:length (v) | |
487 if (v (i) != 0) | |
488 retval = 1; | |
489 return; | |
490 endif | |
491 endfor | |
492 printf ("no nonzero elements found\n"); | |
493 endfunction | |
494 @end group | |
495 @end example | |
496 | |
497 Note that this function could not have been written using the | |
498 @code{break} statement to exit the loop once a nonzero value is found | |
499 without adding extra logic to avoid printing the message if the vector | |
500 does contain a nonzero element. | |
501 | |
5763 | 502 @deffn {Keyword} return |
3294 | 503 When Octave encounters the keyword @code{return} inside a function or |
5016 | 504 script, it returns control to the caller immediately. At the top level, |
3294 | 505 the return statement is ignored. A @code{return} statement is assumed |
506 at the end of every function definition. | |
5763 | 507 @end deffn |
3294 | 508 |
3371 | 509 @DOCSTRING(return_last_computed_value) |
3294 | 510 |
6510 | 511 @node Default Arguments |
512 @section Default Arguments | |
513 @cindex default arguments | |
514 | |
515 Since Octave supports variable number of input arguments, it is very useful | |
516 to assign default values to some input arguments. When an input argument | |
517 is declared in the argument list it is possible to assign a default | |
518 value to the argument like this | |
519 | |
520 @example | |
521 function @var{name} (@var{arg1} = @var{val1}, @dots{}) | |
522 @var{body} | |
523 endfunction | |
524 @end example | |
525 | |
526 @noindent | |
527 If no value is assigned to @var{arg1} by the user, it will have the | |
528 value @var{val1}. | |
529 | |
530 As an example, the following function implements a variant of the classic | |
531 ``Hello, World'' program. | |
532 @example | |
533 function hello (who = "World") | |
534 printf ("Hello, %s!\n", who); | |
535 endfunction | |
536 @end example | |
537 | |
538 @noindent | |
539 When called without an input argument the function prints the following | |
540 @example | |
541 @group | |
542 hello (); | |
543 @print{} Hello, World! | |
544 @end group | |
545 @end example | |
546 | |
547 @noindent | |
548 and when it's called with an input argument it prints the following | |
549 @example | |
550 @group | |
551 hello ("Beautiful World of Free Software"); | |
552 @print{} Hello, Beautiful World of Free Software! | |
553 @end group | |
554 @end example | |
555 | |
556 Sometimes it is useful to explicitly tell Octave to use the default value | |
557 of an input argument. This can be done writing a @samp{:} as the value | |
558 of the input argument when calling the function. | |
559 @example | |
560 @group | |
561 hello (:); | |
562 @print{} Hello, World! | |
563 @end group | |
564 @end example | |
565 | |
4167 | 566 @node Function Files |
3294 | 567 @section Function Files |
568 @cindex function file | |
569 | |
570 Except for simple one-shot programs, it is not practical to have to | |
571 define all the functions you need each time you need them. Instead, you | |
572 will normally want to save them in a file so that you can easily edit | |
573 them, and save them for use at a later time. | |
574 | |
575 Octave does not require you to load function definitions from files | |
576 before using them. You simply need to put the function definitions in a | |
577 place where Octave can find them. | |
578 | |
579 When Octave encounters an identifier that is undefined, it first looks | |
580 for variables or functions that are already compiled and currently | |
581 listed in its symbol table. If it fails to find a definition there, it | |
6556 | 582 searches a list of directories (the @dfn{path}) for files ending in |
6554 | 583 @file{.m} that have the same base name as the undefined |
584 identifier.@footnote{The @samp{.m} suffix was chosen for compatibility | |
585 with @sc{Matlab}.} Once Octave finds a file with a name that matches, | |
586 the contents of the file are read. If it defines a @emph{single} | |
587 function, it is compiled and executed. @xref{Script Files}, for more | |
588 information about how you can define more than one function in a single | |
589 file. | |
3294 | 590 |
591 When Octave defines a function from a function file, it saves the full | |
6554 | 592 name of the file it read and the time stamp on the file. If the time |
593 stamp on the file changes, Octave may reload the file. When Octave is | |
594 running interactively, time stamp checking normally happens at most once | |
595 each time Octave prints the prompt. Searching for new function | |
596 definitions also occurs if the current working directory changes. | |
3294 | 597 |
598 Checking the time stamp allows you to edit the definition of a function | |
599 while Octave is running, and automatically use the new function | |
6554 | 600 definition without having to restart your Octave session. |
3294 | 601 |
602 To avoid degrading performance unnecessarily by checking the time stamps | |
603 on functions that are not likely to change, Octave assumes that function | |
604 files in the directory tree | |
605 @file{@var{octave-home}/share/octave/@var{version}/m} | |
606 will not change, so it doesn't have to check their time stamps every time the | |
607 functions defined in those files are used. This is normally a very good | |
608 assumption and provides a significant improvement in performance for the | |
609 function files that are distributed with Octave. | |
610 | |
611 If you know that your own function files will not change while you are | |
6554 | 612 running Octave, you can improve performance by calling |
613 @code{ignore_function_time_stamp ("all")}, so that Octave will | |
614 ignore the time stamps for all function files. Passing | |
615 @code{"system"} to this function resets the default behavior. | |
3294 | 616 |
5775 | 617 @c FIXME -- note about time stamps on files in NFS environments? |
3294 | 618 |
6549 | 619 @DOCSTRING(mfilename) |
620 | |
6638 | 621 @DOCSTRING(ignore_function_time_stamp) |
622 | |
623 @menu | |
624 * Manipulating the load path:: | |
625 * Subfunctions:: | |
626 * Overloading and Autoloading:: | |
627 * Function Locking:: | |
628 @end menu | |
629 | |
630 @node Manipulating the load path | |
631 @subsection Manipulating the load path | |
632 | |
633 When a function is called Octave searches a list of directories for | |
634 a file that contains the function declaration. This list of directories | |
635 is known as the load path. By default the load path contains | |
636 a list of directories distributed with Octave plus the current | |
637 working directory. To see your current load path call the @code{path} | |
638 function without any input or output arguments. | |
639 | |
640 It is possible to add or remove directories to or from the load path | |
641 using the @code{addpath} and @code{rmpath}. As an example, the following | |
642 code adds @samp{~/Octave} to the load path. | |
643 | |
644 @example | |
645 addpath("~/Octave") | |
646 @end example | |
647 | |
648 @noindent | |
649 After this the directory @samp{~/Octave} will be searched for functions. | |
650 | |
6502 | 651 @DOCSTRING(addpath) |
652 | |
653 @DOCSTRING(genpath) | |
654 | |
655 @DOCSTRING(rmpath) | |
656 | |
657 @DOCSTRING(savepath) | |
658 | |
6477 | 659 @DOCSTRING(path) |
3294 | 660 |
6502 | 661 @DOCSTRING(pathdef) |
662 | |
663 @DOCSTRING(pathsep) | |
664 | |
3428 | 665 @DOCSTRING(rehash) |
666 | |
667 @DOCSTRING(file_in_loadpath) | |
668 | |
7638
2df457529cfa
implement expm1 and log1p functions
Jaroslav Hajek <highegg@gmail.com>
parents:
7588
diff
changeset
|
669 @DOCSTRING(restoredefaultpath) |
2df457529cfa
implement expm1 and log1p functions
Jaroslav Hajek <highegg@gmail.com>
parents:
7588
diff
changeset
|
670 |
6556 | 671 @node Subfunctions |
672 @subsection Subfunctions | |
673 | |
674 A function file may contain secondary functions called | |
675 @dfn{subfunctions}. These secondary functions are only visible to the | |
676 other functions in the same function file. For example, a file | |
677 @file{f.m} containing | |
678 | |
679 @example | |
680 @group | |
681 function f () | |
682 printf ("in f, calling g\n"); | |
683 g () | |
684 endfunction | |
685 function g () | |
686 printf ("in g, calling h\n"); | |
6638 | 687 h () |
6556 | 688 endfunction |
689 function h () | |
690 printf ("in h\n") | |
691 endfunction | |
692 @end group | |
693 @end example | |
694 | |
695 @noindent | |
696 defines a main function @code{f} and two subfunctions. The | |
697 subfunctions @code{g} and @code{h} may only be called from the main | |
698 function @code{f} or from the other subfunctions, but not from outside | |
699 the file @file{f.m}. | |
700 | |
6635 | 701 @node Overloading and Autoloading |
702 @subsection Overloading and Autoloading | |
703 | |
704 The @code{dispatch} function can be used to alias one function name to | |
705 another. It can be used to alias all calls to a particular function name | |
706 to another function, or the alias can be limited to only a particular | |
707 variable type. Consider the example | |
708 | |
709 @example | |
710 @group | |
711 function y = spsin (x) | |
712 printf ("Calling spsin\n"); | |
713 fflush(stdout); | |
714 y = spfun ("sin", x); | |
715 endfunction | |
716 | |
717 dispatch ("sin", "spsin", "sparse matrix"); | |
718 y0 = sin(eye(3)); | |
719 y1 = sin(speye(3)); | |
720 @end group | |
721 @end example | |
722 | |
723 @noindent | |
724 Which aliases the @code{spsin} to @code{sin}, but only for real sparse | |
725 matrices. Note that the builtin @code{sin} already correctly treats | |
726 sparse matrices and so this example is only illustrative. | |
727 | |
728 @DOCSTRING(dispatch) | |
729 | |
730 @DOCSTRING(builtin) | |
731 | |
732 A single dynamically linked file might define several | |
733 functions. However, as Octave searches for functions based on the | |
734 functions filename, Octave needs a manner in which to find each of the | |
735 functions in the dynamically linked file. On operating systems that | |
736 support symbolic links, it is possible to create a symbolic link to the | |
737 original file for each of the functions which it contains. | |
738 | |
739 However, there is at least one well known operating system that doesn't | |
740 support symbolic links. Making copies of the original file for each of | |
741 the functions is also possible, but is undesirable as it multiples the | |
742 amount of disk space used by Octave. Instead Octave supplies the | |
743 @code{autoload} function, that permits the user to define in which | |
744 file a certain function will be found. | |
745 | |
746 @DOCSTRING(autoload) | |
747 | |
748 @node Function Locking | |
749 @subsection Function Locking | |
750 | |
751 It is sometime desirable to lock a function into memory with the | |
752 @code{mlock} function. This is typically used for dynamically linked | |
6899 | 753 functions in Oct-files or mex-files that contain some initialization, |
754 and it is desirable that calling @code{clear} does not remove this | |
6635 | 755 initialization. |
756 | |
6899 | 757 As an example, |
758 | |
759 @example | |
760 mlock ("my_function"); | |
761 @end example | |
762 | |
763 @noindent | |
764 prevents @code{my_function} from being removed from memory, even if | |
765 @code{clear} is called. It is possible to determine if a function is | |
766 locked into memory with the @code{mislocked}, and to unlock a function | |
767 with @code{munlock}, which the following illustrates. | |
768 | |
769 @example | |
770 @group | |
771 mlock ("my_function"); | |
772 mislocked ("my_function") | |
773 @result{} ans = 1 | |
774 munlock ("my_function"); | |
775 mislocked ("my_function") | |
776 @result{} ans = 0 | |
777 @end group | |
778 @end example | |
779 | |
780 A common use of @code{mlock} is to prevent persistent variables from | |
781 being removed from memory, as the following example shows. | |
782 | |
783 @example | |
784 @group | |
785 function count_calls() | |
786 persistent calls = 0; | |
7031 | 787 printf ("'count_calls' has been called %d times\n", |
788 ++calls); | |
6899 | 789 endfunction |
790 mlock ("count_calls"); | |
791 | |
792 count_calls (); | |
793 @print{} 'count_calls' has been called 1 times | |
794 | |
795 clear count_calls | |
796 count_calls (); | |
797 @print{} 'count_calls' has been called 2 times | |
798 @end group | |
799 @end example | |
800 | |
801 @noindent | |
802 It is, however, often inconvenient to lock a function from the prompt, | |
803 so it is also possible to lock a function from within its body. This | |
804 is simply done by calling @code{mlock} from within the function. | |
805 | |
806 @example | |
807 @group | |
808 function count_calls () | |
809 mlock (); | |
810 persistent calls = 0; | |
7031 | 811 printf ("'count_calls' has been called %d times\n", |
812 ++calls); | |
6899 | 813 endfunction |
814 @end group | |
815 @end example | |
816 | |
817 @code{mlock} might equally be used to prevent changes to a function from having | |
6635 | 818 effect in Octave, though a similar effect can be had with the |
819 @code{ignore_function_time_stamp} function. | |
820 | |
821 @DOCSTRING(mlock) | |
822 | |
823 @DOCSTRING(munlock) | |
824 | |
825 @DOCSTRING(mislocked) | |
826 | |
4167 | 827 @node Script Files |
3294 | 828 @section Script Files |
829 | |
830 A script file is a file containing (almost) any sequence of Octave | |
831 commands. It is read and evaluated just as if you had typed each | |
832 command at the Octave prompt, and provides a convenient way to perform a | |
833 sequence of commands that do not logically belong inside a function. | |
834 | |
835 Unlike a function file, a script file must @emph{not} begin with the | |
836 keyword @code{function}. If it does, Octave will assume that it is a | |
837 function file, and that it defines a single function that should be | |
838 evaluated as soon as it is defined. | |
839 | |
840 A script file also differs from a function file in that the variables | |
841 named in a script file are not local variables, but are in the same | |
842 scope as the other variables that are visible on the command line. | |
843 | |
844 Even though a script file may not begin with the @code{function} | |
845 keyword, it is possible to define more than one function in a single | |
846 script file and load (but not execute) all of them at once. To do | |
847 this, the first token in the file (ignoring comments and other white | |
848 space) must be something other than @code{function}. If you have no | |
849 other statements to evaluate, you can use a statement that has no | |
850 effect, like this: | |
851 | |
852 @example | |
853 @group | |
854 # Prevent Octave from thinking that this | |
855 # is a function file: | |
856 | |
857 1; | |
858 | |
859 # Define function one: | |
860 | |
861 function one () | |
862 ... | |
863 @end group | |
864 @end example | |
865 | |
866 To have Octave read and compile these functions into an internal form, | |
6638 | 867 you need to make sure that the file is in Octave's load path |
6477 | 868 (accessible through the @code{path} function), then simply type the |
869 base name of the file that contains the commands. (Octave uses the | |
870 same rules to search for script files as it does to search for | |
871 function files.) | |
3294 | 872 |
873 If the first token in a file (ignoring comments) is @code{function}, | |
874 Octave will compile the function and try to execute it, printing a | |
875 message warning about any non-whitespace characters that appear after | |
876 the function definition. | |
877 | |
878 Note that Octave does not try to look up the definition of any identifier | |
879 until it needs to evaluate it. This means that Octave will compile the | |
880 following statements if they appear in a script file, or are typed at | |
881 the command line, | |
882 | |
883 @example | |
884 @group | |
885 # not a function file: | |
886 1; | |
887 function foo () | |
888 do_something (); | |
889 endfunction | |
890 function do_something () | |
891 do_something_else (); | |
892 endfunction | |
893 @end group | |
894 @end example | |
895 | |
896 @noindent | |
897 even though the function @code{do_something} is not defined before it is | |
898 referenced in the function @code{foo}. This is not an error because | |
899 Octave does not need to resolve all symbols that are referenced by a | |
900 function until the function is actually evaluated. | |
901 | |
902 Since Octave doesn't look for definitions until they are needed, the | |
903 following code will always print @samp{bar = 3} whether it is typed | |
904 directly on the command line, read from a script file, or is part of a | |
905 function body, even if there is a function or script file called | |
6477 | 906 @file{bar.m} in Octave's path. |
3294 | 907 |
908 @example | |
909 @group | |
910 eval ("bar = 3"); | |
911 bar | |
912 @end group | |
913 @end example | |
914 | |
915 Code like this appearing within a function body could fool Octave if | |
916 definitions were resolved as the function was being compiled. It would | |
917 be virtually impossible to make Octave clever enough to evaluate this | |
918 code in a consistent fashion. The parser would have to be able to | |
919 perform the call to @code{eval} at compile time, and that would be | |
920 impossible unless all the references in the string to be evaluated could | |
921 also be resolved, and requiring that would be too restrictive (the | |
922 string might come from user input, or depend on things that are not | |
923 known until the function is evaluated). | |
924 | |
925 Although Octave normally executes commands from script files that have | |
926 the name @file{@var{file}.m}, you can use the function @code{source} to | |
927 execute commands from any file. | |
928 | |
3371 | 929 @DOCSTRING(source) |
3294 | 930 |
6638 | 931 @node Function Handles Inline Functions and Anonymous Functions |
932 @section Function Handles, Inline Functions, and Anonymous Functions | |
4933 | 933 @cindex handle, function handles |
934 @cindex inline, inline functions | |
6638 | 935 @cindex anonymous functions |
4933 | 936 |
6638 | 937 It can be very convenient store a function in a variable so that it |
938 can be passed to a different function. For example, a function that | |
939 performs numerical minimisation needs access to the function that | |
940 should be minimised. | |
4933 | 941 |
942 @menu | |
943 * Function Handles:: | |
6554 | 944 * Anonymous Functions:: |
4933 | 945 * Inline Functions:: |
946 @end menu | |
947 | |
948 @node Function Handles | |
949 @subsection Function Handles | |
950 | |
6554 | 951 A function handle is a pointer to another function and is defined with |
952 the syntax | |
953 | |
954 @example | |
955 @@@var{function-name} | |
956 @end example | |
957 | |
958 @noindent | |
959 For example | |
960 | |
961 @example | |
6556 | 962 f = @@sin; |
6554 | 963 @end example |
964 | |
965 @noindent | |
6570 | 966 Creates a function handle called @code{f} that refers to the |
6554 | 967 function @code{sin}. |
968 | |
969 Function handles are used to call other functions indirectly, or to pass | |
970 a function as an argument to another function like @code{quad} or | |
971 @code{fsolve}. For example | |
972 | |
973 @example | |
6556 | 974 f = @@sin; |
6554 | 975 quad (f, 0, pi) |
6929 | 976 @result{} 2 |
6554 | 977 @end example |
978 | |
979 You may use @code{feval} to call a function using function handle, or | |
6570 | 980 simply write the name of the function handle followed by an argument |
6554 | 981 list. If there are no arguments, you must use an empty argument list |
982 @samp{()}. For example | |
983 | |
984 @example | |
6556 | 985 f = @@sin; |
6554 | 986 feval (f, pi/4) |
6570 | 987 @result{} 0.70711 |
6554 | 988 f (pi/4) |
6570 | 989 @result{} 0.70711 |
6554 | 990 @end example |
991 | |
4933 | 992 @DOCSTRING(functions) |
993 | |
994 @DOCSTRING(func2str) | |
995 | |
996 @DOCSTRING(str2func) | |
997 | |
6570 | 998 @node Anonymous Functions |
6554 | 999 @subsection Anonymous Functions |
1000 | |
1001 Anonymous functions are defined using the syntax | |
1002 | |
1003 @example | |
1004 @@(@var{argument-list}) @var{expression} | |
1005 @end example | |
1006 | |
1007 @noindent | |
1008 Any variables that are not found in the argument list are inherited from | |
1009 the enclosing scope. Anonymous functions are useful for creating simple | |
1010 unnamed functions from expressions or for wrapping calls to other | |
1011 functions to adapt them for use by functions like @code{quad}. For | |
1012 example, | |
1013 | |
1014 @example | |
1015 f = @@(x) x.^2; | |
1016 quad (f, 0, 10) | |
6570 | 1017 @result{} 333.33 |
6554 | 1018 @end example |
1019 | |
1020 @noindent | |
1021 creates a simple unnamed function from the expression @code{x.^2} and | |
1022 passes it to @code{quad}, | |
1023 | |
1024 @example | |
1025 quad (@@(x) sin (x), 0, pi) | |
6933 | 1026 @result{} 2 |
6554 | 1027 @end example |
1028 | |
1029 @noindent | |
1030 wraps another function, and | |
1031 | |
1032 @example | |
1033 a = 1; | |
1034 b = 2; | |
1035 quad (@@(x) betainc (x, a, b), 0, 0.4) | |
6929 | 1036 @result{} 0.13867 |
6554 | 1037 @end example |
1038 | |
1039 @noindent | |
1040 adapts a function with several parameters to the form required by | |
1041 @code{quad}. In this example, the values of @var{a} and @var{b} that | |
1042 are passed to @code{betainc} are inherited from the current | |
1043 environment. | |
1044 | |
4933 | 1045 @node Inline Functions |
1046 @subsection Inline Functions | |
1047 | |
6638 | 1048 An inline function is created from a string containing the function |
1049 body using the @code{inline} function. The following code defines the | |
1050 function @math{f(x) = x^2 + 2}. | |
1051 | |
1052 @example | |
1053 f = inline("x^2 + 2"); | |
1054 @end example | |
1055 | |
1056 @noindent | |
1057 After this it is possible to evaluate @math{f} at any @math{x} by | |
1058 writing @code{f(x)}. | |
1059 | |
4933 | 1060 @DOCSTRING(inline) |
1061 | |
1062 @DOCSTRING(argnames) | |
1063 | |
1064 @DOCSTRING(formula) | |
1065 | |
1066 @DOCSTRING(vectorize) | |
1067 | |
7984
bbaa5d7d0143
Some documentation updates
David Bateman <dbateman@free.fr>
parents:
7638
diff
changeset
|
1068 @DOCSTRING(symvar) |
bbaa5d7d0143
Some documentation updates
David Bateman <dbateman@free.fr>
parents:
7638
diff
changeset
|
1069 |
6549 | 1070 @node Commands |
1071 @section Commands | |
1072 | |
6638 | 1073 Commands are a special class of functions that only accept string |
1074 input arguments. A command can be called as an ordinary function, but | |
1075 it can also be called without the parentheses like the following example | |
1076 shows | |
1077 | |
1078 @example | |
1079 my_command hello world | |
1080 @end example | |
1081 | |
1082 @noindent | |
1083 which is the same as | |
1084 | |
1085 @example | |
1086 my_command("hello", "world") | |
1087 @end example | |
1088 | |
1089 The general form of a command call is | |
1090 | |
1091 @example | |
1092 @var{name} @var{arg1} @var{arg2} @dots{} | |
1093 @end example | |
1094 | |
1095 @noindent | |
1096 which translates directly to | |
1097 | |
1098 @example | |
1099 @var{name} ("@var{arg1}", "@var{arg2}", @dots{}) | |
1100 @end example | |
1101 | |
7001 | 1102 A function can be used as a command if it accepts string input arguments. |
6638 | 1103 To do this, the function must be marked as a command, which can be done |
1104 with the @code{mark_as_command} command like this | |
1105 | |
1106 @example | |
1107 mark_as_command name | |
1108 @end example | |
1109 | |
1110 @noindent | |
1111 where @code{name} is the function to be marked as a command. | |
1112 | |
1113 One difficulty of commands occurs when one of the string input arguments | |
1114 are stored in a variable. Since Octave can't tell the difference between | |
1115 a variable name, and an ordinary string, it is not possible to pass a | |
1116 variable as input to a command. In such a situation a command must be | |
1117 called as a function. | |
1118 | |
6549 | 1119 @DOCSTRING(mark_as_command) |
1120 | |
1121 @DOCSTRING(unmark_command) | |
1122 | |
1123 @DOCSTRING(iscommand) | |
1124 | |
1125 @DOCSTRING(mark_as_rawcommand) | |
1126 | |
1127 @DOCSTRING(unmark_rawcommand) | |
1128 | |
1129 @DOCSTRING(israwcommand) | |
1130 | |
4167 | 1131 @node Organization of Functions |
3294 | 1132 @section Organization of Functions Distributed with Octave |
1133 | |
1134 Many of Octave's standard functions are distributed as function files. | |
1135 They are loosely organized by topic, in subdirectories of | |
1136 @file{@var{octave-home}/lib/octave/@var{version}/m}, to make it easier | |
1137 to find them. | |
1138 | |
1139 The following is a list of all the function file subdirectories, and the | |
1140 types of functions you will find there. | |
1141 | |
1142 @table @file | |
1143 @item audio | |
1144 Functions for playing and recording sounds. | |
1145 | |
1146 @item control | |
1147 Functions for design and simulation of automatic control systems. | |
1148 | |
1149 @item elfun | |
1150 Elementary functions. | |
1151 | |
6554 | 1152 @item finance |
1153 Functions for computing interest payments, investment values, and rates | |
1154 of return. | |
1155 | |
3294 | 1156 @item general |
1157 Miscellaneous matrix manipulations, like @code{flipud}, @code{rot90}, | |
1158 and @code{triu}, as well as other basic functions, like | |
4029 | 1159 @code{ismatrix}, @code{nargchk}, etc. |
3294 | 1160 |
1161 @item image | |
1162 Image processing tools. These functions require the X Window System. | |
1163 | |
1164 @item io | |
1165 Input-ouput functions. | |
1166 | |
1167 @item linear-algebra | |
1168 Functions for linear algebra. | |
1169 | |
1170 @item miscellaneous | |
1171 Functions that don't really belong anywhere else. | |
1172 | |
6554 | 1173 @item optimization |
1174 Minimization of functions. | |
1175 | |
1176 @item path | |
1177 Functions to manage the directory path Octave uses to find functions. | |
1178 | |
1179 @item pkg | |
1180 Install external packages of functions in Octave. | |
1181 | |
3294 | 1182 @item plot |
6556 | 1183 Functions for displaying and printing two- and three-dimensional graphs. |
3294 | 1184 |
1185 @item polynomial | |
1186 Functions for manipulating polynomials. | |
1187 | |
1188 @item set | |
1189 Functions for creating and manipulating sets of unique values. | |
1190 | |
1191 @item signal | |
1192 Functions for signal processing applications. | |
1193 | |
6554 | 1194 @item sparse |
1195 Functions for handling sparse matrices. | |
1196 | |
3294 | 1197 @item specfun |
1198 Special functions. | |
1199 | |
1200 @item special-matrix | |
1201 Functions that create special matrix forms. | |
1202 | |
1203 @item startup | |
1204 Octave's system-wide startup file. | |
1205 | |
1206 @item statistics | |
1207 Statistical functions. | |
1208 | |
1209 @item strings | |
1210 Miscellaneous string-handling functions. | |
1211 | |
6554 | 1212 @item testfun |
1213 Perform unit tests on other functions. | |
1214 | |
3294 | 1215 @item time |
1216 Functions related to time keeping. | |
1217 @end table |