Monday, February 9, 2009

MATLAB工具箱BP神经网络应用介绍(1)

MATLAB神经网络工具箱中包含了许多BP神经网络相关函数,本文主要将主要介绍BP神经网络创建函数newff函数,重点介绍BP神经网络的训练函数。
1.BP网络创建函数newff函数
MATLAB神经网络工具箱中,使用newff函数创建一个反向传播算法的BP网络。其调用格式如下:
net = newff(PR,[S1 S2...SNl],{TF1 TF2...TFNl},BTF,BLF,PF)
在输入参数中,PR为R维的输入元素的R×2最大最小值矩阵;Si为第i层网络神经元的个数,共有N1层;TFi为第i层网络的转移函数,默认为tansig函数;BTF为神经网络的训练函数,默认为trainlm函数;BLF为神经网络权值/偏差的学习函数;PF为性能评价函数,默认为mse函数。在BP网络中原理介绍中,介绍了几种不同的转移函数及它们的曲线特性,在下面章节中,将详细地介绍BP神经网络不同的训练函数。在这里同样使用例14.3中蠓虫分类问题的数据,建立BP神经网络,使用不同的训练函数进行网络训练。
% 输入样本
P=[1.24 1.36 1.38 1.38 1.38 1.4 1.48 1.54 1.56 1.14 1.18 1.2 1.26 1.28 1.3;
1.72 1.74 1.64 1.82 1.9 1.7 1.82 1.82 2.08 1.78 1.96 1.86 2.0 2.0 1.96];
% 目标样本
T=[1 1 1 1 1 1 1 1 1 0 0 0 0 0 0];
%检验样本
p=[1.24,1.28,1.4;1.8,1.84,2.04];
%创建一个两层的BP神经网络,转移函数分别为logsig函数和purelin函数
net=newff(minmax(P),[5,1],{'logsig','purelin'});
A = sim(net,P);
没有经过训练的神经网络输出情况为:
A =
Columns 1 through 8
1.2514 0.7697 0.7263 0.7536 0.6203 0.5283 0.4206 0.2528
Columns 9 through 15
0.4334 1.2217 0.6259 0.8826 0.5589 0.5563 0.5717
可以发现,此时网络的输出与目标样本的误差非常大。
2.BP网络训练函数
MATLAB神经网络工具箱提供了大量的BP网络训练函数,包括反向传播算法函数、自适应学习速率算法函数、共扼梯度算法函数、线性搜索函数和拟牛顿法函数等。
(1)traingd函数
traingd函数使用梯度下降算法训练神经网络,通过net.trainParam可以查看traingd函数网络训练的相关参数。
net=newff(minmax(P),[5,1],{'logsig','purelin'},'traingd');
>> net.trainParam
ans =
epochs: 100 %最大的迭代次数
goal: 0 %训练目标
lr: 0.0100 %学习速率
max_fail: 5
min_grad: 1.0000e-010
show: 25
time: Inf
使用traingd函数进行蠓虫分类,在MATLAB命令行窗口中输入:
net=newff(minmax(P),[5,1],{'logsig','purelin'},'traingd');
net.trainParam.show = 50;
net.trainParam.lr = 0.2;
net.trainParam.epochs = 300;
net.trainParam.goal = 0.01;
[net,tr]=train(net,P,T);
%回代检验
A=sim(net,P);
%测试样本检验
a=sim(net,p);

训练过程及测试样本检验结果如下:
TRAINGD-calcgrad, Epoch 0/300, MSE 1.26821/0.01, Gradient 4.27366/1e-010
TRAINGD-calcgrad, Epoch 50/300, MSE 0.0224145/0.01, Gradient 0.0415513/1e-010
TRAINGD-calcgrad, Epoch 100/300, MSE 0.0123293/0.01, Gradient 0.0241917/1e-010
TRAINGD-calcgrad, Epoch 125/300, MSE 0.0099568/0.01, Gradient 0.0194082/1e-010
TRAINGD, Performance goal met.
a =
0.5978 0.6097 0.3808
网络训练过程均方差下降曲线如下图所示。为了比较各种不同训练函数的特点,在后面的实例中,将统一使用蠓虫分类问题的训练样本数据和测试样本数据。


More details could be found in my published book:
MATLAB编程基础与典型应用
北京:人民邮电出版社,2008
ISBN:978-7-115-17932-6/TP

Pls contact me with Email:lhd06@mails.tsinghua.edu.cn

更多MATLAB交流资源,欢迎访问:
  • Solve nonlinear least-squares (nonlinear data-fitt...

  • 非线性最小二乘曲线拟和问题

  • Visual C++中创建MAT文件

  • Visual C++中使用MATLAB语言C,C++数学函数库

  • Visual C++中调用MATLAB引擎配置

  • MATLAB引擎技术介绍

  • MATLAB里关于集合运算和二进制数的运算的函数

  • 在Matlab图形中怎样输入特殊符号

  • 怎么把Matlab中数组元素写入到文本文档中

  • 在同一个M文件中,怎样实现参数的传递

  • SimPowerSystem工具箱使用注意事项

  • 在MATLAB/Simulink环境中编辑Scope中的图形方法
  • Friday, February 6, 2009

    Solve nonlinear least-squares (nonlinear data-fitting) problem

    Solve nonlinear least-squares (nonlinear data-fitting) problem

    View Source
    In the MATLAB optimization toolbox,function lsqnonlin could be used to solve nonlinear least-squares or nonlinear data-fitting problems。The function's invoke format is as follows:
    x = lsqnonlin(fun,x0)
    x = lsqnonlin(fun,x0,lb,ub)
    x = lsqnonlin(fun,x0,lb,ub,options)
    [x,resnorm] = lsqnonlin(...)
    [x,resnorm,residual] = lsqnonlin(...)
    [x,resnorm,residual,exitflag] = lsqnonlin(...)
    [x,resnorm,residual,exitflag,output] = lsqnonlin(...)
    [x,resnorm,residual,exitflag,output,lambda] = lsqnonlin(...)
    [x,resnorm,residual,exitflag,output,lambda,jacobian] = lsqnonlin(...)
    There is another function lsqcurvefit could also be availabe in solving the nonlinear LS problems or nonlinear data-fitting problems。Lsqcurvefit could be invoked like this:
    x = lsqcurvefit(fun,x0,xdata,ydata)
    x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub)
    x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub,options)
    [x,resnorm] = lsqcurvefit(...)
    [x,resnorm,residual] = lsqcurvefit(...)
    [x,resnorm,residual,exitflag] = lsqcurvefit(...)
    [x,resnorm,residual,exitflag,output] = lsqcurvefit(...)
    [x,resnorm,residual,exitflag,output,lambda] = lsqcurvefit(...)
    [x,resnorm,residual,exitflag,output,lambda,jacobian] = lsqcurvefit(...)
    And now I will show you an example of non-linear data-fitting problem using both the functions lsqnonlin and lsqcurvefit, and more, I will compare the result in both functions.

    Firstly,plot the given data and determine what kind of nonlinear function could be suitable for fitting the given data.
    xdata =[0,4,6,10,12,16,22,26,30];
    ydata =[-33.8980,-13.3859,-6.2068,1.9980,3.0236,-1.0788,-22.6163,-47.2308,-80.0499];
    plot(xdata,ydata,'bo');
    title('original data points');

    Lsqnonlin
    In order to use the lsqnonlin function to realize the data-fitting, the objective nonlinear fitting function has to be prescribedly established.
    function [feval]=curvefit_fun(x,xdata,ydata)
    yval=x(1)*(xdata-x(2)).^2+x(3);
    feval=yval-ydata;
    And then, enter the follwing commands in the MATLAB commands workspace:
    x0=[0;0;0];
    [x,resnorm,residual,exitflag,output] = lsqnonlin(@(x)curvefit_fun(x,xdata,ydata),x0)
    x1=linspace(min(xdata),max(xdata),1000);
    y1=x(1)*(x1-x(2)).^2+x(3);
    hold on
    plot(x1,y1,'r-');
    legend('数据点','lsqnonlin函数拟和曲线')
    The fitting curve is as:

    Lsqcurvefit
    Firstly, the objective fitting curve function should be established. You ought to pay attention to the differences of the two objectives in Lsqnonlin and lsqcurvefit:

    function [feval]=curvefit_fun(x,xdata)
    feval=x(1)*(xdata-x(2)).^2+x(3);
    And then, enter the following commands in the MATLAB command workspace:

    x0=[0;0;0];
    [x,resnorm,residual] = lsqcurvefit(@(x,xdata)curvefit_fun(x,xdata),x0,xdata,ydata)
    x1=linspace(min(xdata),max(xdata),1000);
    y1=x(1)*(x1-x(2)).^2+x(3);
    hold on
    plot(x1,y1,'r-')
    legend('数据点','lsqcurvefit拟和曲线')
    The result is:

    More details could be found in my published book:
    MATLAB编程基础与典型应用
    北京:人民邮电出版社,2008
    ISBN:978-7-115-17932-6/TP

    Pls contact me with Email:lhd06@mails.tsinghua.edu.cn

    更多MATLAB资源,欢迎交流:
  • 非线性最小二乘曲线拟和问题

  • Visual C++中创建MAT文件

  • Visual C++中使用MATLAB语言C,C++数学函数库

  • Visual C++中调用MATLAB引擎配置

  • MATLAB引擎技术介绍
  • Thursday, February 5, 2009

    非线性最小二乘曲线拟和问题

    非线性最小二乘曲线拟和问题

    MATLAB优化工具箱中,使用lsqnonlin函数可以进行非线性最小二乘问题以及非线性曲线拟和问题。其调用格式如:
    x = lsqnonlin(fun,x0)
    x = lsqnonlin(fun,x0,lb,ub)
    x = lsqnonlin(fun,x0,lb,ub,options)
    [x,resnorm] = lsqnonlin(...)
    [x,resnorm,residual] = lsqnonlin(...)
    [x,resnorm,residual,exitflag] = lsqnonlin(...)
    [x,resnorm,residual,exitflag,output] = lsqnonlin(...)
    [x,resnorm,residual,exitflag,output,lambda] = lsqnonlin(...)
    [x,resnorm,residual,exitflag,output,lambda,jacobian] = lsqnonlin(...)
    使用非线性最小二乘求解函数lsqnonlin或者lsqcurvefit同样可以进行最小二乘的曲线拟合。Lsqcurvefit函数调用格式如下:
    x = lsqcurvefit(fun,x0,xdata,ydata)
    x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub)
    x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub,options)
    [x,resnorm] = lsqcurvefit(...)
    [x,resnorm,residual] = lsqcurvefit(...)
    [x,resnorm,residual,exitflag] = lsqcurvefit(...)
    [x,resnorm,residual,exitflag,output] = lsqcurvefit(...)
    [x,resnorm,residual,exitflag,output,lambda] = lsqcurvefit(...)
    [x,resnorm,residual,exitflag,output,lambda,jacobian] = lsqcurvefit(...)

    以下通过实例比较二者的区别:
    首先需要绘制数据点图形,确定拟和数据点的大致曲线形式。
    xdata =[0,4,6,10,12,16,22,26,30];
    ydata =[-33.8980,-13.3859,-6.2068,1.9980,3.0236,-1.0788,-22.6163,-47.2308,-80.0499];
    plot(xdata,ydata,'bo');
    title('original data points');

    Lsqnonlin函数
    使用最小二乘法进行非线性曲线的拟和,首先需要建立目标函数的M文件:
    function [feval]=curvefit_fun(x,xdata,ydata)
    yval=x(1)*(xdata-x(2)).^2+x(3);
    feval=yval-ydata;

    在命令窗口中运行以下程序段:
    x0=[0;0;0];
    [x,resnorm,residual,exitflag,output] = lsqnonlin(@(x)curvefit_fun(x,xdata,ydata),x0)
    x1=linspace(min(xdata),max(xdata),1000);
    y1=x(1)*(x1-x(2)).^2+x(3);
    hold on
    plot(x1,y1,'r-');
    legend('数据点','lsqnonlin函数拟和曲线')

    lsqnonlin函数拟和曲线结果如图11.10所示。多项式曲线的系数向量及拟和曲线在散点处的留数及留数平方和数据如下:

    x =
    -0.2564
    12.0000
    3.0232
    resnorm =
    9.5716e-007
    residual =
    1.0e-003 *
    -0.1805 -0.4245 -0.3716 -0.4164 -0.4139 -0.3594 -0.2535 0.0665 0.2526

    运行结果如图:



    Lsqcurvefit函数曲线拟和
    首先,同样需要建立拟和曲线的目标函数,注意不同函数,目标函数的定义不完全相同:

    function [feval]=curvefit_fun(x,xdata)
    feval=x(1)*(xdata-x(2)).^2+x(3);

    MATLAB的命令行窗口中输入以下程序段:

    x0=[0;0;0];
    [x,resnorm,residual] = lsqcurvefit(@(x,xdata)curvefit_fun(x,xdata),x0,xdata,ydata)
    x1=linspace(min(xdata),max(xdata),1000);
    y1=x(1)*(x1-x(2)).^2+x(3);
    hold on
    plot(x1,y1,'r-')
    legend('数据点','lsqcurvefit拟和曲线')

    运行结果如下:
    x =
    -0.2564
    12.0000
    3.0232
    resnorm =
    9.5716e-007
    residual =
    1.0e-003 *
    -0.1805 -0.4245 -0.3716 -0.4164 -0.4139 -0.3594 -0.2535 0.0665 0.2526

    运行结果如图:

    More details could be found in my published book:
    MATLAB编程基础与典型应用
    北京:人民邮电出版社,2008
    ISBN:978-7-115-17932-6/TP

    Pls contact me with Email:lhd06@mails.tsinghua.edu.cn

    Wednesday, February 4, 2009

    Visual C++中创建MAT文件

    Visual C++中创建MAT文件

    Visual C++开发环境中,可以利用API函数库的MAT函数库,写入和读出MAT数据文件。通过这种数据文件的读写,可以有效地实现Visual C++环境同MATLAB开发环境的数据通信接口。以下matCreatCDemo.c文件为在Visual C++环境下实现MAT数据文件的读写操作,程序代码如下:
    /*
    * matCreatCDemo.c
    */
    #include
    #include
    #include
    #include "mat.h"
    int main()
    {
    //MATFile文件定义,mxArray变量定义
    const char *filename = "MatDemo.mat";
    MATFile *file;
    int flag1,flag2,flag3;
    mxArray *pString, *pArray1, *pArray2;
    // 初始数据定义
    double a1[] = {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0};
    double a2[] = {9.0, 4.0,5.4,6.4,3.2,1.5};
    // 创建MAT文件
    printf("Creating file %s...\n\n",filename);
    file = matOpen(filename,"w");
    if ( file == NULL )
    {
    printf("ERROR: Can not create file %s\n", filename);
    return(EXIT_FAILURE);
    }
    // 创建字符串mxArray数据结构变量
    pString = mxCreateString("This is the MAT demo in C lanuage! Enojy it~!");
    if (pString == NULL)
    {
    printf("ERROR: Unable to create string!");
    return(EXIT_FAILURE);
    }
    //创建矩阵mxArray数据结构变量
    pArray1 = mxCreateDoubleMatrix(3,3,mxREAL);
    pArray2 = mxCreateDoubleMatrix(2,3,mxREAL);
    if( (pArray1 == NULL)(pArray2 ==NULL) )
    {
    printf("Error: Cannot create the double matrix!");
    return(EXIT_FAILURE);
    }
    // 将初始数据拷贝给mxArray数据结构变量
    memcpy( (void *)(mxGetPr(pArray1)), (void *)a1, sizeof(a1));
    memcpy( (void *)(mxGetPr(pArray2)), (void *)a2, sizeof(a2));
    // 向MAT文件中写入变量
    flag1 = matPutVariable(file, "variableString", pString);
    flag2 = matPutVariable(file, "variableDoubleMatrix1", pArray1);
    flag3 = matPutVariable(file, "variableDoubleMatrix2", pArray2);
    if(( flag1 != 0)(flag2 != 0)(flag3 != 0))
    {
    printf("Can not write variable into the file %s \n", filename);
    return(EXIT_FAILURE);
    }
    // 释放内存空间
    mxDestroyArray(pString);
    mxDestroyArray(pArray1);
    mxDestroyArray(pArray2);
    // 关闭MAT文件
    if(matClose(file) != 0)
    {
    printf("ERROR: Can not close %s file.\n",filename);
    return(EXIT_FAILURE);
    }
    // 重新打开MAT文件
    file = matOpen(filename, "r");
    if (file == NULL)
    {
    printf("ERROR: Can not open file %s\n", filename);
    return(EXIT_FAILURE);
    }
    // 读取MAT文件的数据变量
    pArray1 = matGetVariable(file, "variableDoubleMatrix1");
    pArray2 = matGetVariable(file, "variableDoubleMatrix2");
    pString = matGetVariable(file, "variableString");
    if ( (pArray1 == NULL) (pArray2 == NULL) (pString == NULL))
    {
    printf("ERROR: Can not reading variables from file %s\n",filename);
    return(EXIT_FAILURE);
    }
    // 释放内存空间
    mxDestroyArray(pArray1);
    mxDestroyArray(pArray2);
    mxDestroyArray(pString);
    // 关闭MAT文件
    if (matClose(file) != 0)
    {
    printf("ERROR: Can not close file %s\n",filename);
    return(EXIT_FAILURE);
    }

    printf("Complete!\n");
    return(EXIT_SUCCESS);
    }
    More details could be found in my published book:
    MATLAB编程基础与典型应用
    北京:人民邮电出版社,2008
    ISBN:978-7-115-17932-6/TP

    Pls contact me with Email:lhd06@mails.tsinghua.edu.cn

    Visual C++中使用MATLAB语言C,C++数学函数库

    Visual C++中使用MATLAB语言C,C++数学函数库


    MATLAB开发环境的C,C++数学函数库以mwArray结构体为数据核心,使用mcc命令将M文件转换成的C/C++文件可以直接在Visual C++开发环境中使用,但是编译后的C,C++文件一般程序冗长,代码可读性较差。在熟练掌握C, C++数学函数库的基础上,读者可以使用mwArray结构体自行编写基于应用程序接口(API)函数库C, C++数学库的C/C++文件,可以极大优化程序代码,减少程序代码存储空间,提高程序代码的执行效率和执行速度。在下文的讲述中,将通过一个简单实例来演示如何利用mcc命令创建独立与MATLAB平台运行的exe文件。


    首先使用MATLAB的M语言建立用户所需要的特定功能M 文件,在这里,为了简单而言,建立一个实现魔方阵功能的M文件magicCreat.m。>


    function y = magicCreat(n)
    y = magic(n)
    然后从%matlabroot%\ extern\examples\compiler (%matlabroot%为读者计算机系统中MATLAB的安装路径,本文中为
    C:\Program Files\MATLAB\R2006a\extern\examples\compiler)
    路径下拷贝main_for_lib.c和main_for_lib.h.到当前的工作路径下,以便mcc编译命令调用。然后创建调用magicCreat.m文件的C语言程序如下:
      
    #include
    #include
    #include "libPkg.h" //编译建立的库头文件
    main( int argc, char **argv )
    {
    mxArray *N; /* 输入变量矩阵指针 */
    mxArray *R = NULL; /* 结果矩阵指针 */
    int n; //默认的M文件输入变量数值
    /* 获取命令行参数,如果命令行输入小于2,则输入参数默认为5 */
    if (argc >= 2) {
    n = atoi(argv[1]);
    } else {
    n = 5;
    }
    //初始化MCR和libPkg函数库
    mclInitializeApplication(NULL,0);
    libPkgInitialize();
    /* 得到输入参量的数值 */
    N = mxCreateDoubleScalar(n);
    /*调用magicCreat.m编译后的文件mlfMagicCreat*/
    mlfMagicCreat(1, &R, N);
    /* 释放内存空间*/
    mxDestroyArray(N);
    mxDestroyArray(R);
    //结束libPkg库和MCR
    libPkgTerminate();
    mclTerminateApplication();
    }
    其中libPkg.h为mcc命令编译后的库文件。该文件结构清晰,首先程序代码包含相关必要的头文件和libPkg.h文件,主程序入口,变量的定义,然后初始化MCR和libPkg函数库,调用magicCreat.m编译后的文件mlfMagicCreat,调用结果用矩阵R存储,最后释放内存空间,并结束libPkg库和MCR。在程序结束之前及时地释放内存空间是一个很好的编程习惯。将该程序存储为magicCreatCFile.c,接下来使用mcc命令编译该文件,在MATLAB命令行窗口中输入:
     mcc -W lib:libPkg -T link:exe magicCreat magicCreatCFile.c main_for_lib.c
    经过mcc命令编译后,可以发现在当前路径下,出现一个magicCreat.exe文件,为一个可执行程序文件,在MATLAB命令行窗口输入:

    >> !magicCreat
    Extracting CTF archive. This may take a few seconds, depending on the
    size of your application. Please wait...
    ...CTF archive extraction complete.
    y =

    17 24 1 8 15
    23 5 7 14 16
    4 6 13 20 22
    10 12 19 21 3
    11 18 25 2 9
    程序正常运行,由于命令行输入变量个数小于2,因此M文件输入参数默认值为5,程序产生一个5阶的魔方阵,如果需要输入第2个输入参数,则可以按照以下方式在MATLAB命令行窗口中输入:

    >> !magicCreat 3 %创建一个3阶的魔方阵

    y =

    8 1 6
    3 5 7
    4 9 2
    More details could be found in my published book:
    MATLAB编程基础与典型应用
    北京:人民邮电出版社,2008
    ISBN:978-7-115-17932-6/TP

    Pls contact me with Email:lhd06@mails.tsinghua.edu.cn

    Visual C++中调用MATLAB引擎配置

    Visual C++中调用MATLAB引擎配置

    Visual C++环境中调用MATLAB引擎,首先需要对Visual C++环境进行配置,按照以下步骤进行MATLAB引擎环境配置。

    1) 运行Mircosoft Visual C++在菜单栏【File】下选择新建一个工程文件,选择【New】,点击【Project】属性页,选择【Win32 Console Application】,给出工程文件名称。

    2) 选择菜单栏【Tools】下的【Options】,在【Directories】属性页下,设置相关的Include文件路径,Libray文件路径和Executable文件路径。Inlcude文件路径设置为%matlabroot%\extern\include,其中%matlabroot%为读者计算机中MATLAB应用程序的安装根目录,Library文件路径设置为%matlabroot%\extern\lib\win32\microsoft, Executable文件路径设置为%matlabroot%\bin\win。

    3)选择菜单栏【Project】下的【Setting】选项,在【Link】属性页中,添加libeng.lib,libmex.lib,libmx.lib,libmat.lib库文件,注意库文件之间使用空格而不使用逗号,否则编译会出错。

    More details could be found in my published book:
    MATLAB编程基础与典型应用
    北京:人民邮电出版社,2008
    ISBN:978-7-115-17932-6/TP

    Pls contact me with Email:lhd06@mails.tsinghua.edu.cn

    MATLAB引擎技术介绍

    MATLAB的应用程序接口(API)的Engine函数库包含了许多引擎操作的函数,这些函数以Eng作为前缀,同MEX函数库和MX函数库相同,通过前缀来表明函数所在的API函数库。

    1. 使用MEX文件编译Engine函数
    在MATLAB安装程序的路径下,提供了一些Engine函数的演示,读者可以打开文件查看Engine文件编写的基本结构和方法。
    首先拷贝:
    C:\Prgoram Files\MATLAB\R2006a\extern\examples\eng_mat\engwindemo.c
    文件到当前MATLAB的工作窗口中,或者直接打开MATLAB,在MATLAB命令行窗口中输入以下命令:
    demofile = [matlabroot '\extern\examples\eng_mat\engwindemo.c'];
    copyfile(demofile, '.');
    通过which命令或者在Current Diretory目录下,可以看到engwindemo.c文件已经拷贝到当前路径下,然后选择编译属性文件,在MATLAB命令行窗口中输入以下命令:
    optsfile = [matlabroot '/bin/engopts.sh'];
    mex('-f', optsfile, 'engdemo.c');
    或者直接使用以下的MATLAB命令行命令:
    mex('-f', [matlabroot  '\bin\win32\mexopts\lccengmatopts.bat'], ‘engwindemo.c’);
    编译成功后,可以看到在MATLAB的当前工作窗口中出现了一个engwindemo.exe可执行文件,在MATLAB命令行窗口中输入:
    !engwindemo
    通过!操作符,可以在MATLAB的命令行窗口中执行.EXE文件。

    2. 在Visual C++中编译运行engine文件

    #include
    #include
    #include
    #include
    //包含engine.h头文件或者精确列出文件所在,读者根据Matlab安装路径修改即可
    // #include
    #include "engine.h"
    int main(void)
    {
    Engine *ep;
    mxArray *temperatureValue;
    double tempValue[]={0,4,6,10,12,16,22,26,30};
    int length;

    //开启Matlab引擎 Engine
    if( !(ep = engOpen(NULL)) )
    {
    //MatlabEngDemo.c为保存的文件名
    MessageBox( (HWND)NULL, (LPSTR)"Can't start MATLAB engine",
    (LPSTR)"matlabEngDemo.c", MB_OK);
    exit(-1);
    }

    //如果正常开启Matlab引擎,则调用引擎函数
    length = sizeof(tempValue)/sizeof(double);
    //初始化mxArray变量temperatureValue
    temperatureValue = mxCreateDoubleMatrix(1, length, mxREAL);
    //将tempValue的数值拷贝给temperatureValue
    memcpy( (void *)mxGetPr(temperatureValue), (void *) tempValue, length * sizeof(double));
    //将变量导入工作窗口Workspace中
    engPutVariable(ep, "Temperature", temperatureValue);
    //以下利用engEvalString函数调用Matlab命令
    engEvalString(ep, "Density = -0.256 * Temperature.^2 + 6.16 * Temperature - 33.9;");
    engEvalString(ep, "plot(Temperature, Density,'r-');");
    engEvalString(ep, "title('Density vs. Temperature curve');");
    engEvalString(ep, "xlabel('Temperature');");
    engEvalString(ep, "ylabel('Density');");
    engEvalString(ep, "grid on;");

    //释放内存空间
    mxDestroyArray(temperatureValue);

    return 0;
    }
    More details could be found in my published book:
    MATLAB编程基础与典型应用
    北京:人民邮电出版社,2008
    ISBN:978-7-115-17932-6/TP

    Pls contact me with Email:lhd06@mails.tsinghua.edu.cn