將vector容器x,y的數據轉換為matlab矩陣mxMatrix的幾種賦值方式:
1:
memcpy(mxGetPr(mxa_x),&x[0], y.size()*sizeof(double));
memcpy(mxGetPr(mxa_y),&y[0], y.size()*sizeof(double));//OK
&x[0]:即是容器元素的首地址
2.
memcpy(mxGetPr(mxa_x),&x.at(0), y.size()*sizeof(double));
memcpy(mxGetPr(mxa_y),&y.at(0), y.size()*sizeof(double));//OK
3.
memcpy(mxGetPr(mxa_x),(void*)&(*x.begin()), y.size()*sizeof(double));
memcpy(mxGetPr(mxa_y),(void*)&(*y.begin()), y.size()*sizeof(double));//OK
&(*x.begin()):表示vector容器的元素的首地址
4 使用copy函數
copy(x.begin(),x.end(),mxGetPr(mxa_x));
copy(y.begin(),y.end(),mxGetPr(mxa_y));//OK
5.
使用matlab函數的庫的操作函數
mxSetPr(mxa_x,&x[0]);
mxSetPr(mxa_y,&y[0]);//OK,**但是不能釋放內存空間**
6.
mxSetData函數暫時未實現
代碼如下:
bool ellipsefit_engine(Engine *ep,double &Xc,double &Yc,double &A,double &B,double &Phi,double &P,vector<double> x,vector<double> y)
{
mxArray *mxa_x, *mxa_y;
mxArray *mxa_Xc = NULL,*mxa_Yc = NULL,*mxa_A = NULL,*mxa_B = NULL,*mxa_Phi = NULL,*mxa_P = NULL;
mxa_x = mxCreateDoubleMatrix(x.size(),1 , mxREAL);
mxa_y = mxCreateDoubleMatrix(y.size(),1 , mxREAL);
//memcpy(mxGetPr(mxa_x),&x[0], y.size()*sizeof(double));
//memcpy(mxGetPr(mxa_y),&y[0], y.size()*sizeof(double));//OK
//memcpy(mxGetPr(mxa_x),&x.at(0), y.size()*sizeof(double));
//memcpy(mxGetPr(mxa_y),&y.at(0), y.size()*sizeof(double));//OK
//memcpy(mxGetPr(mxa_x),(void*)&(*x.begin()), y.size()*sizeof(double));
//memcpy(mxGetPr(mxa_y),(void*)&(*y.begin()), y.size()*sizeof(double));//OK
//copy(x.begin(),x.end(),mxGetPr(mxa_x));
//copy(y.begin(),y.end(),mxGetPr(mxa_y));//OK
//mxSetPr(mxa_x,&x[0]);
//mxSetPr(mxa_y,&y[0]);//OK,但是不能釋放內存空間
//mlfEllipsefit(6, &mxa_Xc,&mxa_Yc,&mxa_A,&mxa_B,&mxa_Phi,&mxa_P, mxa_x, mxa_x);
engPutVariable(ep,"x",mxa_x);
engPutVariable(ep,"y",mxa_y);
mxDestroyArray(mxa_x);
mxDestroyArray(mxa_y);
engEvalString(ep,"userpath('C:\Users\Administrator\Desktop\eclipse_c\test');");
engEvalString(ep,"[Xc,Yc,A,B,Phi,P]=ellipsefit(x,y);");
mxa_Xc=engGetVariable(ep,"Xc");
mxa_Yc=engGetVariable(ep,"Yc");
mxa_A=engGetVariable(ep,"A");
mxa_B=engGetVariable(ep,"B");
mxa_Phi=engGetVariable(ep,"Phi");
mxa_P=engGetVariable(ep,"P");
double *p_Xc = mxGetPr(mxa_Xc);// 將 matlab 中的矩陣的指針傳遞給 C 語言中的指向 double 的指針
Xc=p_Xc[0];
double *p_Yc =mxGetPr(mxa_Yc);
Yc = p_Yc[0];
double *p_A =mxGetPr(mxa_A);
A = p_A[0];
double *p_B =mxGetPr(mxa_B);
B = p_B[0];
double *p_Phi =mxGetPr(mxa_Phi);
Phi = p_Phi[0];
double *p_P =mxGetPr(mxa_P);
P = p_P[0];
return true;
}