c++调用matlab

1.执行mcc -W lib:liba -T link:lib  oula 生成liba.dll及头文件
2.编译以下c代码,该代码写了一个mxMatDbl类

// callMatlab.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include 
<windows.h>
#include 
<matrix.h>
#include 
"../liba.h"

class mxMatDbl
{
    
public:
    mxArray 
*m_array;
    mxMatDbl()
    
{
        m_array
=0;
    }

    mxMatDbl(
int h,int w,const double * pData)
    
{
        m_array
=mxCreateDoubleMatrix(h,w, mxREAL); 
        
if(pData)
            memcpy(mxGetPr(m_array),pData,h
*w*sizeof(double));
    }


    
double * getPtr()
    
{
        
return mxGetPr(m_array);
    }

    
operator double *()
    
{
        
return mxGetPr(m_array);
    }

    
operator mxArray *()
    
{
        
return m_array;
    }

    
double & operator ()(int y,int x)
    
{
        assert(m_array);
        
int W=w();
        
int H=h();
        assert(y
>=0 && y<&& x>=0 && x<W);
        
return *(mxGetPr(m_array)+ y*+ x);
    }


    
int h()
    
{
        
return mxGetM(m_array);
    }

    
int w()
    
{
        
return mxGetN(m_array);
    }

    
void Release()
    
{
        
if(m_array)
        
{
            mxDestroyArray(m_array);
            m_array
=0;
        }

    }


    
~mxMatDbl()
    
{
        Release();
    }


    
void Print()
    
{
        
for (int y=0;y<h();y++)
        
{
            
for (int x=0;x<w();x++)
            
{
                printf(
"%g ",(*this)(y,x));
            }

            printf(
"\n");
        }

    }

protected:
private:
}
;

void TestMxMatDbl()
{
    
double data[6]={1.0 ,2.0 ,3.0 ,4.0,5.0,6.0};
    mxMatDbl m(
2,3,data);
    printf(
"w %d,h %d\n",m.w(),m.h());
    
for (int y=0;y<m.h();y++)
    
{
        
for (int x=0;x<m.w();x++)
        
{
            printf(
"%g ",m(y,x));
        }

        printf(
"\n");
    }

}


void callMatlab()
{
    libaInitialize();
    
double _r[]={0,0,0};
    mxMatDbl r(
3,1,_r);
    mxMatDbl R(
3,3,0);
    
if(0)
    
{//这一局怎么不行??
        mxArray *prhs[1];prhs[0]=r.m_array;
        mxArray 
*plhs[1];plhs[0]=R.m_array;
        mlxOula(
1, plhs, 1, prhs);
    }

    
else
        mlxOula(
1&R.m_array, 1&r.m_array);
    r.Print();
    R.Print();
    libaTerminate();
}

int main(int argc, char* argv[])
{
    
//TestMxMatDbl();
    callMatlab();
    
return 0;
}


原文地址:https://www.cnblogs.com/cutepig/p/994140.html