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:: |
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 |
3371
|
227 @DOCSTRING(silent_functions) |
3294
|
228 |
4167
|
229 @node Multiple Return Values |
3294
|
230 @section Multiple Return Values |
|
231 |
|
232 Unlike many other computer languages, Octave allows you to define |
|
233 functions that return more than one value. The syntax for defining |
|
234 functions that return multiple values is |
|
235 |
|
236 @example |
|
237 function [@var{ret-list}] = @var{name} (@var{arg-list}) |
|
238 @var{body} |
|
239 endfunction |
|
240 @end example |
|
241 |
|
242 @noindent |
|
243 where @var{name}, @var{arg-list}, and @var{body} have the same meaning |
|
244 as before, and @var{ret-list} is a comma-separated list of variable |
|
245 names that will hold the values returned from the function. The list of |
|
246 return values must have at least one element. If @var{ret-list} has |
|
247 only one element, this form of the @code{function} statement is |
|
248 equivalent to the form described in the previous section. |
|
249 |
|
250 Here is an example of a function that returns two values, the maximum |
|
251 element of a vector and the index of its first occurrence in the vector. |
|
252 |
|
253 @example |
|
254 @group |
|
255 function [max, idx] = vmax (v) |
|
256 idx = 1; |
|
257 max = v (idx); |
|
258 for i = 2:length (v) |
|
259 if (v (i) > max) |
|
260 max = v (i); |
|
261 idx = i; |
|
262 endif |
|
263 endfor |
|
264 endfunction |
|
265 @end group |
|
266 @end example |
|
267 |
|
268 In this particular case, the two values could have been returned as |
|
269 elements of a single array, but that is not always possible or |
|
270 convenient. The values to be returned may not have compatible |
|
271 dimensions, and it is often desirable to give the individual return |
|
272 values distinct names. |
|
273 |
|
274 In addition to setting @code{nargin} each time a function is called, |
|
275 Octave also automatically initializes @code{nargout} to the number of |
|
276 values that are expected to be returned. This allows you to write |
|
277 functions that behave differently depending on the number of values that |
|
278 the user of the function has requested. The implicit assignment to the |
|
279 built-in variable @code{ans} does not figure in the count of output |
|
280 arguments, so the value of @code{nargout} may be zero. |
|
281 |
|
282 The @code{svd} and @code{lu} functions are examples of built-in |
|
283 functions that behave differently depending on the value of |
|
284 @code{nargout}. |
|
285 |
|
286 It is possible to write functions that only set some return values. For |
|
287 example, calling the function |
|
288 |
|
289 @example |
|
290 function [x, y, z] = f () |
|
291 x = 1; |
|
292 z = 2; |
|
293 endfunction |
|
294 @end example |
|
295 |
|
296 @noindent |
|
297 as |
|
298 |
|
299 @example |
|
300 [a, b, c] = f () |
|
301 @end example |
|
302 |
|
303 @noindent |
|
304 produces: |
|
305 |
|
306 @example |
|
307 a = 1 |
|
308 |
|
309 b = [](0x0) |
|
310 |
|
311 c = 2 |
|
312 @end example |
|
313 |
|
314 @noindent |
6501
|
315 along with a warning. |
3294
|
316 |
4700
|
317 @DOCSTRING(nargout) |
3294
|
318 |
3371
|
319 @DOCSTRING(nargchk) |
3294
|
320 |
4167
|
321 @node Variable-length Argument Lists |
3294
|
322 @section Variable-length Argument Lists |
4933
|
323 @cindex variable-length argument lists |
3294
|
324 @cindex @code{...} |
6510
|
325 Sometimes the number of input arguments is not known when the function |
|
326 is defined. As an example think of a function that returns the smallest |
|
327 of all its input arguments. For example, |
|
328 |
|
329 @example |
|
330 a = smallest (1, 2, 3); |
|
331 b = smallest (1, 2, 3, 4); |
|
332 @end example |
|
333 |
|
334 @noindent |
|
335 In this example both @code{a} and @code{b} would be 1. One way to write |
|
336 the @code{smallest} function is |
|
337 |
|
338 @example |
|
339 function val = smallest (arg1, arg2, arg3, arg4, arg5) |
|
340 @var{body} |
|
341 endfunction |
|
342 @end example |
|
343 |
|
344 @noindent |
|
345 and then use the value of @code{nargin} to determine which of the input |
|
346 arguments should be considered. The problem with this approach is |
|
347 that it can only handle a limited number of input arguments. |
|
348 |
|
349 Octave supports the @code{varargin} keyword for handling a variable |
|
350 number of input arguments. Using @code{varargin} the function |
|
351 looks like this |
|
352 |
|
353 @example |
|
354 function val = smallest (varargin) |
|
355 @var{body} |
|
356 endfunction |
|
357 @end example |
|
358 |
|
359 @noindent |
|
360 In the function body the input arguments can be accessed through the |
|
361 variable @code{varargin}. This variable is a cell array containing |
|
362 all the input arguments. @xref{Cell Arrays}, for details on working |
|
363 with cell arrays. The @code{smallest} function can now be defined |
|
364 like this |
|
365 |
|
366 @example |
|
367 function val = smallest (varargin) |
|
368 val = min ([varargin@{:@}]); |
|
369 endfunction |
|
370 @end example |
|
371 |
|
372 @noindent |
|
373 This implementation handles any number of input arguments, but it's also |
|
374 a very simple solution to the problem. |
|
375 |
|
376 A slightly more complex example of @code{varargin} is a function |
|
377 @code{print_arguments} that prints all input arguments. Such a function |
|
378 can be defined like this |
|
379 |
|
380 @example |
|
381 function print_arguments (varargin) |
|
382 for i = 1:length (varargin) |
|
383 printf ("Input argument %d: ", i); |
|
384 disp (varargin@{i@}); |
|
385 endfor |
|
386 endfunction |
|
387 @end example |
|
388 |
|
389 @noindent |
|
390 This function produces output like this |
|
391 |
|
392 @example |
|
393 @group |
|
394 print_arguments (1, "two", 3); |
|
395 @print{} Input argument 1: 1 |
|
396 @print{} Input argument 2: two |
|
397 @print{} Input argument 3: 3 |
|
398 @end group |
|
399 @end example |
3294
|
400 |
4167
|
401 @node Variable-length Return Lists |
3294
|
402 @section Variable-length Return Lists |
4933
|
403 @cindex variable-length return lists |
6510
|
404 It is possible to return a variable number of output arguments from a |
|
405 function using a syntax that's similar to the one used with the |
|
406 @code{varargin} keyword. To let a function return a variable number of |
|
407 output arguments the @code{varargout} keyword is used. As with |
|
408 @code{varargin} @code{varargout} is a cell array that will contain the |
|
409 requested output arguments. |
|
410 |
|
411 As an example the following function sets the first output argument to |
|
412 1, the second to 2, and so on. |
|
413 |
|
414 @example |
|
415 function varargout = one_to_n () |
|
416 for i = 1:nargout |
|
417 varargout@{i@} = i; |
|
418 endfor |
|
419 endfunction |
|
420 @end example |
|
421 |
|
422 @noindent |
|
423 When called this function returns values like this |
|
424 |
|
425 @example |
|
426 @group |
|
427 [a, b, c] = one_to_n () |
|
428 @result{} a = 1 |
|
429 @result{} b = 2 |
|
430 @result{} c = 3 |
|
431 @end group |
|
432 @end example |
3294
|
433 |
4167
|
434 @node Returning From a Function |
3294
|
435 @section Returning From a Function |
|
436 |
|
437 The body of a user-defined function can contain a @code{return} statement. |
|
438 This statement returns control to the rest of the Octave program. It |
|
439 looks like this: |
|
440 |
|
441 @example |
|
442 return |
|
443 @end example |
|
444 |
|
445 Unlike the @code{return} statement in C, Octave's @code{return} |
|
446 statement cannot be used to return a value from a function. Instead, |
|
447 you must assign values to the list of return variables that are part of |
|
448 the @code{function} statement. The @code{return} statement simply makes |
|
449 it easier to exit a function from a deeply nested loop or conditional |
|
450 statement. |
|
451 |
|
452 Here is an example of a function that checks to see if any elements of a |
|
453 vector are nonzero. |
|
454 |
|
455 @example |
|
456 @group |
|
457 function retval = any_nonzero (v) |
|
458 retval = 0; |
|
459 for i = 1:length (v) |
|
460 if (v (i) != 0) |
|
461 retval = 1; |
|
462 return; |
|
463 endif |
|
464 endfor |
|
465 printf ("no nonzero elements found\n"); |
|
466 endfunction |
|
467 @end group |
|
468 @end example |
|
469 |
|
470 Note that this function could not have been written using the |
|
471 @code{break} statement to exit the loop once a nonzero value is found |
|
472 without adding extra logic to avoid printing the message if the vector |
|
473 does contain a nonzero element. |
|
474 |
5763
|
475 @deffn {Keyword} return |
3294
|
476 When Octave encounters the keyword @code{return} inside a function or |
5016
|
477 script, it returns control to the caller immediately. At the top level, |
3294
|
478 the return statement is ignored. A @code{return} statement is assumed |
|
479 at the end of every function definition. |
5763
|
480 @end deffn |
3294
|
481 |
3371
|
482 @DOCSTRING(return_last_computed_value) |
3294
|
483 |
6510
|
484 @node Default Arguments |
|
485 @section Default Arguments |
|
486 @cindex default arguments |
|
487 |
|
488 Since Octave supports variable number of input arguments, it is very useful |
|
489 to assign default values to some input arguments. When an input argument |
|
490 is declared in the argument list it is possible to assign a default |
|
491 value to the argument like this |
|
492 |
|
493 @example |
|
494 function @var{name} (@var{arg1} = @var{val1}, @dots{}) |
|
495 @var{body} |
|
496 endfunction |
|
497 @end example |
|
498 |
|
499 @noindent |
|
500 If no value is assigned to @var{arg1} by the user, it will have the |
|
501 value @var{val1}. |
|
502 |
|
503 As an example, the following function implements a variant of the classic |
|
504 ``Hello, World'' program. |
|
505 @example |
|
506 function hello (who = "World") |
|
507 printf ("Hello, %s!\n", who); |
|
508 endfunction |
|
509 @end example |
|
510 |
|
511 @noindent |
|
512 When called without an input argument the function prints the following |
|
513 @example |
|
514 @group |
|
515 hello (); |
|
516 @print{} Hello, World! |
|
517 @end group |
|
518 @end example |
|
519 |
|
520 @noindent |
|
521 and when it's called with an input argument it prints the following |
|
522 @example |
|
523 @group |
|
524 hello ("Beautiful World of Free Software"); |
|
525 @print{} Hello, Beautiful World of Free Software! |
|
526 @end group |
|
527 @end example |
|
528 |
|
529 Sometimes it is useful to explicitly tell Octave to use the default value |
|
530 of an input argument. This can be done writing a @samp{:} as the value |
|
531 of the input argument when calling the function. |
|
532 @example |
|
533 @group |
|
534 hello (:); |
|
535 @print{} Hello, World! |
|
536 @end group |
|
537 @end example |
|
538 |
4167
|
539 @node Function Files |
3294
|
540 @section Function Files |
|
541 @cindex function file |
|
542 |
|
543 Except for simple one-shot programs, it is not practical to have to |
|
544 define all the functions you need each time you need them. Instead, you |
|
545 will normally want to save them in a file so that you can easily edit |
|
546 them, and save them for use at a later time. |
|
547 |
|
548 Octave does not require you to load function definitions from files |
|
549 before using them. You simply need to put the function definitions in a |
|
550 place where Octave can find them. |
|
551 |
|
552 When Octave encounters an identifier that is undefined, it first looks |
|
553 for variables or functions that are already compiled and currently |
|
554 listed in its symbol table. If it fails to find a definition there, it |
6477
|
555 searches the list of directories specified by the internal variable |
3294
|
556 @code{LOADPATH} for files ending in @file{.m} that have the same base |
|
557 name as the undefined identifier.@footnote{The @samp{.m} suffix was |
|
558 chosen for compatibility with @sc{Matlab}.} Once Octave finds a file |
|
559 with a name that matches, the contents of the file are read. If it |
|
560 defines a @emph{single} function, it is compiled and executed. |
|
561 @xref{Script Files}, for more information about how you can define more |
|
562 than one function in a single file. |
|
563 |
|
564 When Octave defines a function from a function file, it saves the full |
|
565 name of the file it read and the time stamp on the file. After |
|
566 that, it checks the time stamp on the file every time it needs the |
|
567 function. If the time stamp indicates that the file has changed since |
|
568 the last time it was read, Octave reads it again. |
|
569 |
|
570 Checking the time stamp allows you to edit the definition of a function |
|
571 while Octave is running, and automatically use the new function |
|
572 definition without having to restart your Octave session. Checking the |
|
573 time stamp every time a function is used is rather inefficient, but it |
|
574 has to be done to ensure that the correct function definition is used. |
|
575 |
|
576 To avoid degrading performance unnecessarily by checking the time stamps |
|
577 on functions that are not likely to change, Octave assumes that function |
|
578 files in the directory tree |
|
579 @file{@var{octave-home}/share/octave/@var{version}/m} |
|
580 will not change, so it doesn't have to check their time stamps every time the |
|
581 functions defined in those files are used. This is normally a very good |
|
582 assumption and provides a significant improvement in performance for the |
|
583 function files that are distributed with Octave. |
|
584 |
|
585 If you know that your own function files will not change while you are |
|
586 running Octave, you can improve performance by setting the variable |
|
587 @code{ignore_function_time_stamp} to @code{"all"}, so that Octave will |
|
588 ignore the time stamps for all function files. Setting it to |
|
589 @code{"system"} gives the default behavior. If you set it to anything |
|
590 else, Octave will check the time stamps on all function files. |
|
591 |
5775
|
592 @c FIXME -- note about time stamps on files in NFS environments? |
3294
|
593 |
6502
|
594 @DOCSTRING(addpath) |
|
595 |
|
596 @DOCSTRING(genpath) |
|
597 |
|
598 @DOCSTRING(rmpath) |
|
599 |
|
600 @DOCSTRING(savepath) |
|
601 |
6477
|
602 @DOCSTRING(path) |
3294
|
603 |
6502
|
604 @DOCSTRING(pathdef) |
|
605 |
|
606 @DOCSTRING(pathsep) |
|
607 |
3428
|
608 @DOCSTRING(rehash) |
|
609 |
|
610 @DOCSTRING(file_in_loadpath) |
|
611 |
3371
|
612 @DOCSTRING(ignore_function_time_stamp) |
3294
|
613 |
4167
|
614 @node Script Files |
3294
|
615 @section Script Files |
|
616 |
|
617 A script file is a file containing (almost) any sequence of Octave |
|
618 commands. It is read and evaluated just as if you had typed each |
|
619 command at the Octave prompt, and provides a convenient way to perform a |
|
620 sequence of commands that do not logically belong inside a function. |
|
621 |
|
622 Unlike a function file, a script file must @emph{not} begin with the |
|
623 keyword @code{function}. If it does, Octave will assume that it is a |
|
624 function file, and that it defines a single function that should be |
|
625 evaluated as soon as it is defined. |
|
626 |
|
627 A script file also differs from a function file in that the variables |
|
628 named in a script file are not local variables, but are in the same |
|
629 scope as the other variables that are visible on the command line. |
|
630 |
|
631 Even though a script file may not begin with the @code{function} |
|
632 keyword, it is possible to define more than one function in a single |
|
633 script file and load (but not execute) all of them at once. To do |
|
634 this, the first token in the file (ignoring comments and other white |
|
635 space) must be something other than @code{function}. If you have no |
|
636 other statements to evaluate, you can use a statement that has no |
|
637 effect, like this: |
|
638 |
|
639 @example |
|
640 @group |
|
641 # Prevent Octave from thinking that this |
|
642 # is a function file: |
|
643 |
|
644 1; |
|
645 |
|
646 # Define function one: |
|
647 |
|
648 function one () |
|
649 ... |
|
650 @end group |
|
651 @end example |
|
652 |
|
653 To have Octave read and compile these functions into an internal form, |
6477
|
654 you need to make sure that the file is in Octave's @code{LOADPATH} |
|
655 (accessible through the @code{path} function), then simply type the |
|
656 base name of the file that contains the commands. (Octave uses the |
|
657 same rules to search for script files as it does to search for |
|
658 function files.) |
3294
|
659 |
|
660 If the first token in a file (ignoring comments) is @code{function}, |
|
661 Octave will compile the function and try to execute it, printing a |
|
662 message warning about any non-whitespace characters that appear after |
|
663 the function definition. |
|
664 |
|
665 Note that Octave does not try to look up the definition of any identifier |
|
666 until it needs to evaluate it. This means that Octave will compile the |
|
667 following statements if they appear in a script file, or are typed at |
|
668 the command line, |
|
669 |
|
670 @example |
|
671 @group |
|
672 # not a function file: |
|
673 1; |
|
674 function foo () |
|
675 do_something (); |
|
676 endfunction |
|
677 function do_something () |
|
678 do_something_else (); |
|
679 endfunction |
|
680 @end group |
|
681 @end example |
|
682 |
|
683 @noindent |
|
684 even though the function @code{do_something} is not defined before it is |
|
685 referenced in the function @code{foo}. This is not an error because |
|
686 Octave does not need to resolve all symbols that are referenced by a |
|
687 function until the function is actually evaluated. |
|
688 |
|
689 Since Octave doesn't look for definitions until they are needed, the |
|
690 following code will always print @samp{bar = 3} whether it is typed |
|
691 directly on the command line, read from a script file, or is part of a |
|
692 function body, even if there is a function or script file called |
6477
|
693 @file{bar.m} in Octave's path. |
3294
|
694 |
|
695 @example |
|
696 @group |
|
697 eval ("bar = 3"); |
|
698 bar |
|
699 @end group |
|
700 @end example |
|
701 |
|
702 Code like this appearing within a function body could fool Octave if |
|
703 definitions were resolved as the function was being compiled. It would |
|
704 be virtually impossible to make Octave clever enough to evaluate this |
|
705 code in a consistent fashion. The parser would have to be able to |
|
706 perform the call to @code{eval} at compile time, and that would be |
|
707 impossible unless all the references in the string to be evaluated could |
|
708 also be resolved, and requiring that would be too restrictive (the |
|
709 string might come from user input, or depend on things that are not |
|
710 known until the function is evaluated). |
|
711 |
|
712 Although Octave normally executes commands from script files that have |
|
713 the name @file{@var{file}.m}, you can use the function @code{source} to |
|
714 execute commands from any file. |
|
715 |
3371
|
716 @DOCSTRING(source) |
3294
|
717 |
4167
|
718 @node Dynamically Linked Functions |
3294
|
719 @section Dynamically Linked Functions |
|
720 @cindex dynamic linking |
|
721 |
|
722 On some systems, Octave can dynamically load and execute functions |
|
723 written in C++. Octave can only directly call functions written in C++, |
|
724 but you can also load functions written in other languages |
|
725 by calling them from a simple wrapper function written in C++. |
|
726 |
|
727 Here is an example of how to write a C++ function that Octave can load, |
|
728 with commentary. The source for this function is included in the source |
|
729 distributions of Octave, in the file @file{examples/oregonator.cc}. It |
|
730 defines the same set of differential equations that are used in the |
|
731 example problem of @ref{Ordinary Differential Equations}. By running |
|
732 that example and this one, we can compare the execution times to see |
|
733 what sort of increase in speed you can expect by using dynamically |
|
734 linked functions. |
|
735 |
|
736 The function defined in @file{oregonator.cc} contains just 8 statements, |
|
737 and is not much different than the code defined in the corresponding |
|
738 M-file (also distributed with Octave in the file |
|
739 @file{examples/oregonator.m}). |
|
740 |
|
741 Here is the complete text of @file{oregonator.cc}: |
|
742 |
|
743 @example |
|
744 @group |
|
745 #include <octave/oct.h> |
|
746 |
|
747 DEFUN_DLD (oregonator, args, , |
|
748 "The `oregonator'.") |
|
749 @{ |
|
750 ColumnVector dx (3); |
|
751 |
3760
|
752 ColumnVector x (args(0).vector_value ()); |
3294
|
753 |
|
754 dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0) |
|
755 - 8.375e-06*pow (x(0), 2)); |
|
756 |
|
757 dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27; |
|
758 |
|
759 dx(2) = 0.161*(x(0) - x(2)); |
|
760 |
|
761 return octave_value (dx); |
|
762 @} |
|
763 @end group |
|
764 @end example |
|
765 |
|
766 The first line of the file, |
|
767 |
|
768 @example |
|
769 #include <octave/oct.h> |
|
770 @end example |
|
771 |
|
772 @noindent |
|
773 includes declarations for all of Octave's internal functions that you |
|
774 will need. If you need other functions from the standard C++ or C |
|
775 libraries, you can include the necessary headers here. |
|
776 |
|
777 The next two lines |
|
778 @example |
|
779 @group |
|
780 DEFUN_DLD (oregonator, args, , |
|
781 "The `oregonator'.") |
|
782 @end group |
|
783 @end example |
|
784 |
|
785 @noindent |
|
786 declares the function. The macro @code{DEFUN_DLD} and the macros that |
|
787 it depends on are defined in the files @file{defun-dld.h}, |
|
788 @file{defun.h}, and @file{defun-int.h} (these files are included in the |
|
789 header file @file{octave/oct.h}). |
|
790 |
|
791 Note that the third parameter to @code{DEFUN_DLD} (@code{nargout}) is |
3686
|
792 not used, so it is omitted from the list of arguments in order to |
|
793 avoid the warning from gcc about an unused function parameter. |
|
794 |
|
795 The next line, |
|
796 |
|
797 @example |
|
798 ColumnVector dx (3); |
|
799 @end example |
3294
|
800 |
|
801 @noindent |
|
802 simply declares an object to store the right hand sides of the |
3686
|
803 differential equation, and the statement |
3294
|
804 |
|
805 @example |
3760
|
806 ColumnVector x (args(0).vector_value ()); |
3294
|
807 @end example |
|
808 |
|
809 @noindent |
3760
|
810 extracts a vector from the first input argument. The |
|
811 @code{vector_value} method is used so that the user of the function |
|
812 can pass either a row or column vector. The @code{ColumnVector} |
|
813 constructor is needed because the ODE class requires a column |
|
814 vector. The variable @code{args} is passed to functions defined with |
|
815 @code{DEFUN_DLD} as an @code{octave_value_list} object, which includes |
|
816 methods for getting the length of the list and extracting individual |
|
817 elements. |
3294
|
818 |
|
819 In this example, we don't check for errors, but that is not difficult. |
|
820 All of the Octave's built-in functions do some form of checking on their |
|
821 arguments, so you can check the source code for those functions for |
|
822 examples of various strategies for verifying that the correct number and |
|
823 types of arguments have been supplied. |
|
824 |
|
825 The next statements |
|
826 |
|
827 @example |
|
828 @group |
|
829 dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0) |
|
830 - 8.375e-06*pow (x(0), 2)); |
|
831 |
|
832 dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27; |
|
833 |
|
834 dx(2) = 0.161*(x(0) - x(2)); |
|
835 @end group |
|
836 @end example |
|
837 |
|
838 @noindent |
5016
|
839 define the right-hand side of the differential equation. Finally, we |
3294
|
840 can return @code{dx}: |
|
841 |
|
842 @example |
|
843 return octave_value (dx); |
|
844 @end example |
|
845 |
|
846 @noindent |
|
847 The actual return type is @code{octave_value_list}, but it is only |
|
848 necessary to convert the return type to an @code{octave_value} because |
|
849 there is a default constructor that can automatically create an object |
|
850 of that type from an @code{octave_value} object, so we can just use that |
|
851 instead. |
|
852 |
|
853 To use this file, your version of Octave must support dynamic linking. |
|
854 To find out if it does, type the command |
|
855 @kbd{octave_config_info ("dld")} at the Octave prompt. Support for |
|
856 dynamic linking is included if this command returns 1. |
|
857 |
|
858 To compile the example file, type the command @samp{mkoctfile |
|
859 oregonator.cc} at the shell prompt. The script @code{mkoctfile} should |
|
860 have been installed along with Octave. Running it will create a file |
|
861 called @file{oregonator.oct} that can be loaded by Octave. To test the |
|
862 @file{oregonator.oct} file, start Octave and type the command |
|
863 |
|
864 @example |
|
865 oregonator ([1, 2, 3], 0) |
|
866 @end example |
|
867 |
|
868 @noindent |
|
869 at the Octave prompt. Octave should respond by printing |
|
870 |
|
871 @example |
|
872 @group |
|
873 ans = |
|
874 |
|
875 77.269353 |
|
876 -0.012942 |
|
877 -0.322000 |
|
878 @end group |
|
879 @end example |
|
880 |
|
881 You can now use the @file{oregonator.oct} file just as you would the |
|
882 @code{oregonator.m} file to solve the set of differential equations. |
|
883 |
|
884 On a 133 MHz Pentium running Linux, Octave can solve the problem shown |
3402
|
885 in @ref{Ordinary Differential Equations}, in about 1.4 seconds using the |
3294
|
886 dynamically linked function, compared to about 19 seconds using the |
|
887 M-file. Similar decreases in execution time can be expected for other |
|
888 functions, particularly those that rely on functions like @code{lsode} |
|
889 that require user-supplied functions. |
|
890 |
3428
|
891 Just as for M-files, Octave will automatically reload a dynamically linked |
|
892 function when the file that defines it is more recent than the last |
|
893 time that the function was loaded. If more than one function is defined |
|
894 in a single @file{.oct} file, reloading the file may force other |
|
895 functions to be cleared and reloaded. If all the functions loaded from |
|
896 a given @file{.oct} file are cleared, Octave will automatically unload |
|
897 the @file{.oct} file. |
3294
|
898 |
5775
|
899 @c FIXME -- is there a better place for this? |
3428
|
900 |
|
901 @DOCSTRING(variables_can_hide_functions) |
|
902 |
3294
|
903 Additional examples for writing dynamically linked functions are |
|
904 available in the files in the @file{src} directory of the Octave |
|
905 distribution. Currently, this includes the files |
|
906 |
|
907 @example |
|
908 @group |
|
909 balance.cc fft2.cc inv.cc qzval.cc |
|
910 chol.cc filter.cc log.cc schur.cc |
|
911 colloc.cc find.cc lsode.cc sort.cc |
|
912 dassl.cc fsolve.cc lu.cc svd.cc |
|
913 det.cc givens.cc minmax.cc syl.cc |
|
914 eig.cc hess.cc pinv.cc |
|
915 expm.cc ifft.cc qr.cc |
|
916 fft.cc ifft2.cc quad.cc |
|
917 @end group |
|
918 @end example |
|
919 |
|
920 @noindent |
|
921 These files use the macro @code{DEFUN_DLD_BUILTIN} instead of |
|
922 @code{DEFUN_DLD}. The difference between these two macros is just that |
|
923 @code{DEFUN_DLD_BUILTIN} can define a built-in function that is not |
|
924 dynamically loaded if the operating system does not support dynamic |
|
925 linking. To define your own dynamically linked functions you should use |
|
926 @code{DEFUN_DLD}. |
|
927 |
|
928 There is currently no detailed description of all the functions that you |
|
929 can call in a built-in function. For the time being, you will have to |
|
930 read the source code for Octave. |
|
931 |
4933
|
932 @node Function Handles and Inline |
|
933 @section Function Handles and Inline |
|
934 @cindex handle, function handles |
|
935 @cindex inline, inline functions |
|
936 |
|
937 This is a place holder for the description of function handles and |
|
938 inline functions. |
|
939 |
|
940 @menu |
|
941 * Function Handles:: |
|
942 * Inline Functions:: |
|
943 @end menu |
|
944 |
|
945 @node Function Handles |
|
946 @subsection Function Handles |
|
947 |
|
948 @DOCSTRING(functions) |
|
949 |
|
950 @DOCSTRING(func2str) |
|
951 |
|
952 @DOCSTRING(str2func) |
|
953 |
|
954 @node Inline Functions |
|
955 @subsection Inline Functions |
|
956 |
|
957 @DOCSTRING(inline) |
|
958 |
|
959 @DOCSTRING(argnames) |
|
960 |
|
961 @DOCSTRING(formula) |
|
962 |
|
963 @DOCSTRING(vectorize) |
|
964 |
4167
|
965 @node Organization of Functions |
3294
|
966 @section Organization of Functions Distributed with Octave |
|
967 |
|
968 Many of Octave's standard functions are distributed as function files. |
|
969 They are loosely organized by topic, in subdirectories of |
|
970 @file{@var{octave-home}/lib/octave/@var{version}/m}, to make it easier |
|
971 to find them. |
|
972 |
|
973 The following is a list of all the function file subdirectories, and the |
|
974 types of functions you will find there. |
|
975 |
|
976 @table @file |
|
977 @item audio |
|
978 Functions for playing and recording sounds. |
|
979 |
|
980 @item control |
|
981 Functions for design and simulation of automatic control systems. |
|
982 |
|
983 @item elfun |
|
984 Elementary functions. |
|
985 |
|
986 @item general |
|
987 Miscellaneous matrix manipulations, like @code{flipud}, @code{rot90}, |
|
988 and @code{triu}, as well as other basic functions, like |
4029
|
989 @code{ismatrix}, @code{nargchk}, etc. |
3294
|
990 |
|
991 @item image |
|
992 Image processing tools. These functions require the X Window System. |
|
993 |
|
994 @item io |
|
995 Input-ouput functions. |
|
996 |
|
997 @item linear-algebra |
|
998 Functions for linear algebra. |
|
999 |
|
1000 @item miscellaneous |
|
1001 Functions that don't really belong anywhere else. |
|
1002 |
|
1003 @item plot |
|
1004 A set of functions that implement the @sc{Matlab}-like plotting functions. |
|
1005 |
|
1006 @item polynomial |
|
1007 Functions for manipulating polynomials. |
|
1008 |
|
1009 @item set |
|
1010 Functions for creating and manipulating sets of unique values. |
|
1011 |
|
1012 @item signal |
|
1013 Functions for signal processing applications. |
|
1014 |
|
1015 @item specfun |
|
1016 Special functions. |
|
1017 |
|
1018 @item special-matrix |
|
1019 Functions that create special matrix forms. |
|
1020 |
|
1021 @item startup |
|
1022 Octave's system-wide startup file. |
|
1023 |
|
1024 @item statistics |
|
1025 Statistical functions. |
|
1026 |
|
1027 @item strings |
|
1028 Miscellaneous string-handling functions. |
|
1029 |
|
1030 @item time |
|
1031 Functions related to time keeping. |
|
1032 @end table |