Search code examples
c++matlabmex

What did I do wrong with mxGetPr


Please consider this excerpt of code within mexFunction

\\cppfunc.cpp

void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]){

  \\...Parts where I check the number of lhs and rhs

  double* upper = mxGetPr(prhs[0]);
  double* lower = mxGetPr(prhs[1]);
  double* grids = mxGetPr(prhs[2]);

  mexPrintf("upper 1=%d  \n\n", upper[0] ); 

}

I planned to call my mex function like this cppfunc([1 2 3], [1 2 3], [1 2 3]). Basically, it takes in three MATLAB vectors and prints out the first element of the first input vector through mexPrintf. The output should be 1. However, it returns:

upper 1=3.

It seems to me that the function is returning the length of the first input vector. For example, if I do cppfunc([1 2 3 4], [1 2 3], [1 2 3]), it would return upper 1=4.

I thought I was right by using %d in my call to mexPrintf since mxGetPr converts the input to an array of doubles. What did I miss?


Solution

  • Format %d is for integers values of type int. You have to use %f for doubles.
    See documentation of printf.