我想在 C mexFunction 中实现 Matern 相关函数,这需要计算第二类修改后的 Besselk 函数。
在 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 代码成功运行。