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