我有一个代码。但我不知道如何保存输出(点*)。我试图将float * out
保存到plhs
。打印结果是对的。有没有可用的例子,因为我找不到合适的例子。
感谢您的回答。我没有任何错误。但打印的结果是对的。但是在Matlab中,out都是零。
我初始化out
都是零。但在我调用pointwise_search后,out
没有变化。
如果我使用out = pointwise_search(q,p,num_thres,x,len),问题就解决了。
#include "mex.h"
#include "matrix.h"
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
void pointwise_search(double *p,double *q,int num_thres, double* n, int len, double * out )
{
vector<double> P(p, p + num_thres);
vector<double> Q(q, q + num_thres);
int size_of_threshold = P.size();
double * Y;
double *z=new double[len];
typedef vector<double > ::iterator IntVectorIt ;
IntVectorIt start, end, it, location ;
start = P.begin() ; // location of first
// element of Numbers
end = P.end() ; // one past the location
// last element of Numbers
for (int i=0;i<len;i++)
{
location=lower_bound(start, end, n[i]) ;
z[i]=location - start;
if(z[i]>0&&z[i]<=size_of_threshold-1)
{
out[i]=(n[i]-P[z[i]])/(P[z[i]-1]-P[z[i]])*(Q[z[i]-1]-Q[z[i]])+Q[z[i]];
}
else if (z[i]>size_of_threshold-1)
{
out[i]=Q[z[i]-1];
}
else
{
out[i]=Q[z[i]];
}
}
delete []z;
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double * out;
double *n = (double*) mxGetData(prhs[3]);
int len = (int) mxGetScalar(prhs[4]);
int num_thres = (int) mxGetScalar(prhs[2]);
mexPrintf("len=%d\n ",len);
mexPrintf("num_thres=%d\n ",num_thres);
double * Numbers= (double *)mxGetData(prhs[0]);
double * Q= (double *)mxGetData(prhs[1]);
mexPrintf("Q[4]=%f\n ",Q[4]);
plhs[0] = mxCreateNumericMatrix(len, 1,mxSINGLE_CLASS, mxREAL); /* Create the output matrix */
out = (double *)mxGetPr(plhs[0]);
pointwise_search(Numbers,Q,num_thres,n,len,out );
mexPrintf("out[4]=%f\n ",out[0]);
mexPrintf("out[4]=%f\n ",out[1]);
mexPrintf("out[4]=%f\n ",out[2]);
}
答案 0 :(得分:3)
您不应直接指定out
值。
检查出来(C代码应该足够了):
首先,使用不同的变量和类型映射MEX功能接口存储器。
然后,将所有这些传递给实际的C函数。
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int num;
float *A;
double *out;
//mxLogical, etc
/* Extract the inputs */
num = (int)mxGetScalar(prhs[0]);
A = (float *)mxGetData(prhs[1]);
// You can get sizes of A with mxGetM/mxGetN functions
/* Setup the output */
// It's 1x1 matrix of doubles here.
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
out = mxGetPr(plhs[0]);
/* Do the actual work */
// If you need to iterate over A, pass M,N values here also
your_function(num, A, out);
}
最后,C函数应该通过指针设置out
值。
// And declare M,N here as inputs
void your_function(const int num, const float* A, double *out)
{
//Some code. Operate with `num`, `A`, etc
*out = DBL_MAX;
}
哦,为double
写了这个。对于float
和其他类型,请使用mxCreateNumericMatrix(1, 1, mxSINGLE_CLASS, mxREAL)
代替mxCreateDoubleMatrix(1, 1, mxREAL)
。
这也是link to check。