Search code examples
c++matlabvisual-studio-2010matrixmex

How to access members of the matrix passed to a MEX function?


I'm writing a program that involves with finding the real roots of quadratic and cubic polynomials and since the roots function in MATLAB is for polynomials with general degree and computationally heavy, I've chosen such function from the GSL Library and I want to MEX it and use it in MATLAB. Here's the code:

/*
 * mx_solve_quadratic.cpp
 *
 * Solves for real roots of the standard quadratic equation
 *
 * The calling syntax is:
 *
 *      rootsMatrix = mx_solve_quadratic(coefficientsMatrix)
 *
 * This is a MEX file for MATLAB.
*/

#include <config.h>
#include <math.h>
#include "mex.h"
#include "matrix.h"

int gsl_poly_solve_quadratic (double , double , double , double *, double *)

/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  double a; /* coefficient for x^2 */
  double b; /* coefficient for x */
  double c; /* coefficient for 1 */
  double *x0 /* pointer to the smaller root */
  double *x1 /* pointer to the bigger root */
  mxGetData(prhs[0])
}


int gsl_poly_solve_quadratic (double a, double b, double c, double *x0, double *x1)
{
  if (a == 0) /* Handle linear case */
    {
      if (b == 0)
        {
          return 0;
        }
      else
        {
          *x0 = -c / b;
          return 1;
        };
    }

  {
    double disc = b * b - 4 * a * c;

    if (disc > 0)
      {
        if (b == 0)
          {
            double r = sqrt (-c / a);
            *x0 = -r;
            *x1 =  r;
          }
        else
          {
            double sgnb = (b > 0 ? 1 : -1);
            double temp = -0.5 * (b + sgnb * sqrt (disc));
            double r1 = temp / a ;
            double r2 = c / temp ;

            if (r1 < r2) 
              {
                *x0 = r1 ;
                *x1 = r2 ;
              } 
            else 
              {
                *x0 = r2 ;
                  *x1 = r1 ;
              }
          }
        return 2;
      }
    else if (disc == 0) 
      {
        *x0 = -0.5 * b / a ;
        *x1 = -0.5 * b / a ;
        return 2 ;
      }
    else
      {
        return 0;
      }
  }
}   

since a matrix of type single is passed to the MEX function, prhs is an mxArray with just one member and that is a matrix with 3 members.
I get this matrix by mxGetData(prhs[0]), but I don't know how to access members inside the matrix and get a,b,c?


Solution

  • simply

     x0=mxGetPr(prhs[0]);
    

    mxGetPr returns double pointer.

    Then you can access to the member of x0 by

     a=x0[0];
     b=x0[1];
     c=x0[2];
    

    If your data type is different from double, you can use

     type variable = (type *) mxGetData(prhs[0]);