c++ - 在 C MexFunction 中使用 Besselk 函数

标签 c++ c matlab mex bessel-functions

我想在C mexFunction中实现Matern相关函数,这需要计算第二类修正贝塞尔克函数。

在 MATLAB 中,可以使用函数 besselk。然而,任何 C 库中都没有这样的等效项(我是对的吗?)。我知道 boost 库(一个 C++ 库)提供了对第二类修改后的 Besselk 函数的访问,请参阅 https://en.cppreference.com/w/cpp/experimental/special_math ,但我无法在我的 Mac 和 Linux 系统上使用 MATLAB 2018a 在 C mexFunction 中工作。顺便说一句,我不想​​在 C mex 代码中调用 MATLAB 函数 besselk。

如有任何建议,我们将不胜感激。下面是使用 C mex 代码构造母相关函数的最小示例。

#include "mex.h"
#include "matrix.h"
#include <math.h>
//#include <boost/math/special_functions.hpp>
double matern(double h, double nu)
{
    double tau = sqrt(2.0*nu) * h;
    double c = 0.0;
    if(h>0.0){
      c = (pow(tau, nu) * pow(2.0, 1.0-nu) / tgamma(nu)) * boost::math::cyl_bessel_k(nu, tau);
    }else{
      c = 1.0;
    }
    return c;
  }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if(nrhs!=2){
        mexErrMsgTxt("Two Inputs are required.");
    }
    double h = mxGetScalar(prhs[0]);
    double nu = mxGetScalar(prhs[1]);
    double corr = matern(h, nu);
    mexPrint("matern(h=%g, nu=%g) = %g", h, nu, corr);
    plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
    mxSetPr(plhs[0], &corr);
         return;
}

如果我将上面的 C mex 代码翻译为 C++ 代码文件,我可以在我的 mac 上成功使用 g++ 编译器编译 C++ 代码。

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#include <boost/math/special_functions.hpp>

double matern(const double h, const double nu)
{

  double tau = sqrt(2.0*nu) * h;

  double c = 0.0;
  if(h>0.0){
    c = (pow(tau, nu) * pow(2.0, 1.0-nu) / tgamma(nu)) * boost::math::cyl_bessel_k(nu, tau);
  }else{
    c = 1.0;
  }


  return c;
}

int main(){
    double nu=0.5, h=1.0;
    double corr = matern(h, nu);
    printf("corr=%lf\n", corr);

    return 0;
}

再次强调我的问题,我不需要 C++ 代码,而是想让我的 C mex 代码成功运行。

最佳答案

这并不是真正的墨西哥特有的。

您可以在 C 程序中使用 Boost 特殊数学函数;它们设计用于 C 或 C++。

为此,您需要添加

#include <boost/math/tr1.hpp>

在 C++ 中,此文件中的声明被插入到命名空间 booth::math 中,但显然您不能在 C 代码中使用 C++ 命名空间。函数本身是用 C 链接编译的,因此它们是全局名称,可以简单地按原样使用。

请注意,Boost 提供了 C99 和 TR1 特殊数学函数(因此,如果您还生活在过去,它可以与早于 C99 的标准 C 库一起使用),但它们位于不同的库中,如中所述Boost documentation 。即使您有 C99 标准库,在包含 Boost header 后,您将需要使用 C99 函数的 Boost 库。因此,您可能需要向构建命令添加两个链接选项:

-lboost_math_c99 -lboost_math_tr1

如果您需要floatlong double版本,您将需要其他库。有关详细信息,请参阅上面的 Boost 文档链接。

关于c++ - 在 C MexFunction 中使用 Besselk 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51026127/

相关文章:

C++ 指针 - 在函数调用中重新分配

C++矩阵类: overloading assignment operator

c++ - 警告 : left-hand/right-hand operand of comma has no effect

c++ - 从父类 QAbstractItemView 断开插槽

c - 文件C程序错误异常

c - tm struct time.h 未规范化

c - 使用文件和列表修改 C 中的字符

matlab - Lucas Kanade 光流,方向矢量

performance - 在 MATLAB 中 reshape 向量

matlab - 如何在 matlab 中出错时默认到脚本的位置