This example shows an NLREG program that fits a 3D sphere to a set
of data points.
A sphere can be defined by specifying its center point (Xc,Yc,Zc) and
its radius, R. So the goal of this example is to develop a NLREG
program that will compute the values of Xc, Yc, Zc and R that cause a
sphere to best fit a set of data points whose coordinates (Xp,Yp,Zp) are
provided as a data set. We will take "best fit" to mean the sphere minimizes
the sum of squared distances from the points to the surface of the sphere.
Since our goal is to minimize the sum of the squared distances
from the points to the surface of the sphere, we need a function
that will compute this distance for each point. If the center of
the sphere is at (Xc,Yc,Zc) and the position of a point is (Xp,Yp,Zp)
then, from the theorem of Pythagoras, we know the distance from
the center to the point is
sqrt((Xp-Xc)^2 + (Yp-Yc)^2 + (Zp-Zc)^2)
But we are interested in the distance from the surface to the
point. Since the radius of the sphere is R, the distance from the
surface to the point (along a straight line from the center to
the point) is
sqrt((Xp-Xc)^2 + (Yp-Yc)^2 + (Zp-Zc)^2) - R
That is, the distance from the surface to the point is equal to
the distance from the center to the point less the distance from
the center to the surface (the radius). The distance will be
positive or negative depending on whether the point is outside or
inside the sphere, but this does not matter since the value is
squared as part of the minimization process.
The NLREG statements for this analysis are as follows:
/*
* Compute the center and radius of a sphere that
* makes the sphere best fit a set of data points
* (i.e., minimize the sum of squared distances from
* the surface of the sphere to each point).
*/
Title "Fit sphere to group of points";
/*
* We will input the Xp,Yp,Zp coordinate of each point.
*/
Variables Xp, Yp, Zp;
/*
* We will compute the center (Xc,Yc,Zc) of the sphere
* and its radius, R.
*/
Parameters Xc, Yc, Zc, R;
/*
* Define two work variables for our computations.
*/
Double distance, offset;
/*
* Compute the distance of this point from the center
* of the sphere.
*/
distance = sqrt((Xp-Xc)^2 + (Yp-Yc)^2 + (Zp-Zc)^2);
/*
* Compute the distance from the surface of the sphere
* to the point. This is the difference between the
* distance of the point from the center and the radius
* of the sphere. Note: it may be positive or negative.
*/
offset = distance - R;
/*
* Let NLREG minimize the sum of the squared offsets.
*/
Function offset;
/*
* Data values follow.
*/
Data;
[ data goes here ]
Note that there is no dependent variable or equal sign to the left
of the function. NLREG will determine the values of the
parameters Yp, Yc, Zc and R such that the sum of the squared values
of the function (i.e., the sum of the squared distances) is
minimized.