📄 例11-4.m
字号:
#include "mex.h"
#include "string.h"
#define MAXCHARS 80 /* 每个域所能包含的最大字符数 */
/* 入口子程序 */
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
const char **fnames; /* 指向域名的指针 */
const int *dims;
mxArray *tmp, *fout;
char *pdata;
int ifield, jstruct, *classIDflags;
int NStructElems, nfields, ndim;
/* 检查输出参数的个数*/
if (nrhs != 1)
mexErrMsgTxt("One input required.");
else if (nlhs > 1)
mexErrMsgTxt("Too many output arguments.");
else if (!mxIsStruct(prhs[0]))
mexErrMsgTxt("Input must be a structure.");
/* 获得输入参数*/
nfields = mxGetNumberOfFields(prhs[0]);
NStructElems = mxGetNumberOfElements(prhs[0]);
/* 分配内存给classIDflags */
classIDflags = mxCalloc(nfields, sizeof(int));
/* 检查空域、数据类型的正确性和一致性,并且获得每一个域的classID */
for (ifield = 0; ifield < nfields; ifield++) {
for (jstruct = 0; jstruct < NStructElems; jstruct++) {
tmp = mxGetFieldByNumber(prhs[0], jstruct, ifield);
if (tmp == NULL) {
mexPrintf("%s%d\t%s%d\n",
"FIELD:", ifield+1, "STRUCT INDEX :", jstruct+1);
mexErrMsgTxt("Above field is empty!");
}
if (jstruct == 0) {
if ((!mxIsChar(tmp) && !mxIsNumeric(tmp)) ||
mxIsSparse(tmp)) {
mexPrintf("%s%d\t%s%d\n",
"FIELD:", ifield+1, "STRUCT INDEX :", jstruct+1);
mexErrMsgTxt("Above field must have either "
"string or numeric non-sparse data.");
}
classIDflags[ifield] = mxGetClassID(tmp);
} else {
if (mxGetClassID(tmp) != classIDflags[ifield]) {
mexPrintf("%s%d\t%s%d\n",
"FIELD:", ifield+1, "STRUCT INDEX :", jstruct+1);
mexErrMsgTxt("Inconsistent data type in above field!");
}
else if (!mxIsChar(tmp) && ((mxIsComplex(tmp) ||
mxGetNumberOfElements(tmp) != 1))) {
mexPrintf("%s%d\t%s%d\n",
"FIELD:", ifield+1, "STRUCT INDEX :", jstruct+1);
mexErrMsgTxt("Numeric data in above field "
"must be scalar and noncomplex!");
}
}
}
}
/* 分配内存来存储指针 */
fnames = mxCalloc(nfields, sizeof(*fnames));
/* 获得域名指针*/
for (ifield = 0; ifield < nfields; ifield++) {
fnames[ifield] = mxGetFieldNameByNumber(prhs[0],ifield);
}
/* 创建一个1×1 返回结构矩阵 */
plhs[0] = mxCreateStructMatrix(1, 1, nfields, fnames);
mxFree(fnames);
ndim = mxGetNumberOfDimensions(prhs[0]);
dims = mxGetDimensions(prhs[0]);
for (ifield = 0; ifield < nfields; ifield++) {
/* 创建 元胞/数值 数组 */
if (classIDflags[ifield] == mxCHAR_CLASS) {
fout = mxCreateCellArray(ndim, dims);
} else {
fout = mxCreateNumericArray(ndim, dims,
classIDflags[ifield], mxREAL);
pdata = mxGetData(fout);
}
/* 从输入结构数组中复制数据 */
for (jstruct = 0; jstruct < NStructElems; jstruct++) {
tmp = mxGetFieldByNumber(prhs[0],jstruct,ifield);
if (mxIsChar(tmp)) {
mxSetCell(fout, jstruct, mxDuplicateArray(tmp));
} else {
size_t sizebuf;
sizebuf = mxGetElementSize(tmp);
memcpy(pdata, mxGetData(tmp), sizebuf);
pdata += sizebuf;
}
}
/* 设定返回结构中每一个域的值 */
mxSetFieldByNumber(plhs[0], 0, ifield, fout);
}
mxFree(classIDflags);
return;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -