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