title: Most Efficient Way of Using mexCallMATLAB in Converting Double* to mxArray*
body: <p>I am writing a <code>MEX</code> code in which I need to use <code>pinv</code> function. I am trying to find a way to pass the array of type <code>double</code> to <code>pinv</code> using <code>mexCallMATLAB</code> in the most efficient way. Let's for the sake of example say the array is named <code>G</code> and its size is 100.</p>
  
  <pre><code>double *G = (double*) mxMalloc( 100 * sizeof(double) );
  </code></pre>
  
  <p>where</p>
  
  <pre><code>G[0] = G11; G[1] = G12;
  G[2] = G21; G[3] = G22;
  </code></pre>
  
  <p>Which means every four consecutive elements of G is a <code>2×2</code> matrix. <code>G</code> stores <code>25</code> different values of this <code>2×2</code> matrix.</p>
  
  <p><img src="https://i.stack.imgur.com/fuejq.png" alt="enter image description here"></p>
  
  <p>I should note that these <code>2×2</code> matrices are not well-conditioned and they may contain all zero in their element. How can I use <code>pinv</code> function to calculate the pseudoinverse in the elements of <code>G</code>? For example, how can I pass the array to <code>mexCallMATLAB</code> in order to calculate the pseudoinverse of the first <code>2×2</code> matrix in <code>G</code>?</p>
  
  <p>I thought of the following approach:</p>
  
  <pre><code>mxArray *G_PINV_input     = mxCreateDoubleMatrix(2, 2, mxREAL);
  mxArray *G_PINV_output    = mxCreateDoubleMatrix(2, 2, mxREAL);
  double  *G_PINV_input_ptr = mxGetPr(G_PINV_input);
  
  memcpy( G_PINV_input_ptr, &amp;G[0], 4 * sizeof(double));
  mexCallMATLAB(1, G_PINV_output, 1, G_PINV_input, "pinv");
  </code></pre>
  
  <p>I am not sure how good this approach is. Copying the values is not economical at all because the total number of elements in <code>G</code> in my actual application is large. Is there anyway to skip this copying?</p>