Using Eigen to solve nonlinear least squares;
Example: <span style= "font-family:arial, Helvetica, Sans-serif;" >y = 10* (x0+3) ^2 + (x1-5) ^2</span><pre name= "code" class= "HTML" ><span style= "font-family:arial, Helvetica, Sans-serif; " > #include "math.h" </span>
#include "iostream"
#include "vector"
#include "list"
using namespace std;
#include "eigen/dense"
#include "eigen/core"
#include <unsupported/Eigen/NonLinearOptimization>
#include <unsupported/Eigen/NumericalDiff>
using namespace Eigen;
Generic functor
template<typename _scalar, int NX = Eigen::D ynamic, int NY = eigen::D ynamic> struct funct
or
{
typedef _scalar Scalar;
enum {
inputsatcompiletime = NX,
valuesatcompiletime = NY
};
typedef eigen::matrix<scalar,inputsatcompiletime,1> INPUTTYPE;
typedef eigen::matrix<scalar,valuesatcompiletime,1> ValueType;
typedef eigen::matrix<scalar,valuesatcompiletime,inputsatcompiletime> JACOBIANTYPE;
int m_inputs, m_values;
Functor (): M_inputs (Inputsatcompiletime), M_values (valuesatcompiletime) {}
functor (int inputs, int values): m_ Inputs (inputs), m_values (values) {}
int inputs () const {return m_inputs;}
int values () const {return m_values;}
};
struct my_functor:functor<double>
{
//output number must be greater than the number of input, so use 2 not 1;
My_functor (void): Functor<double> (2, 2) {}
int operator () (const EIGEN::VECTORXD &x, EIGEN::VECTORXD &fvec) const
{
//Implement y = 10* (x0+3) ^2 + (x1-5) ^2 Fvec
(0) = 10.0*pow (x (0) +3.0,2) + pow (x (1)-5.0 , 2);
Fvec (1) = 0;
return 0;
}
;
int main (int argc, char *argv[])
{
eigen::vectorxd x (2);
X (0) = 1.0;
X (1) = 3.0;
My_functor functor;
Eigen::numericaldiff<my_functor> Numdiff (functor);
Eigen::levenbergmarquardt<eigen::numericaldiff<my_functor>,double> LM (NumDiff);
Eigen::vectorxd y (2);
Functor.operator () (x, y);
Std::cout << "x-I input: \ n" << x << Std::endl;
std::cout<< "y-outpout: \ n" << y << Std::endl;
Lm.parameters.maxfev = 1000;
Lm.parameters.xtol = 1.0e-8;
int iRet = lm.minimize (x);
Std::cout << "Iteration number: \ n" <<lm.iter << Std::endl;
Std::cout << "calculation sign: \ n" << iRet << Std::endl;
Std::cout << "x finnal: \ n" << x << Std::endl;
Functor.operator () (x, y);
std::cout<< "y Outpout (minimized): \ n" << y << Std::endl;
return 0;
}
finally see output x = [-3.0, 5.0]. Make the target the smallest!