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 eval function lets you do.

 -- eval: (TRY)
 -- eval: (TRY, CATCH)
     Parse the string TRY and evaluate it as if it were an Octave program.

     If execution fails, evaluate the optional string CATCH.

     The string TRY is evaluated in the current context, so any results remain available after eval returns.

     The following example creates the variable A with the approximate value of 3.1416 in the current workspace.

          eval ("A = acos(-1);");

     If an error occurs during the evaluation of TRY then the CATCH string is evaluated, as the following example shows:

          eval ('error ("This is a bad example");',
                'printf ("This error occurred:\n%s\n", lasterr ());');
               -| This error occurred:
                  This is a bad example

     Programming Note: if you are only using eval as an error-capturing mechanism, rather than for the execution of arbitrary code strings, Consider using try/catch blocks or unwind_protect/unwind_protect_cleanup blocks instead.  These techniques have higher performance and don't introduce the security considerations that the evaluation of arbitrary code does. evalin, evalc, assignin, feval

The evalc function additionally captures any console output produced by the evaluated expression.

 -- S =: evalc (TRY)
 -- S =: evalc (TRY, CATCH)
     Parse and evaluate the string TRY as if it were an Octave program, while capturing the output into the return variable S.

     If execution fails, evaluate the optional string CATCH.

     This function behaves like eval, but any output or warning messages which would normally be written to the console are captured and returned in the string S.

     The diary is disabled during the execution of this function.  When system is used, any output produced by external programs is not captured, unless their output is captured by the system function itself.

          s = evalc ("t = 42"), t
            => s = t =  42

            => t =  42

     eval, diary

Calling a Function by its Name
==============================

The 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 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 feval that finds the root of a user-supplied function of one variable using Newton's method.

     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

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.  See Predicates for Numeric Objects, for a list of predicates for numeric objects, and see Status of Variables, for a description of the exist function.

 -- RETVAL =: feval (NAME, ...)
     Evaluate the function named NAME.

     Any arguments after the first are passed as inputs to the named function. For example,

          feval ("acos", -1)
               => 3.1416

     calls the function acos with the argument -1.

     The function feval can also be used with function handles of any sort (see Function Handles).  Historically, 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,

          F = @exp;
          feval (F, 1)
              => 2.7183
          F (1)
              => 2.7183

     are equivalent ways to call the function referred to by F.  If it cannot be predicted beforehand whether F is a function handle, function name in a string, or inline function then feval can be used instead.

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

 -- run: SCRIPT
 -- run: ("SCRIPT")
     Run SCRIPT in the current workspace.

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

     The filename 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 .m extension before falling back to the script name without an extension.

     Implementation Note: If SCRIPT includes a path component, then run first changes the working directory to the directory where SCRIPT is found.  Next, the script is executed.  Finally, run returns to the original working directory unless SCRIPT has specifically changed directories. path, addpath, source

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 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 save and load as m-files.  For example:

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

With evalin, you could write save as follows:

     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

Here, caller is the create_data function and name1 is the string "x", which evaluates simply as the value of x.

You later want to load the values back from mydata in a different context:

     function process_data
       load mydata
       ... do work ...
     endfunction

With assignin, you could write load as follows:

     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

Here, caller is the process_data function.

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

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

 -- evalin: (CONTEXT, TRY)
 -- evalin: (CONTEXT, TRY, CATCH)
     Like eval, except that the expressions are evaluated in the context CONTEXT, which may be either "caller" or "base". eval, assignin

 -- assignin: (CONTEXT, VARNAME, VALUE)
     Assign VALUE to VARNAME in context CONTEXT, which may be either "base" or "caller". evalin