File: eval.texi

package info (click to toggle)
octave 10.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 145,388 kB
  • sloc: cpp: 335,976; ansic: 82,241; fortran: 20,963; objc: 9,402; sh: 8,756; yacc: 4,392; lex: 4,333; perl: 1,544; java: 1,366; awk: 1,259; makefile: 659; xml: 192
file content (391 lines) | stat: -rw-r--r-- 12,369 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
@c DO NOT EDIT!  Generated automatically by munge-texi.pl.

@c Copyright (C) 1996-2025 The Octave Project Developers
@c
@c This file is part of Octave.
@c
@c Octave is free software: you can redistribute it and/or modify it
@c under the terms of the GNU General Public License as published by
@c the Free Software Foundation, either version 3 of the License, or
@c (at your option) any later version.
@c
@c Octave is distributed in the hope that it will be useful, but
@c WITHOUT ANY WARRANTY; without even the implied warranty of
@c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
@c GNU General Public License for more details.
@c
@c You should have received a copy of the GNU General Public License
@c along with Octave; see the file COPYING.  If not, see
@c <https://www.gnu.org/licenses/>.

@node Evaluation
@chapter Evaluation

Normally, you evaluate expressions simply by typing them at the Octave
prompt, or by asking Octave to interpret commands that you have saved in
a file.

Sometimes, you may find it necessary to evaluate an expression that has
been computed and stored in a string, which is exactly what the
@code{eval} function lets you do.

@c eval libinterp/parse-tree/oct-parse.yy
@anchor{XREFeval}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} eval (@var{try})
@deftypefnx {} {} eval (@var{try}, @var{catch})
@deftypefnx {} {[@var{var1}, @dots{}] =} eval (@dots{})
Parse the string @var{try} and evaluate it as if it were an Octave program.

If execution fails, evaluate the optional string @var{catch}.

The string @var{try} is evaluated in the current context, so any results remain
available after @code{eval} returns.

The following example creates the variable @var{A} with the approximate value
of pi (3.1416) in the current workspace.

@example
eval ('A = acos (-1);');
@end example

If an error occurs during the evaluation of @var{try} then the @var{catch}
string is evaluated, as the following example shows:

@example
@group
eval ('error ("This is a bad example");',
      'printf ("This error occurred:\n%s\n", lasterr ());');
     @print{} This error occurred:
        This is a bad example
@end group
@end example

Rather than create variables as part of the code string @var{try}, it is
clearer and slightly faster to assign the results of evaluation to an output
variable(s).  The first example can be re-written as

@example
A = eval ('acos (-1);');
@end example

Programming Note: if you are only using @code{eval} as an error-capturing
mechanism, rather than for the execution of arbitrary code strings, consider
using @code{try}/@code{catch} blocks or
@code{unwind_protect}/@code{unwind_protect_cleanup} blocks instead.  These
techniques have higher performance and don't introduce the security
considerations that the evaluation of arbitrary code does.
@xseealso{@ref{XREFevalin,,evalin}, @ref{XREFevalc,,evalc}, @ref{XREFassignin,,assignin}, @ref{XREFfeval,,feval}, @ref{XREFtry,,try}, @ref{XREFunwind_protect,,unwind_protect}}
@end deftypefn


The @code{evalc} function additionally captures any console output
produced by the evaluated expression.

@c evalc libinterp/parse-tree/oct-parse.yy
@anchor{XREFevalc}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{s} =} evalc (@var{try})
@deftypefnx {} {@var{s} =} evalc (@var{try}, @var{catch})
@deftypefnx {} {[~, @var{var1}, @dots{}] =} evalc (@dots{})
Parse and evaluate the string @var{try} as if it were an Octave program,
while capturing the output into the return variable @var{s}.

If execution fails, evaluate the optional string @var{catch}.

This function behaves like @code{eval}, but any output or warning messages
which would normally be written to the console are captured and returned in
the string @var{s}.

If the first output @var{s} is ignored with @code{~} then the actual results
of the code evaluation (not the string capture) will be assigned to output
variables @var{var1}, @var{var2}, etc.

Example 1:

@example
@group
s = evalc ("t = 42"), t
  @result{} s = t =  42

  @result{} t =  42
@end group
@end example

Example 2:

@example
@group
[~, p] = evalc ("pi")
  @result{} p = 3.1416
@end group
@end example

Programming Note: The @code{diary} is disabled during the execution of this
function.  When @code{system} is used, any output produced by external programs
is @emph{not} captured, unless their output is captured by the @code{system}
function itself.

@xseealso{@ref{XREFeval,,eval}, @ref{XREFdiary,,diary}}
@end deftypefn


@menu
* Calling a Function by its Name::
* Evaluation in a Different Context::
@end menu

@node Calling a Function by its Name
@section Calling a Function by its Name

The @code{feval} function allows you to call a function from a string
containing its name.  This is useful when writing a function that needs to
call user-supplied functions.  The @code{feval} function takes the name
of the function to call as its first argument, and the remaining
arguments are given to the function.

The following example is a simple-minded function using @code{feval}
that finds the root of a user-supplied function of one variable using
Newton's method.

@example
function result = newtroot (fname, x)

# usage: newtroot (fname, x)
#
#   fname : a string naming a function f(x).
#   x     : initial guess

  delta = tol = sqrt (eps);
  maxit = 200;
  fx = feval (fname, x);
  for i = 1:maxit
    if (abs (fx) < tol)
      result = x;
      return;
    else
      fx_new = feval (fname, x + delta);
      deriv = (fx_new - fx) / delta;
      x = x - fx / deriv;
      fx = fx_new;
    endif
  endfor

  result = x;

endfunction
@end example

Note that this is only meant to be an example of calling user-supplied
functions and should not be taken too seriously.  In addition to using a
more robust algorithm, any serious code would check the number and type
of all the arguments, ensure that the supplied function really was a
function, etc.  @xref{Predicates for Numeric Objects},
for a list of predicates for numeric objects, and @pxref{Status of
Variables}, for a description of the @code{exist} function.

@c feval libinterp/parse-tree/oct-parse.yy
@anchor{XREFfeval}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {[@var{y1}, @var{y2}, @dots{}] =} feval ('@var{fcn}', @var{x1}, @var{x2}, @dots{})
@deftypefnx {} {[@var{y1}, @var{y2}, @dots{}] =} feval (@@@var{fcn}, @var{x1}, @var{x2}, @dots{})
Evaluate the function @var{fcn} with inputs @var{x1}, @var{x2}, @enddots{}

The function @var{fcn} may be specified by name in a string or given as a
function handle.  Any arguments after the first are passed as inputs to the
named function.  For example,

@example
@group
feval ("acos", -1)
     @result{} 3.1416
@end group
@end example

@noindent
calls the function @code{acos} with the argument @samp{-1}.

The function @code{feval} can also be used with function handles of any sort
(@pxref{Function Handles}).  Historically, @code{feval} was the only way to
call user-supplied functions in strings, but function handles are now preferred
due to the cleaner syntax they offer.  For example,

@example
@group
@var{f} = @@exp;
feval (@var{f}, 1)
    @result{} 2.7183
@var{f} (1)
    @result{} 2.7183
@end group
@end example

@noindent
are equivalent ways to call the function referred to by @var{f}.  If it cannot
be predicted beforehand whether @var{f} is a function handle, function name in
a string, or inline function then @code{feval} can be used instead.
@xseealso{@ref{XREFbuiltin,,builtin}, @ref{XREFeval,,eval}, @ref{XREFevalin,,evalin}}
@end deftypefn


A similar function @code{run} exists for calling user script files, that
are not necessarily on the user path

@c run scripts/miscellaneous/run.m
@anchor{XREFrun}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} run @var{script}
@deftypefnx {} {} run ("@var{script}")
Run @var{script} in the current workspace.

Scripts which reside in directories specified in Octave's load path, and
which end with the extension @file{.m}, can be run simply by typing
their name.  For scripts not located on the load path, use @code{run}.

The filename @var{script} can be a bare, fully qualified, or relative
filename and with or without a file extension.  If no extension is
specified, Octave will first search for a script with the @file{.m}
extension before falling back to the script name without an extension.

Implementation Note: If @var{script} includes a path component, then
@code{run} first changes the working directory to the directory where
@var{script} is found.  Next, the script is executed.  Finally, @code{run}
returns to the original working directory @emph{unless} @var{script} has
specifically changed directories.
@xseealso{@ref{XREFpath,,path}, @ref{XREFaddpath,,addpath}, @ref{XREFsource,,source}}
@end deftypefn


@node Evaluation in a Different Context
@section Evaluation in a Different Context

Before you evaluate an expression you need to substitute
the values of the variables used in the expression.  These
are stored in the symbol table.  Whenever the interpreter
starts a new function it saves the current symbol table
and creates a new one, initializing it with the list of
function parameters and a couple of predefined variables
such as @code{nargin}.  Expressions inside the function use the
new symbol table.

Sometimes you want to write a function so that when you
call it, it modifies variables in your own context.  This
allows you to use a pass-by-name style of function,
which is similar to using a pointer in programming languages such
as C.

Consider how you might write @code{save} and @code{load} as
m-files.  For example:

@example
@group
function create_data
  x = linspace (0, 10, 10);
  y = sin (x);
  save mydata x y
endfunction
@end group
@end example

With @code{evalin}, you could write @code{save} as follows:

@example
@group
function save (file, name1, name2)
  f = open_save_file (file);
  save_var (f, name1, evalin ("caller", name1));
  save_var (f, name2, evalin ("caller", name2));
endfunction
@end group
@end example

@noindent
Here, @samp{caller} is the @code{create_data} function and @code{name1}
is the string @qcode{"x"}, which evaluates simply as the value of @code{x}.

You later want to load the values back from @code{mydata}
in a different context:

@example
@group
function process_data
  load mydata
  @dots{} do work @dots{}
endfunction
@end group
@end example

@noindent
With @code{assignin}, you could write @code{load} as follows:

@example
@group
function load (file)
  f = open_load_file (file);
  [name, val] = load_var (f);
  assignin ("caller", name, val);
  [name, val] = load_var (f);
  assignin ("caller", name, val);
endfunction
@end group
@end example

@noindent
Here, @samp{caller} is the @code{process_data} function.

You can set and use variables at the command prompt
using the context @samp{base} rather than @samp{caller}.

These functions are rarely used in practice.  One
example is the @code{fail (@samp{code}, @samp{pattern})} function
which evaluates @samp{code} in the caller's context and
checks that the error message it produces matches
the given pattern.  Other examples such as @code{save} and @code{load}
are written in C++ where all Octave variables
are in the @samp{caller} context and @code{evalin} is not needed.

@c evalin libinterp/parse-tree/oct-parse.yy
@anchor{XREFevalin}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} evalin (@var{context}, @var{try})
@deftypefnx {} {} evalin (@var{context}, @var{try}, @var{catch})
@deftypefnx {} {[@var{var1}, @dots{}] =} evalin (@dots{})
Like @code{eval}, except that the expressions are evaluated in the context
@var{context}, which may be either @qcode{"caller"} or @qcode{"base"}.
@xseealso{@ref{XREFeval,,eval}, @ref{XREFassignin,,assignin}}
@end deftypefn


@c assignin libinterp/parse-tree/oct-parse.yy
@anchor{XREFassignin}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {} assignin (@var{context}, @var{varname}, @var{value})
Assign @var{value} to @var{varname} in context @var{context}, which
may be either @qcode{"base"} or @qcode{"caller"}.
@xseealso{@ref{XREFevalin,,evalin}}
@end deftypefn