Using the NAG Toolbox for MATLAB® - Part 2
Using the NAG Toolbox for MATLAB® - Part 2
The NAG Toolbox makes the full functionality of the NAG Library available through MATLAB. An advantage of calling NAG via MATLAB is that many routine arguments become optional or unnecessary, which makes code easier to read and maintain. In addition, all of the NAG Library documentation (seventeen large volumes taking up a substantial amount of shelf space) has been converted to MATLAB help format, and so it is simple to access via MATLAB's usual documentation facilities. The documentation for each NAG Library routine includes example MATLAB code showing how to use the routine.
We have already highlighted some of the contents of the NAG Toolbox in https://www.nag.co.uk/content/using-nag-toolbox-matlab; here, we continue our exploration of the Toolbox, demonstrating how to call some of the other NAG routines, using MATLAB's plotting facilities to view the results.
Note: The code examples in this article have been extracted from demo scripts, and will not necessarily work properly if cut and pasted from this page into MATLAB. The full version of the scripts, which have been used to make the figures in this article, are available in this archive.
We start with the calculation of the zeros of a continuous function. The C05 chapter contains several routines for doing this (as well as other routines which solve a set of nonlinear equations in several unknowns). In our first example, we solve a quadratic equation.
25x^2 - 10x + 1 = 0
Of course, it is trivial to determine analytically that both roots are at x = 0.2 (which provides a handy check on our numerical result - see below) but the C05 routines can be used to find the zeros of any function, as long as it is continuous. Here, we use routine c05ax; this evaluates the function via reverse communication, which allows us to display the intermediate results on the way to finding the root.
Here's the code, including some plotting commands:
and the results are shown in this picture:
Figure 1: Finding the root of a quadratic.
As a second example, we can use the same code to find the root of a different function (for example, one that is harder to determine analytically) by changing the first few lines of the code above to:
giving the results shown in Figure 2.
Figure 2: Finding the root of a transcendental function.
The MATLAB script for this demo is available as the file NAGToolboxDemos/Root_finding/c05ax_demo.m, distributed in this archive.
A common task in many areas of science is to find a function which approximates a set of data points. The data may contain random perturbations - such as measurement errors - which it is desirable to smooth out. In the previous article, we looked at how to use the NAG Toolbox to compute a bicubic spline approximation to a two-dimensional set of data values given on a grid in the x-y plane; the result was displayed as a surface, f(x,y). Here, we investigate the one-dimensional case, where we seek to find a cubic spline curve f(x) which approximates a set of data values given on the x-axis. The NAG routine which does this is e02be, while the supplementary routine e02bb can be used to evaluate the spline at any point, given the results from e02be.
As in the two-dimensional example, a single parameter is specified to control the trade-off between closeness and smoothness of fit. A small value for this smoothing parameter, named s in e02be, will give a closer fit to the data, but the exact meaning of 'small' in this context will vary according to the particular data set. In the extremes, a value of s = 0 will produce an interpolating spline, while a very large value will produce the weighted least-squares cubic polynomial approximation to the points.
Figure 3 shows the data points and the spline for three values of s. It can be seen that, as s is decreased, the fit becomes less smooth, and closer to the points.
Figure 3: Fitting a cubic spline through data points.
The MATLAB script for this demo is available as the file NAGToolboxDemos/Curve_and_surface_fitting/e02be_demo.m, distributed in this archive.
In the previous example, when s = 0, we have a cubic spline curve that passes through all of the data points, and could be used to determine function values at any given x within the range of the supplied data points. This is interpolation, and the cubic spline can be a useful interpolating function for some data sets. However, as we have already seen in our discussion of the trade-off when determining values for the smoothness parameter, the interpolant can exhibit unwanted fluctuations in between the data points (see, for example, the Smoothness = 0 curve in Figure 3).
To illustrate this further, consider Figure 4, which shows a cubic spline interpolant, as fitted to another dataset.
Figure 4: Interpolating through data points using a piecewise cubic Hermite interpolant.
Here, we see that while the cubic spline appears to be a reasonable interpolant for low x values, it shows large fluctuations near the endpoints. These might be undesirable - for example, if the data represented some physical quantity whose value could not exceed 1, the behaviour of the cubic spline would be unacceptable.
However, other interpolants are available - for example, in chapter E01 of the NAG Toolbox, the e01be routine fits a piecewise cubic Hermite interpolant through a set of data points. This preserves monotonicity - that is, it will always increase, or decrease, over the same intervals as the data. As can be seen from Figure 4, this interpolant has no fluctuations, and might be more physically valid for our data set.
Here's the code for the e01be example. Once again, the NAG Toolbox provides an supplementary routine - here, e01bf - which can be used to evaluate the interpolant at any point, given the results from e01be.
The MATLAB script for this demo is available as the file NAGToolboxDemos/Interpolation/e01be_demo.m, distributed in this archive.
In this final section, we use the NAG Toolbox in an application that is somewhat more complicated. In statistics, a copula can be thought of as defining the correlation structure for a family of multivariate distributions. Each distribution in the family is constructed by "gluing" together two or more univariate distributions, with the copula supplying the "glue". Copulas can be applied to a wide range of simulation problems - for example, the so-called Gaussian copula is often used in financial modelling.
To illustrate, suppose we wish to simulate the joint distribution of several random variables. The kind of copula we use - Gaussian, Student's t, etc - describes the correlation structure between the variables, while a collection of univariate distributions (usually called the marginal distributions) define the distribution within each of the variables. Compared to more conventional multivariate distributions (such as, for example, the multivariate normal), the use of a copula allows each variable to have a different marginal distribution. Thus, for example, one variable may have a Gaussian (normal) marginal distribution, while another has a Beta distribution, a third is uniformly distributed, and so on.
In this example, we construct a bivariate distribution using a Gaussian copula with Beta marginal distributions. The input for the calculation of the multivariate distribution includes its covariance matrix, which contains details of the correlations between the different variables. The copula is created using NAG routine g05rd . The shape of the Beta distribution is defined by two parameters (usually called alpha and beta), and can range from the symmetric bell curve of the normal distribution (when alpha and beta are both 1) to being highly skewed or, at the other extreme, a uniform distribution. Here, we set alpha = 12.0 and beta = 5.0 for the first variable - which gives a skewed distribution - and alpha = beta = 5.0 for the second variable, which is distributed symmetrically. Here's the code:
The resultant distribution is then converted into a two-dimensional array of frequencies and displayed in MATLAB as a surface (though other representations - such as a contour plot - are also possible).
Figure 5: Creating a Gaussian copula.
It can be instructive to look at the shape of the copula for different marginal distributions, or for other correlations - for example, increasing the correlation coefficient causes the peak to become narrower. Furthermore, it's reasonably straightforward in MATLAB to construct an animation, based upon a loop over parameter values, which tracks the progress of the peak across the two-dimensional domain.
The MATLAB script for this demo is available as the file NAGToolboxDemos/Random_number_generation/g05ra_demo.m, distributed in this archive.