e04gz {NAGFWrappers}  R Documentation 
e04gz is an easytouse modified GaussNewton algorithm for finding an unconstrained minimum of a sum of squares of m nonlinear functions in n variables (m >= n). First derivatives are required.
It is intended for functions which are continuous and which have continuous first and second derivatives (although it will usually work even if the derivatives have occasional discontinuities).
e04gz(m, lsfun2, x, n = nrow(x))
m 
integer 
lsfun2 
function You must supply this function to calculate the vector of values f_i(x) and the Jacobian matrix of first derivatives ( \partial f_i)/( \partial x_j) at any point x. It should be tested separately before being used in conjunction with e04gz.

x 
double array x[j]must be set to a guess at the jth component of the position of the minimum for j=1 . . . n. The function checks the first derivatives calculated by lsfun2 at the starting point and so is more likely to detect any error in your functions if the initial x[j] are nonzero and mutually distinct. 
n 
integer: default = nrow(x) The number m of residuals, f_i(x), and the number n of variables, x_j. 
R interface to the NAG Fortran routine E04GZF.
X 
double array The lowest point found during the calculations. Thus, if ifail =0 on exit, x[j] is the jth component of the position of the minimum. 
FSUMSQ 
double The value of the sum of squares, F(x), corresponding to the final point stored in x. 
IFAIL 
integer ifail =0unless the function detects an error or a warning has been flagged (see the Errors section in Fortran library documentation). 
NAG
http://www.nag.co.uk/numeric/FL/nagdoc_fl23/pdf/E04/e04gzf.pdf
ifail < 0 lsfun2 = function(m, n, xc, ljc) { fvec < as.matrix(mat.or.vec(m, 1)) fjacc < as.matrix(mat.or.vec(ljc, n)) for (i in c(1:m)) { denom < xc[2] %*% user(2)[i, 2] + xc[3] %*% user(2)[i, 3] fvec[i] < xc[1] + user(2)[i, 1]/denom  user(1)[i] fjacc[i, 1] < 1 dummy < 1/(denom %*% denom) fjacc[i, 2] < user(2)[i, 1] %*% user(2)[i, 2] %*% dummy fjacc[i, 3] < user(2)[i, 1] %*% user(2)[i, 3] %*% dummy } list(FVEC = as.matrix(fvec), FJAC = as.matrix(fjacc)) } m < 15 x < matrix(c(0.5, 1, 1.5), nrow = 3, ncol = 1, byrow = TRUE) y < matrix(c(0.14, 0.18, 0.22, 0.25, 0.29, 0.32, 0.35, 0.39, 0.37, 0.58, 0.73, 0.96, 1.34, 2.1, 4.39), nrow = 1, ncol = 15, byrow = TRUE) t < matrix(c(1, 15, 1, 2, 14, 2, 3, 13, 3, 4, 12, 4, 5, 11, 5, 6, 10, 6, 7, 9, 7, 8, 8, 8, 9, 7, 7, 10, 6, 6, 11, 5, 5, 12, 4, 4, 13, 3, 3, 14, 2, 2, 15, 1, 1), nrow = 15, ncol = 3, byrow = TRUE) user < function(switch_integer) { switch(switch_integer, y, t, 3) } e04gz(m, lsfun2, x)