我正在尝试在Matlab中编写一个使用C的mex函数 . 我的函数目标是创建并返回结构数组 . 代码位于这篇文章的底部 . 该函数应该被称为
result = structtest(1,2,3);
返回的变量 result
将是matlab中的结构数组 . 我将其设置为1x3阵列,其字段名为test1,test2和test3 . 这都是通过 mxCreateStructArray
在mex函数中完成的 . struct数组的元素通过 mxSetField
命令在mex文件中的 test
函数中设置 . 预期的产出是
result =
1x3 struct array with fields:
test1
test2
test3
例如,
>> result(1)
ans =
test1: [1 2]
test2: 2
test3: 3
棘手的部分似乎是获得第一个字段 test1
,以便在其中存储数组 . 字段 test2
和 test3
似乎不是问题,但我的程序的输出是 test1
是一个数字(不是我在mex程序中设置的数组),否则Matlab只是崩溃 . 任何人都可以在我的代码中指出我可能出错的地方吗?
#include "mex.h"
#include <string.h>
#ifndef UCHAR
typedef unsigned char UCHAR;
#endif
void test(UCHAR a, UCHAR b, UCHAR c, mxArray **result)
{
int i;
UCHAR testArr[2] = {a, a*2};
mxArray * arr;
UCHAR * parr;
mwSize dim[2] = {1,2};
size_t bytes_to_copy;
arr = mxCreateNumericArray(2, dim, mxUINT8_CLASS, mxREAL);
parr = (UCHAR *)mxGetData(arr);
bytes_to_copy = 2 * mxGetElementSize(arr);
memcpy(parr, testArr, bytes_to_copy);
for (i = 0; i < 3; i++) {
mxSetField(*result,i,"test1",arr);
mxSetField(*result,i,"test2",mxCreateDoubleScalar(b*(i+1)));
mxSetField(*result,i,"test3",mxCreateDoubleScalar(c*(i+1)));
}
mxDestroyArray(arr);
}
/* The gateway function for Matlab */
/* Inputs:
* nlhs: The number of left-hand side (i.e., output) arguments
* *plhs[]: An array of output arguments
* nrhs: The number of right-hand side (i.e., input) arguments
* *prhs[]: An array of input arguments
*/
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* Define necessary variables */
UCHAR a; /* First number */
UCHAR b; /* Second number */
UCHAR c; /* Third number */
mwSize dims[2] = {1,3};
const char *fieldNames[] = {"test1", "test2", "test3"};
mxArray **result; /* Pointer to store result of function call */
/* Validate mexFunction Input */
// Ensure that the number of input variables is 3
if (nrhs != 3) {
mexErrMsgIdAndTxt("MyToolbox:sendTest:nrhs", "Required three input variables");
}
// Ensure that the user output to one variable
if (nlhs != 1) {
mexErrMsgIdAndTxt("MyToolbox:sendTest:nlhs", "One output required.");
}
/* Extract inputs and define outputs for mexFunction */
// Inputs
a = (UCHAR)mxGetScalar(prhs[0]);
b = (UCHAR)mxGetScalar(prhs[1]);
c = (UCHAR)mxGetScalar(prhs[2]);
// Outputs
plhs[0] = mxCreateStructArray(2, dims, 3, fieldNames);
result = &plhs[0];
/* Call the main function */
test(a, b, c, result);
}