如何将整数值作为 mex 函数的输入传递?
How to pass as input of a mex function an integer value?
我正在尝试将一个整数作为 mexfunction 的参数传递,该整数表示 mxCreateDoubleMatrix 的列数。这个整数不应该用在除主 mexFunction 以外的任何地方。
不知何故,这似乎不起作用。
// mex function for calling c++ code .
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
char *input_buf;
size_t buflen;
double ncols;
double *result_final;
double *result_second;
/* get the length of the input string */
buflen = (mxGetM(prhs[0]) * mxGetN(prhs[0])) + 1;
/* copy the string data from prhs[0] into a C string input_ buf. */
input_buf = mxArrayToString(prhs[0]);
/* copy the int from prhs[0] to decide on length of the results. */
ncols = (int) (size_t) mxGetPr(prhs[1]);
plhs[0] = mxCreateDoubleMatrix(1, ncols, mxREAL);
plhs[1] = mxCreateDoubleMatrix(1, ncols, mxREAL);
result_final = mxGetPr(plhs[0]);
result_second = mxGetPr(plhs[1]);
/* Do the actual computations in a subroutine */
subroutine(input_buf, buflen, result_final, result_second);
}
如果我去掉 ncols 行,其余的都按预期工作。我没有将 ncols 作为子程序的输入,因为它实际上并没有在那里使用,而是仅在主程序中使用,以定义输出数组的大小。
如果我调用 myfun('examplefile.txt',100) 而不是在调用结束时显示的矩阵有一个 infinite/very,我希望输出数组有一个 1x100 的矩阵列数很长。
有人可以帮忙吗?
您正在将指向值的指针转换为 size_t
,然后是 int
。但它是一个指针,是值所在 RAM 中的地址,而不是值本身。
ncols = (int) (size_t) mxGetPr(prhs[1]); %mex Get Pointer!!
改为获取值。
ncols = (int)(mxGetScalar(prhs[1]));
我正在尝试将一个整数作为 mexfunction 的参数传递,该整数表示 mxCreateDoubleMatrix 的列数。这个整数不应该用在除主 mexFunction 以外的任何地方。
不知何故,这似乎不起作用。
// mex function for calling c++ code .
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
char *input_buf;
size_t buflen;
double ncols;
double *result_final;
double *result_second;
/* get the length of the input string */
buflen = (mxGetM(prhs[0]) * mxGetN(prhs[0])) + 1;
/* copy the string data from prhs[0] into a C string input_ buf. */
input_buf = mxArrayToString(prhs[0]);
/* copy the int from prhs[0] to decide on length of the results. */
ncols = (int) (size_t) mxGetPr(prhs[1]);
plhs[0] = mxCreateDoubleMatrix(1, ncols, mxREAL);
plhs[1] = mxCreateDoubleMatrix(1, ncols, mxREAL);
result_final = mxGetPr(plhs[0]);
result_second = mxGetPr(plhs[1]);
/* Do the actual computations in a subroutine */
subroutine(input_buf, buflen, result_final, result_second);
}
如果我去掉 ncols 行,其余的都按预期工作。我没有将 ncols 作为子程序的输入,因为它实际上并没有在那里使用,而是仅在主程序中使用,以定义输出数组的大小。
如果我调用 myfun('examplefile.txt',100) 而不是在调用结束时显示的矩阵有一个 infinite/very,我希望输出数组有一个 1x100 的矩阵列数很长。
有人可以帮忙吗?
您正在将指向值的指针转换为 size_t
,然后是 int
。但它是一个指针,是值所在 RAM 中的地址,而不是值本身。
ncols = (int) (size_t) mxGetPr(prhs[1]); %mex Get Pointer!!
改为获取值。
ncols = (int)(mxGetScalar(prhs[1]));