title: How to return a matrix structure from a mex function?
body: <p>I have a struct that defines a 3d array, the size is known:</p>
  
  <pre><code>struct uchar3
  {
    unsigned char x, y, z;
  };
  </code></pre>
  
  <p>and I want to return it via mex function in order to use it in matlab like a three dimensional array, like an image. How can this be done?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>This is apart of the function I use.</p>
  
  <pre><code>foo(uchar3 **imagePtr, Mat Im){
  unsigned char *cvPtr = Im.ptr&lt;unsigned char&gt;(0);
      for (size_t i = 0; i &lt; Im.rows * Im.cols; ++i) {
          (*imagePtr)[i].x = cvPtr[3 * i + 0];
          (*imagePtr)[i].y = cvPtr[3 * i + 1];
          (*imagePtr)[i].z = cvPtr[3 * i + 2];
      }
  }
  </code></pre>
  
  <p><strong>Shai's code:</strong></p>
  
  <pre><code>cv::Mat imageRGB;
      cv::cvtColor(OutPutMat, imageRGB, CV_BGR2RGB);
  
      // uc3 is populated here 
      mwSize sz[3];
      sz[0] = imageRGB.rows; // matlab is row first
      sz[1] = imageRGB.cols;
      sz[2] = 3;
      plhs[0] = mxCreateNumericArray( 3, sz, mxDOUBLE_CLASS, // create double array, you can change the type here
          mxREAL ); // create real matrix
      float *cvPtr = imageRGB.ptr&lt;float&gt;(0);
      float* p = (float*)mxGetData(plhs[0]); // get a pointer to actual data
      for ( size_t y = 0 ; y &lt; imageRGB.rows ; y++ ) {
          for ( size_t x = 0; x &lt; imageRGB.cols ; x++ ) {
              int i = y * imageRGB.cols + x; // opencv is col first
              p[ x * imageRGB.rows + y ] = cvPtr[3 * i + 0];
              p[ imageRGB.cols * imageRGB.rows + x * imageRGB.rows + y ] = cvPtr[3 * i + 1];
              p[ 2*imageRGB.cols * imageRGB.rows + x * imageRGB.rows + y ] = cvPtr[3 * i + 2];
          }
      }
  </code></pre>