如何访问传递给MEX函数的矩阵成员
How to access members of the matrix passed to a MEX function?
我正在写一个程序,涉及寻找二次多项式和三次多项式的实根,由于MATLAB中的roots
函数是针对一般次多项式和计算量大的多项式,我从GSL库中选择了这样的函数,我想在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;
}
}
}
由于传递给MEX函数的是一个类型为single的矩阵,因此prhs
是一个只有一个成员的mxArray,而这是一个有3个成员的矩阵。
我通过mxGetData(prhs[0])
得到这个矩阵,但我不知道如何访问矩阵中的成员并得到a
, b
, c
?
simply
x0=mxGetPr(prhs[0]);
mxGetPr
返回double
指针
则可以通过
访问x0
的成员。 a=x0[0];
b=x0[1];
c=x0[2];
如果您的数据类型与double
不同,您可以使用
type variable = (type *) mxGetData(prhs[0]);
相关文章:
- 索引和访问 mex 函数中单元数组和矩阵的元素
- 创建 Matlab MEX 函数时,我是否将 mexFunction 放在 c++ 头文件或源文件中
- MEX文件实现特征库伪内函数崩溃
- 从MEX函数中清除MATLAB命令窗口
- 如何将整数值作为 mex 函数的输入传递?
- 如何使用 Boost 库构建 MEX 函数
- 如何在多线程 MEX 函数中打印到控制台?
- 在 matlab 中编写一个非常基本的 mex 函数
- 网关函数损坏了从matlab到c++mex程序的输入
- 在mex函数中返回双指针2D矩阵
- 如何从mex函数返回矩阵结构
- Mex C++类函数声明
- 无法解析 MEX 函数 Eclipse
- 如何在 Matlab 中分析一个 MEX 函数
- 为什么此 MEX 函数会产生意外结果
- 在不使用mex的情况下,将C++回调作为函数句柄传递给matlab引擎
- 线程成员函数和mex文件因std::bad_alloc而崩溃
- 从Matlab调用的Mex函数和数值差分
- 在mex函数中使用OpenCV:编译后出错
- 如何在 MEX 函数运行时制作它 printf?