基于Eigen库和Matlab计算非线性多元函数最小值
生活随笔
收集整理的這篇文章主要介紹了
基于Eigen库和Matlab计算非线性多元函数最小值
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
當(dāng)函數(shù)y = 10*(x0+3)^2 + (x1-5)^2取最小值時,計算x0和x1的值,即:
{x0, x1} = arg?min?x0,x1(10?(x0+3)2+(x1?5)2)\mathop{\arg\min}_{x0, x1}( 10*(x0+3)^2 + (x1-5)^2)argminx0,x1?(10?(x0+3)2+(x1?5)2)
#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::Dynamic, int NY = Eigen::Dynamic>
struct Functor
{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>
{// 輸出個數(shù)必須大于輸入個數(shù), 故用2不用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)^2fvec(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 first input: \n" << x << std::endl;std::cout << "y first outpout: \n" << y << std::endl;lm.parameters.maxfev = 1000;lm.parameters.xtol = 1.0e-8;int iRet = lm.minimize(x);std::cout << "迭代次數(shù):\n" << lm.iter << std::endl;std::cout << "計算標志:\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;getchar();return 0;
}
如果使用Matlab則可以考慮用fmincon函數(shù):
https://www.zhihu.com/question/57557247/answer/332589995
https://www.bilibili.com/read/cv5132071/
總結(jié)
以上是生活随笔為你收集整理的基于Eigen库和Matlab计算非线性多元函数最小值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于Sobel计算图像梯度图
- 下一篇: 基于C++CUDA实现全景图(2:1 E