title: How to pass Matlab m x n cell matrix argument in C++ mex function?
body: <p>I want to pass such a cell matrix created in Matlab as input argument to mex function,</p>
  
  <pre><code>for i=1:5,
      p{i}=rand(3,4);
  end
  </code></pre>
  
  <p>and then return it as as an 3 dimensional double array as output argument.
  intended syntax:</p>
  
  <pre><code>Parray = convert(p);
  </code></pre>
  
  <p>where Parray is a 3-by-4-by-5 numerical array and P(:,:,i) = p{i};</p>
  
  <p>The following code I am using can be successfully built into desired mex function:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;math.h&gt;
  #include &lt;matrix.h&gt;
  #include &lt;cstring&gt;
  #include &lt;string&gt;
  #include "mex.h"
  
  
  using namespace std;
  
  void mexFunction( int nlhs, mxArray *plhs[],
                    int nrhs, const mxArray *prhs[] )
  {
  
  if (nlhs&gt;=1 &amp;&amp; nrhs&gt;=1){
          int       nsubs =2,  index;
          mwIndex   subs[]={0, 0};
          mxArray   *tmp;
          double     **buf;
  
          int cameraNum = mxGetNumberOfElements(prhs[0]);
          mwIndex  dims[]={cameraNum,3,4};
          plhs[0] = mxCreateNumericArray(3,dims,mxDOUBLE_CLASS,mxREAL);
          mexPrintf("there are %d cameras in the input cell.",cameraNum);
  
          /* allocate memory  for storing pointers */
  
          buf = (double**)mxGetData(plhs[0]);
  
          for (int i=0; i&lt;cameraNum; i++){
              subs8[1] = i;
  
              // get the cell (i,1)
              index = mxCalcSingleSubscript(prhs[1], nsubs, subs);
              tmp = mxGetCell(prhs[0],index);
  
              buf[i] = (double*)mxGetData(tmp); 
              int rownum = mxGetM(tmp);
              int colnum = mxGetN(tmp);
              mexPrintf("\n No. %d camera matrix is: \n",i);
              for(int m=0;m&lt;rownum;m++){
                  for(int n=0; n&lt;colnum;n++){
                      mexPrintf("%lf\t",buf[i][m*colnum+n]);
                  }
              }
  
          }
          mxFree(buf);
      }
  
      return;
  }
  </code></pre>
  
  <p>However, it causes Matlab's collapse due to unknown reason.
  What is the reason? and How can I get rid of the problem?</p>
  
  <p>Additionally, if the desired syntax is :</p>
  
  <pre><code>Parray = convert(p);
  </code></pre>
  
  <p>and Parray is exactly the same as p, how to implement in C++ mex function?</p>
  
  <p>Thanks</p>