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