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 Evaluation |
3294
|
6 @chapter Evaluation |
|
7 |
|
8 Normally, you evaluate expressions simply by typing them at the Octave |
|
9 prompt, or by asking Octave to interpret commands that you have saved in |
|
10 a file. |
|
11 |
|
12 Sometimes, you may find it necessary to evaluate an expression that has |
|
13 been computed and stored in a string, or use a string as the name of a |
|
14 function to call. The @code{eval} and @code{feval} functions allow you |
|
15 to do just that, and are necessary in order to evaluate commands that |
|
16 are not known until run time, or to write functions that will need to |
|
17 call user-supplied functions. |
|
18 |
3371
|
19 @DOCSTRING(eval) |
3294
|
20 |
3371
|
21 @DOCSTRING(feval) |
3294
|
22 |
|
23 Here is a simple-minded function using @code{feval} that finds the root |
|
24 of a user-supplied function of one variable using Newton's method. |
|
25 |
|
26 @example |
|
27 @group |
|
28 @cindex Fordyce, A. P. |
|
29 @findex newtroot |
|
30 function result = newtroot (fname, x) |
|
31 |
|
32 # usage: newtroot (fname, x) |
|
33 # |
|
34 # fname : a string naming a function f(x). |
|
35 # x : initial guess |
|
36 |
|
37 delta = tol = sqrt (eps); |
|
38 maxit = 200; |
|
39 fx = feval (fname, x); |
|
40 for i = 1:maxit |
|
41 if (abs (fx) < tol) |
|
42 result = x; |
|
43 return; |
|
44 else |
|
45 fx_new = feval (fname, x + delta); |
|
46 deriv = (fx_new - fx) / delta; |
|
47 x = x - fx / deriv; |
|
48 fx = fx_new; |
|
49 endif |
|
50 endfor |
|
51 |
|
52 result = x; |
|
53 |
|
54 endfunction |
|
55 @end group |
|
56 @end example |
|
57 |
|
58 Note that this is only meant to be an example of calling user-supplied |
|
59 functions and should not be taken too seriously. In addition to using a |
|
60 more robust algorithm, any serious code would check the number and type |
|
61 of all the arguments, ensure that the supplied function really was a |
|
62 function, etc. See @xref{Predicates for Numeric Objects}, for example, |
|
63 for a list of predicates for numeric objects, and @xref{Status of |
|
64 Variables}, for a description of the @code{exist} function. |