Search code examples
cmatlabmex

mex: Calculation right; but, I am getting wrong output


I am trying to use mex to be able to call c-function from Matlab.

It seems that I can get inputs right and even calculations are right. But, it returns wrong input. Somehow I am messing up with output pointer Please help.

Matlab code:

cd /home/dkumar/MatlabCodes_DKU;
smA_System = ConstructSystemMatrix();

Dir2  = '/home/dkumar/Mex_Codes_DKU/MexCode_Working/Mex_C_Codes_DKU_makefile_Working';

% MEX
cd(Dir2);
system('make');
tic
    y = normpdfDKU(1/2,0,1)
toc

C-code

#include "mex.h"
#include <math.h>
#include <stdio.h>

/* using namespace std; */

#define pi (3.141592653589793)

extern void _main();

const int numInputArgs  = 3;
const int numOutputArgs = 1;

// Function declarations.
// -----------------------------------------------------------------
double  getMatlabScalar    (const mxArray* ptr);
//double& createMatlabScalar (mxArray*& ptr);

// Function definitions.
// -----------------------------------------------------------------
void mexFunction (int nlhs, mxArray *plhs[],
          int nrhs, const mxArray *prhs[]) {


  int res = TestingLibraries() ; 

  //declare variables
  mxArray *c_out_m;
  double  *c, p, c1;

  #define B_OUT plhs[0]

  // Check to see if we have the correct number of input and output
  // arguments.
  if (nrhs != numInputArgs)
    mexErrMsgTxt(" DKU-1: Incorrect number of input arguments");
  if (nlhs != numOutputArgs)
    mexErrMsgTxt("DKU-2: Incorrect number of output arguments");

  // Get the inputs.
  double x  = getMatlabScalar(prhs[0]);
  double mu = getMatlabScalar(prhs[1]);
  double v  = getMatlabScalar(prhs[2]);

  // Create the output. It is also a double-precision scalar.
  //double& p = createMatlabScalar(plhs[0]);

  //associate outputs
  plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
  //associate pointers
  c = mxGetPr(plhs[0]);

  // Compute the value of the univariate Normal at x.
  p = (double)(exp(-(x-mu)*(x-mu)/(2*v)) / sqrt(2*pi*v));
  printf("First normal value: %f\n", p);

  c = &p; 
}

double getMatlabScalar (const mxArray* ptr) {

  // Make sure the input argument is a scalar in double-precision.
  if (!mxIsDouble(ptr) || mxGetNumberOfElements(ptr) != 1)
    mexErrMsgTxt("The input argument must be a double-precision scalar");

  return *mxGetPr(ptr);
}

Output:

First normal value: 0.352065

y =

     0

Elapsed time is 0.002202 seconds.

Solution

  • The problem is here

    c = &p;
    

    You're relocating the pointer c so that it now points to the address of p.

    What you want to do is copy the contents of p to the address currently pointed to by c (the real part of the scalar you previously created).

    *c = p;