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