A.2.4 带有 Mex 文件的元胞数组

在mex文件中可以对元胞数组执行与oct文件中完全相同的操作。下面给出的示例文件mycell.c在mex文件中实现了与celldemo.cc oct文件相同的功能,如下所示。

#include "mex.h"

void
mexFunction (int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[])
{
  mwSize n;
  mwIndex i;

  if (nrhs != 1 || ! mxIsCell (prhs[0]))
    mexErrMsgTxt ("ARG1 must be a cell");

  n = mxGetNumberOfElements (prhs[0]);
  n = (n > nlhs ? nlhs : n);

  for (i = 0; i < n; i++)
    plhs[i] = mxDuplicateArray (mxGetCell (prhs[0], i));
}

输出也与oct文件的版本相同。

[b1, b2, b3] = mycell ({1, [1, 2], "test"})
⇒ 
b1 =  1
b2 =

   1   2

b3 = test

请注意在示例中使用了mxDuplicateArray函数。这是必要的,因为mxGetCell返回的mxArray指针可能会被释放。mxGetCell的反函数,用于设置元胞值,是mxSetCell,其定义如下:

void mxSetCell (mxArray *ptr, int idx, mxArray *val);

最后,要创建元胞数组或矩阵,相应的函数为:

mxArray *mxCreateCellArray (int ndims, const int *dims);
mxArray *mxCreateCellMatrix (int m, int n);

版权所有 © 2024-2026 Octave中文网

ICP备案/许可证号:黑ICP备2024030411号-2