c++ - 在Rcpp中使用OptimLib时出现错误

标签 c++ algorithm rcpparmadillo

在Rcpp中使用OptimLib库时遇到错误。首先我在线复制了sphere_fn函数,以便以后在optim函数中使用它。但是,此shere_fn不起作用。

Error: can not initialize a member subobject of type `'arma::Col<double>*'with an lvalue of type 'SEXP'(aka'SEXPREC *').` 
看来问题出在grad_out,但是optim函数需要此输入形式。
例如,使用以下方法调用优化算法:
bool cg(arma::vec& init_out_vals, std::function<double (const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)> opt_objfn, void* opt_data);  
有人可以帮我吗?
我的代码是:
#include <iostream>
#include <math.h>       /* sqrt */

#define USE_RCPP_ARMADILLO
#include "optim.hpp"

// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;
using namespace std;

// This is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp
// function (or via the Source button on the editor toolbar). Learn
// more about Rcpp at:
//
//   http://www.rcpp.org/
//   http://adv-r.had.co.nz/Rcpp.html
//   http://gallery.rcpp.org/
//


// [[Rcpp::export]]
double sphere_fn(const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)
{
  double obj_val = arma::dot(vals_inp,vals_inp);
  //
  if (grad_out) {
    *grad_out = 2.0*vals_inp;
  }
  //
  return obj_val;
}

最佳答案

好吧,有时候您可能需要花一些时间学习走路,然后才能参加比赛。
换句话说,您不能只在其中放置半任意签名并期望Rcpp属性为您翻译所有内容。 void *应该映射到什么?同上arma::vec *。
只需传递arma::vec,它将在内部使用指针。从使用RcppArmadillo的工作包中研究一些现有示例,也许还可以浏览一些小插曲。

关于c++ - 在Rcpp中使用OptimLib时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63024760/

相关文章:

c++ - 多维数组的划分

r - 如何在 Apple Silicon (M1) Mac 上安装 RcppArmadillo

c++ - 使用 RcppArmadillo 时无法加载 Armadillo Cube<uword>

c++ - Graham Scan C++无法正常工作

arrays - 与目标数字数组的接近度得分

c++ - 在 Armadillo 中捕获 LAPACK 错误

c++ - 为什么向量化对于几乎相同的代码表现不同?

c++ - 增加长 double

c++ - 既是线框又是实体的 openGL 球体

java - 模运算 : Division over factorials % Prime