Search code examples
c++matlabmex

Getting output of type double in matlab using C++ mex Function


 #define E_OUT plhs[1]      
 double *E;
 double error[training_epochs];
 double err;

 int size_err1 = mxGetM(IN_training_epochs);
 int size_err2 = mxGetN(IN_training_epochs);   

 Dim1 = mxGetScalar(IN_training_epochs);
 Dim2 = 1;
 mexPrintf("Erro_Rows_numb = %d.\n", Dim1);
 mexPrintf("Error_Collums_numb = %d.\n", Dim2);
 E_OUT = mxCreateDoubleMatrix(Dim1, Dim2, mxREAL);
 E = mxGetPr(E_OUT); // getting the value of data to which E_OUT points at

 for(int epoch=0; epoch<training_epochs; epoch++)
  {
     err = 0;

        for(int i=0; i<sizeTrain_X2; i++)

        {     

     rbm.contrastive_divergence(&train_X[sizeTrain_X2*i],       learning_rate, k);
     rbm.reconstruct(&train_X[sizeTrain_X1*i], reconstructed_X[i]);

         for (int j=0; j< n_visible; j++)
          {             
           err += pow(train_X[n_hidden*i+j] - reconstructed_X[i][j],2);
          }  
         }
          error[epoch] = err; 
        }

From the above code i have been computing the reconstructed error from my RBM input matrix, and i need to retrieve it in matlab using mexFunction. but still struggling with how to point the stored data in my variable error to plhs[1].


Solution

  • Looks like two things you're missing are:

    plhs[0] = mxCreateDoubleMatrix(Dim1, Dim2, mxREAL);
    

    Arrays in c are 0 indexed so it should be plhs[0] for the first item returned. To copy in the data from your error:

    memcpy(mxGetPr(plhs[0]), error, Dim1*sizeof(double));