Saturday, February 21, 2009

Simulink库文件的建立

Simulink仿真平台可以建立用户自定义的库文件,并将它们显示在Library Browser窗口下,方便用户进行模块的操作。用户可以将一些平时使用比较频繁,或者自己建立的一些封装子模块集中在一块,方便使用。要建立Simulink库文件,首先启动Simulink工作窗口,单击菜单栏【File】下的【New】选项,选择【library】选项,打开一个新的Library窗口界面,此时,用户可以将自己需要添加的一些模块加入到新的窗口中。然后保存为所需要定义的库文件名称。这样,就建立了一个自定义的库文件。

虽然按照上述的方法,将一些用户常用的模块集中在一块,可以方便使用,但是,每次使用都需要打开自定义模块的窗口,而无法象Simulink仿真模块一样显示在Library Browser窗口下。按照以下步骤可以实现该功能:
•首先建立一个库文件,将自定义的封装模块加入库文件中,保存文件,在这里,命名为:own_definition.lib。

•在MATLAB路径下创建存放库文件的路径,也即自定义的模块库在Library Browser下的显示位置。注意在MATLAB中,每一个模块库文件所在的路径必须不同。创建的Maltab路径是:D:\MATLAB\R2006a\toolbox\Simulink\myLibrary(根据自己的MATLAB安装路径来确定),其中myLibrary为自定义的文件夹。

•将第一步中建立的库文件拷贝到新建的Matlab路径下。在MATLAB主窗口的【File】菜单栏下选择【Set Path】选项,然后单击【Add Folder】按钮,将新建的路径添加进来,然后保存(Save),退出(Close)。

• 要显示自定义的模块库,还需要拷贝slblocks.m函数到新建的路径下。在MATLAB的命令窗口中输入:
>> which('slblocks.m', '-all')
>> open('D:\MATLAB\R2006a\toolbox\Simulink\blocks\slblocks.m')

这样就可以打开slbocks.m文件模板,为了将自定义的模块库显示在Library Browser窗口下,需要对该程序进行修改。在本演示中,模块库的名称为own_definition.lib,因此对应的slbocks.m文件为:
function blkStruct = slblocks  

%SLBLOCKS Defines a block library.

% Library's name. The name appears in the Library Browser's
% contents pane.

blkStruct.Name = ['own Definition' sprintf('\n') 'Library']; % 模块库的显示名称

% The function that will be called when the user double-clicks on
% the library's name. ;

blkStruct.OpenFcn = 'own_definition'; %自定义的模块库名称

% The argument to be set as the Mask Display for the subsystem. You
% may comment this line out if no specific mask is desired.
% Example: blkStruct.MaskDisplay =
'plot([0:2*pi],sin([0:2*pi]));';
% No display for now.

% blkStruct.MaskDisplay = '';

% End of blocks

按照以上的代码修改文件后,将其拷贝到自定义的路径下,这样在原来自定义的路径下就包含有两个文件,一个是自定义模块库文件,另一个则是slbocks.m文件。

•重新启动MATLAB环境,启动Simulink仿真平台,可以发现在Simulink Library Browser窗口下增加了一个新的模块库,名称是own Definition Library,展开后,可以看到内部的自定义模块。那么用户可以方便地进行拖放模块,就可以使用自定义的封装模块了。


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工具箱BP神经网络应用介绍(3)

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

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

  • Solve nonlinear least-squares (nonlinear data-fitt...

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

  • Visual C++中创建MAT文件

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

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

  • MATLAB引擎技术介绍

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

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

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

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

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

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

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


  • 在MATLAB工具箱bp神经网络(1)和(2)中介绍了两个BP神经网络的训练函数,这里接着介绍第三个人工神经网络训练函数traingdx函数。
    traingdx函数
    traingdx函数结合了自适应改变学习速率和动量法,和traingda函数完全相同,只是增加了一个动量因子参数mc。
    net=newff(minmax(P),[5,1],{'logsig','purelin'},'traingdx');
    net.trainParam
    ans =
    epochs: 100
    goal: 0
    lr: 0.0100 %学习速率基值
    lr_dec: 0.7000 %学习速率减少率
    lr_inc: 1.0500 %学习速率增加率
    max_fail: 5
    max_perf_inc: 1.0400
    mc: 0.9000 %动量因子
    min_grad: 1.0000e-006
    show: 25
    time: Inf
    MATLAB命令行窗口中输入:
    net=newff(minmax(P),[5,1],{'logsig','purelin'},'traingdx');
    net.trainParam.show = 50;
    net.trainParam.lr = 0.1;
    net.trainParam.lr_inc = 1.05;
    net.trainParam.lr_dec = 0.85;
    net.trainParam.mc = 0.9;
    net.trainParam.epochs = 300;
    net.trainParam.goal = 0.01;
    [net,tr]=train(net,P,T);
    %回代检验
    A=sim(net,P);
    %测试样本检验
    a=sim(net,p);
    下图所示为traingdx函数bp神经网络训练过程曲线,测试样本的输出结果为:
    TRAINGDX-calcgrad, Epoch 0/300, MSE 5.70591/0.01, Gradient 7.94678/1e-006
    TRAINGDX-calcgrad, Epoch 50/300, MSE 0.0185869/0.01, Gradient 0.0617651/1e-006
    TRAINGDX-calcgrad, Epoch 72/300, MSE 0.00997184/0.01, Gradient 0.0194848/1e-006
    TRAINGDX, Performance goal met.
    a =
    0.5880 0.6223 0.5236




    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工具箱BP神经网络应用介绍(2)

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

  • Solve nonlinear least-squares (nonlinear data-fitt...

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

  • Visual C++中创建MAT文件

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

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

  • MATLAB引擎技术介绍

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

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

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

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

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

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



  • 在上一篇MATLAB工具箱bp神经网络应用介绍中,已经介绍了traingd函数的使用。这一节将继续介绍MATLABBP神经网络训练函数。

    (2)traingda函数
    BP神经网络使用traingd函数和traingdm函数训练时,学习速率在训练过程中保持恒定不变,那么训练结果对学习速率的灵敏度大,不同的学习速率对网络的训练结果影响大,如果学习速率过大,那么网络将变得不稳定,如果学习速率过小,那么网络收敛速度慢,训练时间大大加长。因此,对于给定训练样本和目标样本,必须首先确定最优的学习速率。而traingda函数在人工神经网络训练中采用变学习速率的网络训练算法,可以有效地克服学习速率难以确定的缺点,在训练过程中自适应改变学习速率的大小。
    net=newff(minmax(P),[5,1],{'logsig','purelin'},'traingda');
    net.trainParam
    ans =
    epochs: 100
    goal: 0
    lr: 0.0100 %学习速率基值
    lr_inc: 1.0500 %学习速率增加率为1.05
    lr_dec: 0.7000 %学习速率减少率为0.7
    max_fail: 5
    max_perf_inc: 1.0400
    min_grad: 1.0000e-006
    show: 25
    time: Inf
    MATLAB命令行窗口中输入以下程序段:
    net=newff(minmax(P),[5,1],{'logsig','purelin'},'traingda');
    net.trainParam.show = 50;
    net.trainParam.lr = 0.1;
    net.trainParam.lr_inc = 1.05;
    net.trainParam.lr_dec = 0.85;
    net.trainParam.epochs = 300;
    net.trainParam.goal = 0.01;
    [net,tr]=train(net,P,T);
    %回代检验
    A=sim(net,P);
    %测试样本检验
    a=sim(net,p);
    下图所示为traingda函数bp神经网络训练过程曲线,BP神经网络对测试样本的输出结果为:
    TRAINGDA-calcgrad, Epoch 0/300, MSE 0.784702/0.01, Gradient 1.98321/1e-006
    TRAINGDA-calcgrad, Epoch 36/300, MSE 0.00993732/0.01, Gradient 0.0156508/1e-006
    TRAINGDA, Performance goal met.
    a =
    0.4192 0.5750 0.7746


    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工具箱BP神经网络应用介绍(1)

  • Solve nonlinear least-squares (nonlinear data-fitt...

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

  • Visual C++中创建MAT文件

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

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

  • MATLAB引擎技术介绍

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

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

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

  • 在同一个M文件中,怎样实现参数的传递
  • 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

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

    问: matlab里关于集合运算和二进制数的运算的函数

    答: 进行集合运算的函数有如下的一些:

    intersect:集合交集

    ismember :是否集合中元素

    setdiff :集合差集

    setxor :集合异或(不在交集中的元素)

    union :两个集合的并

    unique :返回向量作为一个集合所有元素(去掉相同元素)

    对于二进制数的处理运算函数有如下:

    dec2bin(x) 是把十进制整数x变换为二进制

    bin2dec(y) 是把二进制数y变换为十进制数

    base2dec('x',a) 是把a进制数x变化为十进制数

    dec2base(y,a) 是把十进制数y变化为a进制数

    移位,循环,与,反等操作函数:

    BITAND——对二进制数进行与操作;

    BITOR——对二进制数进行或操作;

    BITXOR——对二进制数进行异或操作;

    BITSHIFT——对二进制数进行移位操作。

    详细使用方法和其他函数可以参看help!!!!!

    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图形中怎样输入特殊符号???

    答: 上标用 ^(指数) 下标用 _(下划线)调用方式为:^{任意字符}, _{任意字符}, 注意{}的使用!希腊字母等特殊字符用 \加拼音 如:α \alpha, β \beta , γ \gamma θ \theta Θ \ThetaГ \Gamma δ \delta Δ \Delta ξ \xi Ξ \Xiη \elta ε \epsilong ζ \zeta μ \miu υ \nu τ \tau λ \lamda Λ \Lamda π \pi Π \Pi σ \sigma Σ \Sigma φ \phi Φ \Phi ψ \psi Ψ \Psi χ \chi ω \ommiga Ω \Ommiga< \leq > \geq 不等于 \neq << \ll >> \gg正负 \pm 左箭头 \leftarrow 右箭头 \rightarrow 上箭头 \uparrow

    体会以下两例:

    figure, title('\zeta^{-t}sint');

    figure, title('x~{\chi}_{\alpha}^{2}(3)');


    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中数组元素写入到文本文档中???

    答: 下面是几个常用的函数:

    (1)matGetNextMatrix:读取MAT文件中的下一个矩阵,调用格式如下:integer*4 function matGetNextMatrix(mfp)integer*4 mfp 说明:函数读取mfp所指向的MAT文件的下一个矩阵的数据并返回一个mxArray类型的指针。

    (2)matGetDir:获得MAT文件中的所有矩阵目录,调用格式如下:integer*4 function matGetDir(mfp,num)integer*4 mfp,num说明:函数从mfp指向的MAT文件中获取所有矩阵的目录。如果执行成功,将返回一个字符串指针数组,数组每个元素均为字符串指针,指向的字符串表示MAT文件中矩阵的目录。若函数执行失败,num返回为-1,并连接一个空指针。如果num为0,则表示MAT文件没有矩阵。

    (3)mexErrMsgTxt:用于输出错误信息,并返回到MATLAB命令提示符下,调用格式如下:subroutine mexErrMsgTxt(error_smg)character*(*)error_msg说明:error_smg为字符串常量,当程序执行后,在MATLAB窗口中显示错误信息error_smg,并终止程序运行。

    (4)mxGetM、mxGetN:分别用来获取矩阵的行数和列数,调用格式相同,格式如下:integer*4 function mxGetN(pm)integer*4 pm说明:pm为形式参数,指定一个矩阵,返回整数。

    (5)mxIsNumeric:判断矩阵是否为数值类型矩阵,调用格式如下:integer*4 function mxIsNumeric(pm)integer*4 pm

    (6)mxCreateFull:创建一个二维的未赋值的满矩阵,调用格式如下:integer*4 function mxCreateFull(m,n,ComplexFlag)integer*4 m,n,ComplexFlag说明:m,n分别为创建矩阵的行数和列数。ComplexFlag为0表示创建实数类型矩阵,ComplexFlag为1表示创建复数类型矩阵。

    (7)mxGetPr、mxGetPi:获得矩阵的实数或虚数部分,调用格式相同,如下:integer*4 function mxGetPr(pm)integer*4 pm说明:如果函数执行成功则获得一个指向pm第一个实数部分的指针。

    (8)mxCopyPtrToReal8、mxCopyReal8ToPtr:将某个矩阵的实数或虚数部分的数据复制到一个实数组中,后一个正好相反,调用格式如下:subroutine mxCopyPtrToReal8(px,y,n)integer*4 px,nreal*8 y(n)subroutine mxCopyReal8ToPtr(y,px,n)integer*4 px,nreal*8 y(n)说明:px为指向某个矩阵的实数或虚数部分的指针,n为需要复制单元的个数,y为实数类型的数组。


    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

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

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

    答: 在同一个M文件中传递参数的几种方式:

    1): assignin(‘base’,’para’,para);
    在后面的程序中,就可以直接调用了:
    Para=evalin(‘base’,’para’) ;

    2) :在当前的对象中;
    set(h0bject,’userdata’,[]) ;
    Set(h0bject,’userdata’,para) ;
    在后面的程序中就可以直接调用了:
    Para=get(h0bject,’userdata’) ;
    这里h0bject为某一对象的句柄


    3):直接使用句柄,该方法最为简便而且安全性最高;
    Handles.xxx=?????;
    Guidata(h0bject,handles);
    在后面的程序中,就可以直接调用
    Handles.xxx=????

    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

    SimPowerSystem工具箱使用注意事项

    在广泛使用SimPowerSystem工具箱,当然也有可能涉及到SimExtra工具箱。但主要是实用前两者来进行电力系统,电力电子和电机等方面的仿真。因此在进行这些仿真的时候,有一些基本的原则:

    1):注意不要混用非电气库的线和电气库线。这个原则在Matlab6.5中尤要注意,否则一些电压测量模块,电流测量模块可能会出错。显示数据类型不匹配Data type mismatch错误。在Matlab7.0以上的版本中,simlink做了这方面的区分,不同连接线是无法连接在一起的。

    2):SimPowerSystem工具箱和Simulink工具箱不是随便可以相连的。SimPowerSystem工具箱中有些模块是不能直接连接Simulink信号的。例如电机模型中,电压输入是需要电压源模块的(Power systems Blockset模块),而转矩可以输入simulink信号。如果实在想给电压端口输入simulink信号,需要给其先加一个受控电压源,用simulink信号控制受控信号。还有比如受控电流源模块等,都可以实现SimPowerSystem工具箱与Simulink工具箱的连接。


    3):注意选择适当的仿真算法。Matlab/Simulink中提供了一系列的仿真算法,比如discrete, ode algorithm(龙格库塔算法) including ode45, ode23, ode11s等等。一个适当算法的选择,可以有效的缩短仿真时间和提供仿真的精度。当然具体的算法选择,可以参照相关的书籍讲解。


    4):参数的正确设置是确保模型仿真正确的前提和必要条件。参数的不匹配可能完全导致一些错误的仿真结果。举个简单的例子:我们要得到电阻元件,可以使用SimPowerSystem工具箱中Series RLC Branch模块或者Parallel RLC Branch模块,对于前者,我们必须设置电感为0,电容为inf, 后者,要求设置为电感为inf, 电容为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

    在MATLAB/Simulink环境中编辑Scope中的图形方法

    问: Matlab仿真中怎样编辑Scope中的图象???

    答: 实现的方法有以下的几种:

    1)PrintScreen,然后粘贴到Windows位图编辑器,选择图像点击右键,选择“反色”即可;

    2)在Scope中,它的参数设置的第二页,有一个Save Data to Workplace,将它选中,然后在下面的方框中指定变量名,然后用plot命令画出;

    3)直接在模型上再加一个,to Workplace模块,也用plot画出;

    4)直接在模型上加一个,outport模块,用plot命令绘制tout和yout;

    5) 等scope显示出来图像以后,在matlab的命令行窗口中运行: set(0,'ShowHiddenHandles','On'); set(gcf,'menubar','figure'); 这时候你会发现scope的工具栏的上面多了一行,与plot命令得到的figure的工具栏是一样的。点击insert-axes,鼠标会变成十字形状,然后再图像的任意一处双击左键出现一个对话框PropertyEditor,选中style在窗口的右便会出现color,这时你就可以任意修改背景颜色了。

    Question: How to edit the Scope's figure in the MATLAB/Simulink?

    Answer: There are several methods to edit Scope's figure in the MATLAB/Simulink environment.

    1). Print Screen. Print screen maybe the most convinent method to edit Scope's figure. Whe finished the simulation, The Scope block will display the simulation result. Press the keyboard key Print Screen(In PC, correspond to the key Print Screen, in notebook, maybe "prt sc" and so on), and paste to the windows bitmap editor(Start->program->attachment->draw), select the print figure, and press right button, "reverse color" menu is selected.

    2). In the Scope, press the property setting button, and in the second properties page, select "Save Data to Workplace", and at the same time, fill the variable name in the following box, and after simulation, the variable will exist in the currt workspace. Then go to the MATLAB command workspace, PLOT the saved variables.

    3). Add a "To Workspace" block in the simulation model. Operation is same as the second (2) method. After simulation, the variables will exist in the MATLAB command workspace. PLOT command could be used.

    4). Add a "Outport" block in the simulation model. Operation is same as 2) and 3). PLOT command is available to plot the new variables tout and yout.

    5). When simulation is finished, turn to the MATLAB command workspace, and type the following commands:
    set(0,'ShowHiddenHandles','On');
    set(gcf,'menubar','figure');
    After the commands are executed, A new toolbar will appear in the Scope block which is just same as the figure toolbar with PLOT command. You can use the toolbar to set the figure properties.
    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

    欢迎来到OPEN for MATLAB空间!

    OPEN for MATLAB博客主要是提供各种MATLAB学习资源以及源代码!另外在博客中后续会继续更新包括常用软件的一些使用体验,学习资源以及源代码等,包括Protel, Candence Capture/Allegro以及编程语言,包括C,C++, Java等,欢迎大家交流!

    OPEN for MATLAB blog is created to provide some experience and source codes when I learn the MATLAB software. It has been four to five years since I have a chance to use the powerful tool--MATLAB. The main destination of the blog is to record some basic idea and fundament program methods with MATLAB. I am confident that you will gain a lot from the blog since it will distrube a great deal of MATLAB source codes that are widely used in your ordinary work. I hope OPEN for MATLAB will become a comfortable place to communicate and progress for all MATLAB learner no matter our levels.
    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