我正在尝试制作一个MEX文件,所以我可以调用LAPACK子程序dgesv()来解决线性方程式Ax=b.
如果我在调用dgesv_时注释该行,我得到了结果(例如,如果我将nb的值传递给x,当我调用MEX文件时,我在matlab代码中得到值返回值)
问题是当我调用dgesv_时,我无法指出是什么造成了分段错误。
以下是代码(我的问题的重要内容):
#include "mex.h"
/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* Variable Declaration */
double *A; /* input Array */
double *b; /* input Vector */
double *nA;
double *nb;
double *x; /* Output Vector */
int M, N, NRHS, INFO, *IPIV, LDA, LDB, i;
/* Check input arguments */
if(nrhs!=2)
{
mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs",
"Two inputs required.");
}
/* create a pointer to the real data in the input matrix */
A = mxGetPr(prhs[0]);
/* create a pointer to the real data in the input vector */
b = mxGetPr(prhs[1]);
/* Get Dims */
M = mxGetM(prhs[0]);
N = mxGetN(prhs[0]);
NRHS=mxGetN(prhs[1]);
LDA=M;
LDB=M;
/* Allocate mem for new arrays */
nA = (double *)mxCalloc(M*N, sizeof(double));
nb = (double *)mxCalloc(M*NRHS, sizeof(double));
IPIV = (int* )mxCalloc(M,sizeof(int));
/* Copy values new arrays */
for (i=0; i<M*N; i++)
nA[i]=A[i];
for (i=0; i<M*NRHS; i++)
nb[i]=b[i];
/* Programm is tested on OS X Mavericks so dgesv_ instead of dgesv */
dgesv_(&M, &NRHS, nA, &LDA, IPIV, nb, &LDB, &INFO);
/* create the output vector */
plhs[0] = mxCreateDoubleMatrix(M,NRHS,mxREAL);
/* get a pointer to the real data in the output matrix */
x = mxGetPr(plhs[0]);
/* If INFO == 0 then we got a solve on nb, so pass it to x */
if (INFO == 0)
for(i=0;i<M*NRHS;i++)
x[i] = nb[i];
else if (INFO < 0)
/*Print something */
else
/* Print something */
mxFree(nA);
mxFree(nb);
mxFree(IPIV);
}
此外,我试图调用dgesv_而不创建新数组(如此)
dgesv_(&M, &NRHS, A, &LDA, IPIV, b, &LDB, &INFO);
但我有同样的问题。
我编译并在MATLAB上调用MEX文件,如下所示:
mex -v -largeArrayDims MEXfile.c -lmwlapack
A=rand(3);
b=rand(3,1);
x=MEXfile(A,b);
我得到了分段错误。