【发布时间】:2016-08-28 19:52:17
【问题描述】:
我正在编写一个程序,该程序涉及找到二次和三次多项式的实根,并且由于 MATLAB 中的 roots 函数适用于具有一般程度和计算量大的多项式,因此我从 @987654321 中选择了这样的函数@ 我想 MEX 它并在 MATLAB 中使用它。代码如下:
/*
* 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;
}
}
}
由于将 single 类型的矩阵传递给 MEX 函数,prhs 是一个只有一个成员的 mxArray,它是一个有 3 个成员的矩阵。
我通过mxGetData(prhs[0])得到了这个矩阵,但是我不知道如何访问矩阵内部的成员并得到a,b,c?
【问题讨论】:
标签: c++ matlab visual-studio-2010 matrix mex