Contents Previous Next Subchapters Current Chapters-> interp interp1 lagrange polyfit smospl cubespl cubeval interp2 mlmode_interp2 snewton brent linlsq linlsqb nlsq dnlsq nlsqbox dnlsqb conjdir neldermead conjgrad minline lemke Qpos Qbox Qpro sqp relative fordiff cendiff autodiff testder testgrad testhess Parent Chapters-> Omatrix6 fit testgrad Search Tools-> contents reference index search

Testing Calculation of The Gradient of a Function
 Syntax `testgrad(function `fval`, `x0`, `h`)` See Also testder , testhess

Description
Given a routine fval that calculates the gradient of a column vector valued function `f(x)`, `testgrad` compares this calculation with a central difference approximation. (The gradient is the transpose of the derivative.) The results of the comparison are printed in the command window. The column vector x0 specifies the value of `x` at which to check the calculation of the gradient. The column vector h has the same type and dimension as x0. It specifies the step size to use for each component of `x` when computing the central difference approximations to the derivative of `f(x)`. ``` ```fval`(`x1`, `fout```) ```fval`(`x1`, `fout`, `gout```) ```The column vector x1 has the same type and dimension as x0 and specifies a point at which to calculate the value of `f(x)`. The input value of fout does not matter. Its output value is a column vector with the same type as x0 and equal to the value of `f(x1)`. If gout is present, its input value does not matter. Its output value is a matrix with the same type and row dimension as x0. Its column dimension is equal to the row dimension of fout and ```                d f (x)  |                   j     |          gout    = -------- |          i,j   d x      | x = x1                   i ```For each component of `x`, the partials returned by fval, the central difference approximation, and the corresponding relative error are printed in the command window.

Example
The following program checks the gradient calculation for the function `f(x)` where ```             /  x  \     __      |      f(x) = |     | ,   \/ f(x) |      =  (1, 2)             \ x^2 /             |x = 1 `````` clear function fval(x1, fout, gout) begin      fout = {x1, x1^2}      if arg(0) == 3 then ...           gout = [1, 2 * x1] end x0 = 1. h  = .001 testgrad(function fval, x0, h) ```