Mex-File에서의 셀 배열

Mex-File에서의 셀 배열 (Cell Arrays with Mex-Files)

oct-file에서 셀 배열에 할 수 있는 작업은 mex-file에서도 똑같이 할 수 있어요. oct-file의 celldemo.cc 기능을 mex-file에서 재현하는 mycell.c 예시를 중심으로 살펴볼게요. Appendix A.2.4절을 정리해 봤어요.

출처: Cell Arrays with Mex-Files

본문

oct-file에서 셀 배열에 할 수 있는 것과 정확히 같은 연산을 mex-file에서도 수행할 수 있어요. oct-file celldemo.cc의 기능을 mex-file에서 복제하는 예시가 아래 mycell.c로 주어집니다.

#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-file 버전과 똑같아요.

[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);

더 알아보기

  • octave-mex-files — mex-파일 인터페이스 개요
  • octave-external-code-interface — 외부 코드 인터페이스 개요
  • octave-cell-array-objects — 셀 배열 객체