您可以使用成员变量作为感兴趣的变量。为了简单起见,我使用
public
这里的成员:
// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::depends(RcppNumerical)]]
#include <RcppNumerical.h>
using namespace Numer;
// f = 100 * (x2 - x1^2)^2 + (1 - x1)^2
// True minimum: x1 = x2 = 1
class Rosenbrock: public MFuncGrad
{
public:
double t1;
double t2;
double f_grad(Constvec& x, Refvec grad)
{
t1 = x[1] - x[0] * x[0];
t2 = 1 - x[0];
grad[0] = -400 * x[0] * t1 - 2 * t2;
grad[1] = 200 * t1;
return 100 * t1 * t1 + t2 * t2;
}
};
// [[Rcpp::export]]
Rcpp::List optim_test()
{
Eigen::VectorXd x(2);
x[0] = -1.2;
x[1] = 1;
double fopt;
Rosenbrock f;
int res = optim_lbfgs(f, x, fopt);
return Rcpp::List::create(
Rcpp::Named("xopt") = x,
Rcpp::Named("fopt") = fopt,
Rcpp::Named("status") = res,
Rcpp::Named("t1") = f.t1,
Rcpp::Named("t2") = f.t2
);
}
/*** R
optim_test()
*/
结果:
> optim_test()
$xopt
[1] 1 1
$fopt
[1] 3.12499e-15
$status
[1] 0
$t1
[1] -2.849634e-09
$t2
[1] -4.809313e-08