A simple example - the ln Γ(x) function routine nag_log_gamma (s14abc) |
According to the C Library Manual, the prototype for function s14abc looks like this:
#include <nag.h> #include <nags.h> double s14abc(double x, NagError *fail);The function takes two arguments. The first one is of type double and is the argument x of the log gamma function ln Γ (x). The second argument to s14abc is the error handling argument fail which is of type NagError. See the NAG C Library Manual for more information about the NagError type. To keep things simple we are not going to pass the contents of the NagError structure back to Octave. Instead, we will return only integer value of fail.code.
Here is the source code of our C++ function nag_lgamma.cc:
#include <octave/oct.h> #define Complex NagComplex #define MatrixType NagMatrixType #include <nag.h> #include <nags.h> DEFUN_DLD (nag_lgamma, args, , "Calls nag_log_gamma (s14abc), which returns\n\ the value of the logarithm of the Gamma function, ln Gamma(x)\n\ via the function name.\n") { octave_value_list retval; // Retrieve input arguments from args double x = args(0).double_value(); // Declare local variables double y; NagError fail; INIT_FAIL(fail); // Call NAG routine like in C y = nag_log_gamma(x,&fail); // Assign output arguments to retval retval(0) = y; retval(1) = fail.code; return retval; }
Points to note about this code:
To compile the C++ function into oct-files, we use the mkoctfile script supplied with Octave:
% mkoctfile nag_lgamma.cc -L/opt/NAG/cll6a08dg/lib -lnagc_nag -I/opt/NAG/cll6a08dg/includewhere:
Assuming that all has gone well, we can call the function as if it was part of Octave itself, i.e. either from the Octave command line or from within an Octave program. An example call may be:
octave:1> [y,ifail]=nag_lgamma(1.25) y = -0.098272 ifail = 0
Tip: If you get an error message in Octave saying that libnagc_nag.so cannot be found, you may need to set an environment variable to tell the system where to look. The environment variable name is operating-system dependent. On Linux machines it is named LD_LIBRARY_PATH, and is a colon-separated list of directories to be searched for libnagc_nag.so. For example, if you use the C shell, the command
% setenv LD_LIBRARY_PATH /opt/NAG/cll6a08dg/lib:${LD_LIBRARY_PATH}will ensure that directory /opt/NAG/cll6a08dg/lib gets searched.