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 |
|
5 @node Functions and Scripts, Error Handling, Statements, Top |
|
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:: |
|
23 * Function Files:: |
|
24 * Script Files:: |
|
25 * Dynamically Linked Functions:: |
|
26 * Organization of Functions:: |
|
27 @end menu |
|
28 |
|
29 @node Defining Functions, Multiple Return Values, Functions and Scripts, Functions and Scripts |
|
30 @section Defining Functions |
|
31 @cindex @code{function} statement |
|
32 @cindex @code{endfunction} statement |
|
33 |
|
34 In its simplest form, the definition of a function named @var{name} |
|
35 looks like this: |
|
36 |
|
37 @example |
|
38 @group |
|
39 function @var{name} |
|
40 @var{body} |
|
41 endfunction |
|
42 @end group |
|
43 @end example |
|
44 |
|
45 @noindent |
|
46 A valid function name is like a valid variable name: a sequence of |
|
47 letters, digits and underscores, not starting with a digit. Functions |
|
48 share the same pool of names as variables. |
|
49 |
|
50 The function @var{body} consists of Octave statements. It is the |
|
51 most important part of the definition, because it says what the function |
|
52 should actually @emph{do}. |
|
53 |
|
54 For example, here is a function that, when executed, will ring the bell |
|
55 on your terminal (assuming that it is possible to do so): |
|
56 |
|
57 @example |
|
58 @group |
|
59 function wakeup |
|
60 printf ("\a"); |
|
61 endfunction |
|
62 @end group |
|
63 @end example |
|
64 |
|
65 The @code{printf} statement (@pxref{Input and Output}) simply tells |
|
66 Octave to print the string @code{"\a"}. The special character @samp{\a} |
|
67 stands for the alert character (ASCII 7). @xref{Strings}. |
|
68 |
|
69 Once this function is defined, you can ask Octave to evaluate it by |
|
70 typing the name of the function. |
|
71 |
|
72 Normally, you will want to pass some information to the functions you |
|
73 define. The syntax for passing parameters to a function in Octave is |
|
74 |
|
75 @example |
|
76 @group |
|
77 function @var{name} (@var{arg-list}) |
|
78 @var{body} |
|
79 endfunction |
|
80 @end group |
|
81 @end example |
|
82 |
|
83 @noindent |
|
84 where @var{arg-list} is a comma-separated list of the function's |
|
85 arguments. When the function is called, the argument names are used to |
|
86 hold the argument values given in the call. The list of arguments may |
|
87 be empty, in which case this form is equivalent to the one shown above. |
|
88 |
|
89 To print a message along with ringing the bell, you might modify the |
|
90 @code{beep} to look like this: |
|
91 |
|
92 @example |
|
93 @group |
|
94 function wakeup (message) |
|
95 printf ("\a%s\n", message); |
|
96 endfunction |
|
97 @end group |
|
98 @end example |
|
99 |
|
100 Calling this function using a statement like this |
|
101 |
|
102 @example |
|
103 wakeup ("Rise and shine!"); |
|
104 @end example |
|
105 |
|
106 @noindent |
|
107 will cause Octave to ring your terminal's bell and print the message |
|
108 @samp{Rise and shine!}, followed by a newline character (the @samp{\n} |
|
109 in the first argument to the @code{printf} statement). |
|
110 |
|
111 In most cases, you will also want to get some information back from the |
|
112 functions you define. Here is the syntax for writing a function that |
|
113 returns a single value: |
|
114 |
|
115 @example |
|
116 @group |
|
117 function @var{ret-var} = @var{name} (@var{arg-list}) |
|
118 @var{body} |
|
119 endfunction |
|
120 @end group |
|
121 @end example |
|
122 |
|
123 @noindent |
|
124 The symbol @var{ret-var} is the name of the variable that will hold the |
|
125 value to be returned by the function. This variable must be defined |
|
126 before the end of the function body in order for the function to return |
|
127 a value. |
|
128 |
|
129 Variables used in the body of a function are local to the |
|
130 function. Variables named in @var{arg-list} and @var{ret-var} are also |
|
131 local to the function. @xref{Global Variables}, for information about |
|
132 how to access global variables inside a function. |
|
133 |
|
134 For example, here is a function that computes the average of the |
|
135 elements of a vector: |
|
136 |
|
137 @example |
|
138 @group |
|
139 function retval = avg (v) |
|
140 retval = sum (v) / length (v); |
|
141 endfunction |
|
142 @end group |
|
143 @end example |
|
144 |
|
145 If we had written @code{avg} like this instead, |
|
146 |
|
147 @example |
|
148 @group |
|
149 function retval = avg (v) |
4029
|
150 if (isvector (v)) |
3294
|
151 retval = sum (v) / length (v); |
|
152 endif |
|
153 endfunction |
|
154 @end group |
|
155 @end example |
|
156 |
|
157 @noindent |
|
158 and then called the function with a matrix instead of a vector as the |
|
159 argument, Octave would have printed an error message like this: |
|
160 |
|
161 @example |
|
162 @group |
|
163 error: `retval' undefined near line 1 column 10 |
|
164 error: evaluating index expression near line 7, column 1 |
|
165 @end group |
|
166 @end example |
|
167 |
|
168 @noindent |
|
169 because the body of the @code{if} statement was never executed, and |
|
170 @code{retval} was never defined. To prevent obscure errors like this, |
|
171 it is a good idea to always make sure that the return variables will |
|
172 always have values, and to produce meaningful error messages when |
|
173 problems are encountered. For example, @code{avg} could have been |
|
174 written like this: |
|
175 |
|
176 @example |
|
177 @group |
|
178 function retval = avg (v) |
|
179 retval = 0; |
4029
|
180 if (isvector (v)) |
3294
|
181 retval = sum (v) / length (v); |
|
182 else |
|
183 error ("avg: expecting vector argument"); |
|
184 endif |
|
185 endfunction |
|
186 @end group |
|
187 @end example |
|
188 |
|
189 There is still one additional problem with this function. What if it is |
|
190 called without an argument? Without additional error checking, Octave |
|
191 will probably print an error message that won't really help you track |
|
192 down the source of the error. To allow you to catch errors like this, |
|
193 Octave provides each function with an automatic variable called |
|
194 @code{nargin}. Each time a function is called, @code{nargin} is |
|
195 automatically initialized to the number of arguments that have actually |
|
196 been passed to the function. For example, we might rewrite the |
|
197 @code{avg} function like this: |
|
198 |
|
199 @example |
|
200 @group |
|
201 function retval = avg (v) |
|
202 retval = 0; |
|
203 if (nargin != 1) |
|
204 usage ("avg (vector)"); |
|
205 endif |
4029
|
206 if (isvector (v)) |
3294
|
207 retval = sum (v) / length (v); |
|
208 else |
|
209 error ("avg: expecting vector argument"); |
|
210 endif |
|
211 endfunction |
|
212 @end group |
|
213 @end example |
|
214 |
|
215 Although Octave does not automatically report an error if you call a |
|
216 function with more arguments than expected, doing so probably indicates |
|
217 that something is wrong. Octave also does not automatically report an |
|
218 error if a function is called with too few arguments, but any attempt to |
|
219 use a variable that has not been given a value will result in an error. |
|
220 To avoid such problems and to provide useful messages, we check for both |
|
221 possibilities and issue our own error message. |
|
222 |
|
223 @defvr {Automatic Variable} nargin |
|
224 When a function is called, this local variable is automatically |
|
225 initialized to the number of arguments passed to the function. At the |
|
226 top level, @code{nargin} holds the number of command line arguments that |
|
227 were passed to Octave. |
|
228 @end defvr |
|
229 |
3371
|
230 @DOCSTRING(silent_functions) |
3294
|
231 |
3371
|
232 @DOCSTRING(warn_missing_semicolon) |
3294
|
233 |
|
234 @node Multiple Return Values, Variable-length Argument Lists, Defining Functions, Functions and Scripts |
|
235 @section Multiple Return Values |
|
236 |
|
237 Unlike many other computer languages, Octave allows you to define |
|
238 functions that return more than one value. The syntax for defining |
|
239 functions that return multiple values is |
|
240 |
|
241 @example |
|
242 function [@var{ret-list}] = @var{name} (@var{arg-list}) |
|
243 @var{body} |
|
244 endfunction |
|
245 @end example |
|
246 |
|
247 @noindent |
|
248 where @var{name}, @var{arg-list}, and @var{body} have the same meaning |
|
249 as before, and @var{ret-list} is a comma-separated list of variable |
|
250 names that will hold the values returned from the function. The list of |
|
251 return values must have at least one element. If @var{ret-list} has |
|
252 only one element, this form of the @code{function} statement is |
|
253 equivalent to the form described in the previous section. |
|
254 |
|
255 Here is an example of a function that returns two values, the maximum |
|
256 element of a vector and the index of its first occurrence in the vector. |
|
257 |
|
258 @example |
|
259 @group |
|
260 function [max, idx] = vmax (v) |
|
261 idx = 1; |
|
262 max = v (idx); |
|
263 for i = 2:length (v) |
|
264 if (v (i) > max) |
|
265 max = v (i); |
|
266 idx = i; |
|
267 endif |
|
268 endfor |
|
269 endfunction |
|
270 @end group |
|
271 @end example |
|
272 |
|
273 In this particular case, the two values could have been returned as |
|
274 elements of a single array, but that is not always possible or |
|
275 convenient. The values to be returned may not have compatible |
|
276 dimensions, and it is often desirable to give the individual return |
|
277 values distinct names. |
|
278 |
|
279 In addition to setting @code{nargin} each time a function is called, |
|
280 Octave also automatically initializes @code{nargout} to the number of |
|
281 values that are expected to be returned. This allows you to write |
|
282 functions that behave differently depending on the number of values that |
|
283 the user of the function has requested. The implicit assignment to the |
|
284 built-in variable @code{ans} does not figure in the count of output |
|
285 arguments, so the value of @code{nargout} may be zero. |
|
286 |
|
287 The @code{svd} and @code{lu} functions are examples of built-in |
|
288 functions that behave differently depending on the value of |
|
289 @code{nargout}. |
|
290 |
|
291 It is possible to write functions that only set some return values. For |
|
292 example, calling the function |
|
293 |
|
294 @example |
|
295 function [x, y, z] = f () |
|
296 x = 1; |
|
297 z = 2; |
|
298 endfunction |
|
299 @end example |
|
300 |
|
301 @noindent |
|
302 as |
|
303 |
|
304 @example |
|
305 [a, b, c] = f () |
|
306 @end example |
|
307 |
|
308 @noindent |
|
309 produces: |
|
310 |
|
311 @example |
|
312 a = 1 |
|
313 |
|
314 b = [](0x0) |
|
315 |
|
316 c = 2 |
|
317 @end example |
|
318 |
|
319 @noindent |
|
320 provided that the built-in variable @code{define_all_return_values} is |
|
321 nonzero and the value of @code{default_return_value} is @samp{[]}. |
|
322 @xref{Summary of Built-in Variables}. |
|
323 |
|
324 @defvr {Automatic Variable} nargout |
|
325 When a function is called, this local variable is automatically |
|
326 initialized to the number of arguments expected to be returned. For |
|
327 example, |
|
328 |
|
329 @example |
|
330 f () |
|
331 @end example |
|
332 |
|
333 @noindent |
|
334 will result in @code{nargout} being set to 0 inside the function |
|
335 @code{f} and |
|
336 |
|
337 @example |
|
338 [s, t] = f () |
|
339 @end example |
|
340 |
|
341 @noindent |
|
342 will result in @code{nargout} being set to 2 inside the function |
|
343 @code{f}. |
|
344 |
|
345 At the top level, @code{nargout} is undefined. |
|
346 @end defvr |
|
347 |
3371
|
348 @DOCSTRING(default_return_value) |
3294
|
349 |
3371
|
350 @DOCSTRING(define_all_return_values) |
3294
|
351 |
3371
|
352 @DOCSTRING(nargchk) |
3294
|
353 |
|
354 @node Variable-length Argument Lists, Variable-length Return Lists, Multiple Return Values, Functions and Scripts |
|
355 @section Variable-length Argument Lists |
|
356 @cindex Variable-length argument lists |
|
357 @cindex @code{...} |
|
358 |
|
359 Octave has a real mechanism for handling functions that take an |
|
360 unspecified number of arguments, so it is not necessary to place an |
|
361 upper bound on the number of optional arguments that a function can |
|
362 accept. |
|
363 |
|
364 @c XXX FIXME XXX -- should we add a note about why this feature is not |
|
365 @c compatible with Matlab 5? |
|
366 |
|
367 Here is an example of a function that uses the new syntax to print a |
|
368 header followed by an unspecified number of values: |
|
369 |
|
370 @example |
|
371 function foo (heading, ...) |
|
372 disp (heading); |
|
373 va_start (); |
|
374 ## Pre-decrement to skip `heading' arg. |
|
375 while (--nargin) |
|
376 disp (va_arg ()); |
|
377 endwhile |
|
378 endfunction |
|
379 @end example |
|
380 |
|
381 The ellipsis that marks the variable argument list may only appear once |
|
382 and must be the last element in the list of arguments. |
|
383 |
3371
|
384 @DOCSTRING(va_arg) |
3294
|
385 |
3371
|
386 @DOCSTRING(va_start) |
3294
|
387 |
|
388 Sometimes it is useful to be able to pass all unnamed arguments to |
|
389 another function. The keyword @var{all_va_args} makes this very easy to |
|
390 do. For example, |
|
391 |
|
392 @example |
|
393 @group |
|
394 function f (...) |
|
395 while (nargin--) |
|
396 disp (va_arg ()) |
|
397 endwhile |
|
398 endfunction |
|
399 |
|
400 function g (...) |
|
401 f ("begin", all_va_args, "end") |
|
402 endfunction |
|
403 |
|
404 g (1, 2, 3) |
|
405 |
|
406 @print{} begin |
|
407 @print{} 1 |
|
408 @print{} 2 |
|
409 @print{} 3 |
|
410 @print{} end |
|
411 @end group |
|
412 @end example |
|
413 |
|
414 @defvr {Keyword} all_va_args |
|
415 This keyword stands for the entire list of optional argument, so it is |
|
416 possible to use it more than once within the same function without |
|
417 having to call @code{va_start}. It can only be used within functions |
|
418 that take a variable number of arguments. It is an error to use it in |
|
419 other contexts. |
|
420 @end defvr |
|
421 |
|
422 @node Variable-length Return Lists, Returning From a Function, Variable-length Argument Lists, Functions and Scripts |
|
423 @section Variable-length Return Lists |
|
424 @cindex Variable-length return lists |
|
425 @cindex @code{...} |
|
426 |
|
427 Octave also has a real mechanism for handling functions that return an |
|
428 unspecified number of values, so it is no longer necessary to place an |
|
429 upper bound on the number of outputs that a function can produce. |
|
430 |
|
431 Here is an example of a function that uses a variable-length return list |
|
432 to produce @var{n} values: |
|
433 |
|
434 @example |
|
435 @group |
|
436 function [...] = f (n, x) |
|
437 for i = 1:n |
|
438 vr_val (i * x); |
|
439 endfor |
|
440 endfunction |
|
441 |
|
442 [dos, quatro] = f (2, 2) |
|
443 @result{} dos = 2 |
|
444 @result{} quatro = 4 |
|
445 @end group |
|
446 @end example |
|
447 |
|
448 As with variable argument lists, the ellipsis that marks the variable |
|
449 return list may only appear once and must be the last element in the |
|
450 list of returned values. |
|
451 |
3371
|
452 @DOCSTRING(vr_val) |
3294
|
453 |
|
454 @node Returning From a Function, Function Files, Variable-length Return Lists, Functions and Scripts |
|
455 @section Returning From a Function |
|
456 |
|
457 The body of a user-defined function can contain a @code{return} statement. |
|
458 This statement returns control to the rest of the Octave program. It |
|
459 looks like this: |
|
460 |
|
461 @example |
|
462 return |
|
463 @end example |
|
464 |
|
465 Unlike the @code{return} statement in C, Octave's @code{return} |
|
466 statement cannot be used to return a value from a function. Instead, |
|
467 you must assign values to the list of return variables that are part of |
|
468 the @code{function} statement. The @code{return} statement simply makes |
|
469 it easier to exit a function from a deeply nested loop or conditional |
|
470 statement. |
|
471 |
|
472 Here is an example of a function that checks to see if any elements of a |
|
473 vector are nonzero. |
|
474 |
|
475 @example |
|
476 @group |
|
477 function retval = any_nonzero (v) |
|
478 retval = 0; |
|
479 for i = 1:length (v) |
|
480 if (v (i) != 0) |
|
481 retval = 1; |
|
482 return; |
|
483 endif |
|
484 endfor |
|
485 printf ("no nonzero elements found\n"); |
|
486 endfunction |
|
487 @end group |
|
488 @end example |
|
489 |
|
490 Note that this function could not have been written using the |
|
491 @code{break} statement to exit the loop once a nonzero value is found |
|
492 without adding extra logic to avoid printing the message if the vector |
|
493 does contain a nonzero element. |
|
494 |
|
495 @defvr {Keyword} return |
|
496 When Octave encounters the keyword @code{return} inside a function or |
|
497 script, it returns control to be caller immediately. At the top level, |
|
498 the return statement is ignored. A @code{return} statement is assumed |
|
499 at the end of every function definition. |
|
500 @end defvr |
|
501 |
3371
|
502 @DOCSTRING(return_last_computed_value) |
3294
|
503 |
|
504 @node Function Files, Script Files, Returning From a Function, Functions and Scripts |
|
505 @section Function Files |
|
506 @cindex function file |
|
507 |
|
508 Except for simple one-shot programs, it is not practical to have to |
|
509 define all the functions you need each time you need them. Instead, you |
|
510 will normally want to save them in a file so that you can easily edit |
|
511 them, and save them for use at a later time. |
|
512 |
|
513 Octave does not require you to load function definitions from files |
|
514 before using them. You simply need to put the function definitions in a |
|
515 place where Octave can find them. |
|
516 |
|
517 When Octave encounters an identifier that is undefined, it first looks |
|
518 for variables or functions that are already compiled and currently |
|
519 listed in its symbol table. If it fails to find a definition there, it |
|
520 searches the list of directories specified by the built-in variable |
|
521 @code{LOADPATH} for files ending in @file{.m} that have the same base |
|
522 name as the undefined identifier.@footnote{The @samp{.m} suffix was |
|
523 chosen for compatibility with @sc{Matlab}.} Once Octave finds a file |
|
524 with a name that matches, the contents of the file are read. If it |
|
525 defines a @emph{single} function, it is compiled and executed. |
|
526 @xref{Script Files}, for more information about how you can define more |
|
527 than one function in a single file. |
|
528 |
|
529 When Octave defines a function from a function file, it saves the full |
|
530 name of the file it read and the time stamp on the file. After |
|
531 that, it checks the time stamp on the file every time it needs the |
|
532 function. If the time stamp indicates that the file has changed since |
|
533 the last time it was read, Octave reads it again. |
|
534 |
|
535 Checking the time stamp allows you to edit the definition of a function |
|
536 while Octave is running, and automatically use the new function |
|
537 definition without having to restart your Octave session. Checking the |
|
538 time stamp every time a function is used is rather inefficient, but it |
|
539 has to be done to ensure that the correct function definition is used. |
|
540 |
|
541 To avoid degrading performance unnecessarily by checking the time stamps |
|
542 on functions that are not likely to change, Octave assumes that function |
|
543 files in the directory tree |
|
544 @file{@var{octave-home}/share/octave/@var{version}/m} |
|
545 will not change, so it doesn't have to check their time stamps every time the |
|
546 functions defined in those files are used. This is normally a very good |
|
547 assumption and provides a significant improvement in performance for the |
|
548 function files that are distributed with Octave. |
|
549 |
|
550 If you know that your own function files will not change while you are |
|
551 running Octave, you can improve performance by setting the variable |
|
552 @code{ignore_function_time_stamp} to @code{"all"}, so that Octave will |
|
553 ignore the time stamps for all function files. Setting it to |
|
554 @code{"system"} gives the default behavior. If you set it to anything |
|
555 else, Octave will check the time stamps on all function files. |
|
556 |
|
557 @c XXX FIXME XXX -- note about time stamps on files in NFS environments? |
|
558 |
3371
|
559 @DOCSTRING(DEFAULT_LOADPATH) |
3294
|
560 |
3371
|
561 @DOCSTRING(LOADPATH) |
3294
|
562 |
3428
|
563 @DOCSTRING(rehash) |
|
564 |
|
565 @DOCSTRING(file_in_loadpath) |
|
566 |
3371
|
567 @DOCSTRING(ignore_function_time_stamp) |
3294
|
568 |
3371
|
569 @DOCSTRING(warn_function_name_clash) |
3294
|
570 |
3428
|
571 @DOCSTRING(warn_future_time_stamp) |
|
572 |
3294
|
573 @node Script Files, Dynamically Linked Functions, Function Files, Functions and Scripts |
|
574 @section Script Files |
|
575 |
|
576 A script file is a file containing (almost) any sequence of Octave |
|
577 commands. It is read and evaluated just as if you had typed each |
|
578 command at the Octave prompt, and provides a convenient way to perform a |
|
579 sequence of commands that do not logically belong inside a function. |
|
580 |
|
581 Unlike a function file, a script file must @emph{not} begin with the |
|
582 keyword @code{function}. If it does, Octave will assume that it is a |
|
583 function file, and that it defines a single function that should be |
|
584 evaluated as soon as it is defined. |
|
585 |
|
586 A script file also differs from a function file in that the variables |
|
587 named in a script file are not local variables, but are in the same |
|
588 scope as the other variables that are visible on the command line. |
|
589 |
|
590 Even though a script file may not begin with the @code{function} |
|
591 keyword, it is possible to define more than one function in a single |
|
592 script file and load (but not execute) all of them at once. To do |
|
593 this, the first token in the file (ignoring comments and other white |
|
594 space) must be something other than @code{function}. If you have no |
|
595 other statements to evaluate, you can use a statement that has no |
|
596 effect, like this: |
|
597 |
|
598 @example |
|
599 @group |
|
600 # Prevent Octave from thinking that this |
|
601 # is a function file: |
|
602 |
|
603 1; |
|
604 |
|
605 # Define function one: |
|
606 |
|
607 function one () |
|
608 ... |
|
609 @end group |
|
610 @end example |
|
611 |
|
612 To have Octave read and compile these functions into an internal form, |
|
613 you need to make sure that the file is in Octave's @code{LOADPATH}, then |
|
614 simply type the base name of the file that contains the commands. |
|
615 (Octave uses the same rules to search for script files as it does to |
|
616 search for function files.) |
|
617 |
|
618 If the first token in a file (ignoring comments) is @code{function}, |
|
619 Octave will compile the function and try to execute it, printing a |
|
620 message warning about any non-whitespace characters that appear after |
|
621 the function definition. |
|
622 |
|
623 Note that Octave does not try to look up the definition of any identifier |
|
624 until it needs to evaluate it. This means that Octave will compile the |
|
625 following statements if they appear in a script file, or are typed at |
|
626 the command line, |
|
627 |
|
628 @example |
|
629 @group |
|
630 # not a function file: |
|
631 1; |
|
632 function foo () |
|
633 do_something (); |
|
634 endfunction |
|
635 function do_something () |
|
636 do_something_else (); |
|
637 endfunction |
|
638 @end group |
|
639 @end example |
|
640 |
|
641 @noindent |
|
642 even though the function @code{do_something} is not defined before it is |
|
643 referenced in the function @code{foo}. This is not an error because |
|
644 Octave does not need to resolve all symbols that are referenced by a |
|
645 function until the function is actually evaluated. |
|
646 |
|
647 Since Octave doesn't look for definitions until they are needed, the |
|
648 following code will always print @samp{bar = 3} whether it is typed |
|
649 directly on the command line, read from a script file, or is part of a |
|
650 function body, even if there is a function or script file called |
|
651 @file{bar.m} in Octave's @code{LOADPATH}. |
|
652 |
|
653 @example |
|
654 @group |
|
655 eval ("bar = 3"); |
|
656 bar |
|
657 @end group |
|
658 @end example |
|
659 |
|
660 Code like this appearing within a function body could fool Octave if |
|
661 definitions were resolved as the function was being compiled. It would |
|
662 be virtually impossible to make Octave clever enough to evaluate this |
|
663 code in a consistent fashion. The parser would have to be able to |
|
664 perform the call to @code{eval} at compile time, and that would be |
|
665 impossible unless all the references in the string to be evaluated could |
|
666 also be resolved, and requiring that would be too restrictive (the |
|
667 string might come from user input, or depend on things that are not |
|
668 known until the function is evaluated). |
|
669 |
|
670 Although Octave normally executes commands from script files that have |
|
671 the name @file{@var{file}.m}, you can use the function @code{source} to |
|
672 execute commands from any file. |
|
673 |
3371
|
674 @DOCSTRING(source) |
3294
|
675 |
|
676 @node Dynamically Linked Functions, Organization of Functions, Script Files, Functions and Scripts |
|
677 @section Dynamically Linked Functions |
|
678 @cindex dynamic linking |
|
679 |
|
680 On some systems, Octave can dynamically load and execute functions |
|
681 written in C++. Octave can only directly call functions written in C++, |
|
682 but you can also load functions written in other languages |
|
683 by calling them from a simple wrapper function written in C++. |
|
684 |
|
685 Here is an example of how to write a C++ function that Octave can load, |
|
686 with commentary. The source for this function is included in the source |
|
687 distributions of Octave, in the file @file{examples/oregonator.cc}. It |
|
688 defines the same set of differential equations that are used in the |
|
689 example problem of @ref{Ordinary Differential Equations}. By running |
|
690 that example and this one, we can compare the execution times to see |
|
691 what sort of increase in speed you can expect by using dynamically |
|
692 linked functions. |
|
693 |
|
694 The function defined in @file{oregonator.cc} contains just 8 statements, |
|
695 and is not much different than the code defined in the corresponding |
|
696 M-file (also distributed with Octave in the file |
|
697 @file{examples/oregonator.m}). |
|
698 |
|
699 Here is the complete text of @file{oregonator.cc}: |
|
700 |
|
701 just |
|
702 |
|
703 @example |
|
704 @group |
|
705 #include <octave/oct.h> |
|
706 |
|
707 DEFUN_DLD (oregonator, args, , |
|
708 "The `oregonator'.") |
|
709 @{ |
|
710 ColumnVector dx (3); |
|
711 |
3760
|
712 ColumnVector x (args(0).vector_value ()); |
3294
|
713 |
|
714 dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0) |
|
715 - 8.375e-06*pow (x(0), 2)); |
|
716 |
|
717 dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27; |
|
718 |
|
719 dx(2) = 0.161*(x(0) - x(2)); |
|
720 |
|
721 return octave_value (dx); |
|
722 @} |
|
723 @end group |
|
724 @end example |
|
725 |
|
726 The first line of the file, |
|
727 |
|
728 @example |
|
729 #include <octave/oct.h> |
|
730 @end example |
|
731 |
|
732 @noindent |
|
733 includes declarations for all of Octave's internal functions that you |
|
734 will need. If you need other functions from the standard C++ or C |
|
735 libraries, you can include the necessary headers here. |
|
736 |
|
737 The next two lines |
|
738 @example |
|
739 @group |
|
740 DEFUN_DLD (oregonator, args, , |
|
741 "The `oregonator'.") |
|
742 @end group |
|
743 @end example |
|
744 |
|
745 @noindent |
|
746 declares the function. The macro @code{DEFUN_DLD} and the macros that |
|
747 it depends on are defined in the files @file{defun-dld.h}, |
|
748 @file{defun.h}, and @file{defun-int.h} (these files are included in the |
|
749 header file @file{octave/oct.h}). |
|
750 |
|
751 Note that the third parameter to @code{DEFUN_DLD} (@code{nargout}) is |
3686
|
752 not used, so it is omitted from the list of arguments in order to |
|
753 avoid the warning from gcc about an unused function parameter. |
|
754 |
|
755 The next line, |
|
756 |
|
757 @example |
|
758 ColumnVector dx (3); |
|
759 @end example |
3294
|
760 |
|
761 @noindent |
|
762 simply declares an object to store the right hand sides of the |
3686
|
763 differential equation, and the statement |
3294
|
764 |
|
765 @example |
3760
|
766 ColumnVector x (args(0).vector_value ()); |
3294
|
767 @end example |
|
768 |
|
769 @noindent |
3760
|
770 extracts a vector from the first input argument. The |
|
771 @code{vector_value} method is used so that the user of the function |
|
772 can pass either a row or column vector. The @code{ColumnVector} |
|
773 constructor is needed because the ODE class requires a column |
|
774 vector. The variable @code{args} is passed to functions defined with |
|
775 @code{DEFUN_DLD} as an @code{octave_value_list} object, which includes |
|
776 methods for getting the length of the list and extracting individual |
|
777 elements. |
3294
|
778 |
|
779 In this example, we don't check for errors, but that is not difficult. |
|
780 All of the Octave's built-in functions do some form of checking on their |
|
781 arguments, so you can check the source code for those functions for |
|
782 examples of various strategies for verifying that the correct number and |
|
783 types of arguments have been supplied. |
|
784 |
|
785 The next statements |
|
786 |
|
787 @example |
|
788 @group |
|
789 ColumnVector dx (3); |
|
790 |
|
791 dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0) |
|
792 - 8.375e-06*pow (x(0), 2)); |
|
793 |
|
794 dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27; |
|
795 |
|
796 dx(2) = 0.161*(x(0) - x(2)); |
|
797 @end group |
|
798 @end example |
|
799 |
|
800 @noindent |
|
801 define the right hand side of the differential equation. Finally, we |
|
802 can return @code{dx}: |
|
803 |
|
804 @example |
|
805 return octave_value (dx); |
|
806 @end example |
|
807 |
|
808 @noindent |
|
809 The actual return type is @code{octave_value_list}, but it is only |
|
810 necessary to convert the return type to an @code{octave_value} because |
|
811 there is a default constructor that can automatically create an object |
|
812 of that type from an @code{octave_value} object, so we can just use that |
|
813 instead. |
|
814 |
|
815 To use this file, your version of Octave must support dynamic linking. |
|
816 To find out if it does, type the command |
|
817 @kbd{octave_config_info ("dld")} at the Octave prompt. Support for |
|
818 dynamic linking is included if this command returns 1. |
|
819 |
|
820 To compile the example file, type the command @samp{mkoctfile |
|
821 oregonator.cc} at the shell prompt. The script @code{mkoctfile} should |
|
822 have been installed along with Octave. Running it will create a file |
|
823 called @file{oregonator.oct} that can be loaded by Octave. To test the |
|
824 @file{oregonator.oct} file, start Octave and type the command |
|
825 |
|
826 @example |
|
827 oregonator ([1, 2, 3], 0) |
|
828 @end example |
|
829 |
|
830 @noindent |
|
831 at the Octave prompt. Octave should respond by printing |
|
832 |
|
833 @example |
|
834 @group |
|
835 ans = |
|
836 |
|
837 77.269353 |
|
838 -0.012942 |
|
839 -0.322000 |
|
840 @end group |
|
841 @end example |
|
842 |
|
843 You can now use the @file{oregonator.oct} file just as you would the |
|
844 @code{oregonator.m} file to solve the set of differential equations. |
|
845 |
|
846 On a 133 MHz Pentium running Linux, Octave can solve the problem shown |
3402
|
847 in @ref{Ordinary Differential Equations}, in about 1.4 seconds using the |
3294
|
848 dynamically linked function, compared to about 19 seconds using the |
|
849 M-file. Similar decreases in execution time can be expected for other |
|
850 functions, particularly those that rely on functions like @code{lsode} |
|
851 that require user-supplied functions. |
|
852 |
3428
|
853 Just as for M-files, Octave will automatically reload a dynamically linked |
|
854 function when the file that defines it is more recent than the last |
|
855 time that the function was loaded. If more than one function is defined |
|
856 in a single @file{.oct} file, reloading the file may force other |
|
857 functions to be cleared and reloaded. If all the functions loaded from |
|
858 a given @file{.oct} file are cleared, Octave will automatically unload |
|
859 the @file{.oct} file. |
3294
|
860 |
3371
|
861 @DOCSTRING(warn_reload_forces_clear) |
3294
|
862 |
3428
|
863 @c XXX FIXME XXX -- is there a better place for this? |
|
864 |
|
865 @DOCSTRING(variables_can_hide_functions) |
|
866 |
3294
|
867 Additional examples for writing dynamically linked functions are |
|
868 available in the files in the @file{src} directory of the Octave |
|
869 distribution. Currently, this includes the files |
|
870 |
|
871 @example |
|
872 @group |
|
873 balance.cc fft2.cc inv.cc qzval.cc |
|
874 chol.cc filter.cc log.cc schur.cc |
|
875 colloc.cc find.cc lsode.cc sort.cc |
|
876 dassl.cc fsolve.cc lu.cc svd.cc |
|
877 det.cc givens.cc minmax.cc syl.cc |
|
878 eig.cc hess.cc pinv.cc |
|
879 expm.cc ifft.cc qr.cc |
|
880 fft.cc ifft2.cc quad.cc |
|
881 @end group |
|
882 @end example |
|
883 |
|
884 @noindent |
|
885 These files use the macro @code{DEFUN_DLD_BUILTIN} instead of |
|
886 @code{DEFUN_DLD}. The difference between these two macros is just that |
|
887 @code{DEFUN_DLD_BUILTIN} can define a built-in function that is not |
|
888 dynamically loaded if the operating system does not support dynamic |
|
889 linking. To define your own dynamically linked functions you should use |
|
890 @code{DEFUN_DLD}. |
|
891 |
|
892 There is currently no detailed description of all the functions that you |
|
893 can call in a built-in function. For the time being, you will have to |
|
894 read the source code for Octave. |
|
895 |
|
896 @node Organization of Functions, , Dynamically Linked Functions, Functions and Scripts |
|
897 @section Organization of Functions Distributed with Octave |
|
898 |
|
899 Many of Octave's standard functions are distributed as function files. |
|
900 They are loosely organized by topic, in subdirectories of |
|
901 @file{@var{octave-home}/lib/octave/@var{version}/m}, to make it easier |
|
902 to find them. |
|
903 |
|
904 The following is a list of all the function file subdirectories, and the |
|
905 types of functions you will find there. |
|
906 |
|
907 @table @file |
|
908 @item audio |
|
909 Functions for playing and recording sounds. |
|
910 |
|
911 @item control |
|
912 Functions for design and simulation of automatic control systems. |
|
913 |
|
914 @item elfun |
|
915 Elementary functions. |
|
916 |
|
917 @item general |
|
918 Miscellaneous matrix manipulations, like @code{flipud}, @code{rot90}, |
|
919 and @code{triu}, as well as other basic functions, like |
4029
|
920 @code{ismatrix}, @code{nargchk}, etc. |
3294
|
921 |
|
922 @item image |
|
923 Image processing tools. These functions require the X Window System. |
|
924 |
|
925 @item io |
|
926 Input-ouput functions. |
|
927 |
|
928 @item linear-algebra |
|
929 Functions for linear algebra. |
|
930 |
|
931 @item miscellaneous |
|
932 Functions that don't really belong anywhere else. |
|
933 |
|
934 @item plot |
|
935 A set of functions that implement the @sc{Matlab}-like plotting functions. |
|
936 |
|
937 @item polynomial |
|
938 Functions for manipulating polynomials. |
|
939 |
|
940 @item set |
|
941 Functions for creating and manipulating sets of unique values. |
|
942 |
|
943 @item signal |
|
944 Functions for signal processing applications. |
|
945 |
|
946 @item specfun |
|
947 Special functions. |
|
948 |
|
949 @item special-matrix |
|
950 Functions that create special matrix forms. |
|
951 |
|
952 @item startup |
|
953 Octave's system-wide startup file. |
|
954 |
|
955 @item statistics |
|
956 Statistical functions. |
|
957 |
|
958 @item strings |
|
959 Miscellaneous string-handling functions. |
|
960 |
|
961 @item time |
|
962 Functions related to time keeping. |
|
963 @end table |