码迷,mamicode.com
首页 > 编程语言 > 详细

VC和matleb混合编程之mx矩阵赋值(C语言)

时间:2015-04-27 11:14:46      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:c语言   matlab   混合编程   

将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;
}

VC和matleb混合编程之mx矩阵赋值(C语言)

标签:c语言   matlab   混合编程   

原文地址:http://blog.csdn.net/u010177286/article/details/45307475

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!