如何编写simulink library

由于simulink中没有非线性系统的状态空间模块,即形如
x'=f(x)+g(x)u
y=h(x)
的模块,因此对于非线性系统,使用simulink建模比较困难。
但是现在这不是问题了,因为我们有了一个第三方的simulink library:NelinSys
下载下来之后,顺便分析了这个库的实现方法,发现真的是very easy!下面介绍一下如何编写simulink library:
1.打开simulink,选择File->new->library,这样就能在里面随便添加文本,等。。东西。然后保存为.mdl文件。
2.然后就得添加一个模块,这里我没找到如何用可视化的方法进行设计,但是我发现可以直接修改.mdl文件实现。比如有一个library中的一个模块叫做Nonlinear MIMO system,它对应的代码如下:

ExpandedBlockStart.gif ContractedBlock.gif Block   dot.gif {
InBlock.gif      BlockType          SubSystem
InBlock.gif      Name              
"Nonlinear MIMO system\n(State-Space model)"
InBlock.gif      Ports              [
12000]
InBlock.gif      Position          [
2552038595]
InBlock.gif      ShowPortLabels      off
InBlock.gif      MaskType          
"Nonlinear MIMO system - state-space model"
InBlock.gif      MaskDescription      
"Nonlinear MIMO system is described by follo"
InBlock.gif
"wing nonlinear differential equations:\n                       dx/dt = f(x) +"
InBlock.gif
" g(x) u\n                        y = h(x)\n\n             states vector:  x ="
InBlock.gif
" [x1; x2; dot.gif; xN]\n             system input: u (vector)\n             syste"
InBlock.gif
"m output: y (vector)\n\nParameters f(x), g(x), h(x) can be specified either a"
InBlock.gif
"s a symbolic expression or as an identifier of a symbolic variable.\n\nFor a "
InBlock.gif
"detailed description of parameters, click \"Help\" button."
InBlock.gif      MaskHelp          
"web(fullfile(cd,'help','stavp_mimo.html'));"
InBlock.gif      MaskPromptString      
"System order (number of states, N)|f(x) - s"
InBlock.gif
"ymbolic expression:|f(x) - variable identifier:|g(x) - symbolic expression:|g"
InBlock.gif
"(x) - variable identifier:|h(x) - symbolic expression:|h(x) - variable identi"
InBlock.gif
"fier:|Initial conditions (initial states):"
InBlock.gif      MaskStyleString      
"edit,edit,edit,edit,edit,edit,edit,edit"
InBlock.gif      MaskTunableValueString  
"on,on,on,on,on,on,on,on"
InBlock.gif      MaskVariables          
"n=@1;F=&2;Fp=@3;G=&4;Gp=@5;H=&6;Hp=@7;pp=@8"
InBlock.gif
";"
InBlock.gif      MaskInitialization      
"% Overenie spravnosti zadania parametrov bl"
InBlock.gif
"oku %\nif ~isempty(F) & (Fp == 0)\n   F = sym(F);\nelseif isempty(F) & (any(F"
InBlock.gif
"p ~= 0))\n   F = sym(Fp);\nelse\n   error(['Matrix f(x) unspecified or specif"
InBlock.gif
"ied more than once - cannot continue!']);\nend\n\nif ~isempty(G) & (Gp == 0)"
InBlock.gif
"\n   G = sym(G);\nelseif isempty(G) & (any(Gp ~= 0))\n   G = sym(Gp);\nelse\n"
InBlock.gif
"   error(['Matrix g(x) unspecified or specified more than once - cannot conti"
InBlock.gif
"nue!']);\nend\n\nif ~isempty(H) & (Hp == 0)\n   H = sym(H);\nelseif isempty(H"
InBlock.gif
") & (any(Hp ~= 0))\n   H = sym(Hp);\nelse\n   error(['Matrix h(x) unspecified"
InBlock.gif
" or specified more than once - cannot continue!']);\nend\n\n% Zisti si symbol"
InBlock.gif
"icke premenne, ktore vystupuju vo vyrazoch %\npremF = strrep(strrep(findsym(s"
InBlock.gif
"ym(F)),', ',''),',',' ');\npremG = strrep(strrep(findsym(sym(G)),', ',''),','"
InBlock.gif
",' ');\npremH = strrep(strrep(findsym(sym(H)),', ',''),',',' ');\n\n% Premenn"
InBlock.gif
"e x1, x2, dot.gif, xN su korektne, preskoc ich %\nfor k = 1 : n\n   premF = strre"
InBlock.gif
"p(premF, sprintf('x%d',k), '');\n   premG = strrep(premG, sprintf('x%d',k), '"
InBlock.gif
"');\n   premH = strrep(premH, sprintf('x%d',k), '');\nend\n\n% Ak niektory re"
InBlock.gif
"tazec nezostal prazdny, vyhlas chybu %\nif ~isempty(premF)\n   error(['Unknow"
InBlock.gif
"n symbol in f(x) expression - cannot continue!']);\nend\nif ~isempty(premG)\n"
InBlock.gif
"   error(['Unknown symbol in g(x) expression - cannot continue!']);\nend\nif "
InBlock.gif
"~isempty(premH)\n   error(['Unknown symbol in h(x) expression - cannot contin"
InBlock.gif
"ue!']);\nend\n\n% Otestovanie spravnosti rozmerov matic F,G,H (podla \"n\") %"
InBlock.gif
"\nif ~all(size(F) == [n,1])\n   error(['Invalid matrix dimensions: f(x) - can"
InBlock.gif
"not continue!']);\n   return;\nend\n\nnin = size(G);\nif (nin(1,1) ~= n)\n   "
InBlock.gif
"error(['Invalid matrix dimensions: g(x) - cannot continue!']);\n   return;\ne"
InBlock.gif
"nd\nnin = nin(1,2);\n\nnout = size(H);\nif (nout(1,2) ~= 1)\n   error(['Inval"
InBlock.gif
"id matrix dimensions: h(x) - cannot continue!']);\n   return;\nend\nnout = no"
InBlock.gif
"ut(1,1);\n\n% Kontrola vektora pociatocnych podmienok (pociatocnych stavov) %"
InBlock.gif
"\nif ~all(size(pp) == [n,1])\n   error(['Initial conditions vector: invalid d"
InBlock.gif
"imensions - cannot continue!']);\n   return;\nend\n\n% Nahradenie identifikat"
InBlock.gif
"orov \"xI\" identifikatormi \"x(I)\" %\nco_str = '{''x1'; cim_str = '{''x(1)'"
InBlock.gif
";\n\nfor k = 2 : n\n    co_str = sprintf('%s'',''x%d', co_str, k);\n    cim_s"
InBlock.gif
"tr = sprintf('%s'',''x(%d)', cim_str, k);\nend\n\nco_str = strcat(co_str, '''"
InBlock.gif
"}'); cim_str = strcat(cim_str, '''}');\n\nF = eval(sprintf('subs(F,%s,%s)', c"
InBlock.gif
"o_str, cim_str));\nG = eval(sprintf('subs(G,%s,%s)', co_str, cim_str));\nH = "
InBlock.gif
"eval(sprintf('subs(H,%s,%s)', co_str, cim_str));\n"
InBlock.gif      MaskDisplay          
"disp('Nonlinear MIMO system\\n\\nx'' = f(x)"
InBlock.gif
" + g(x) u\\ny = h(x)');"
InBlock.gif      MaskIconFrame          on
InBlock.gif      MaskIconOpaque      on
InBlock.gif      MaskIconRotate      none
InBlock.gif      MaskIconUnits          autoscale
InBlock.gif      MaskValueString      
"3|[84.249*x2*x3; -165.8654*x1*x3-62.5*x2; -"
InBlock.gif
"15.3846*x3]|0|[0 0; 2500 0; 0 0.9799]|0|[x1; x3]|0|[0; 0; 1e-9]"
ExpandedSubBlockStart.gifContractedSubBlock.gif      System 
dot.gif{
InBlock.gif        Name            
"Nonlinear MIMO system\n(State-Space model"
InBlock.gif
")"
InBlock.gif        Location            [
124225456399]
InBlock.gif        Open            off
InBlock.gif        ToolBar            off
InBlock.gif        StatusBar            off
InBlock.gif        ScreenColor            white
InBlock.gif        PaperOrientation        landscape
InBlock.gif        PaperPositionMode        auto
InBlock.gif        PaperType            usletter
InBlock.gif        PaperUnits            inches
ExpandedSubBlockStart.gifContractedSubBlock.gif        Block 
dot.gif{
InBlock.gif          BlockType              Inport
InBlock.gif          Name              
"Vstup"
InBlock.gif          Position              [
15784592]
InBlock.gif          Port              
"1"
InBlock.gif          PortWidth              
"-1"
InBlock.gif          SampleTime          
"-1"
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        Block 
dot.gif{
InBlock.gif          BlockType              Demux
InBlock.gif          Name              
"Demux"
InBlock.gif          Ports              [
12000]
InBlock.gif          Position              [
2356240159]
InBlock.gif          BackgroundColor          black
InBlock.gif          ShowName              off
InBlock.gif          Outputs              
"[nout n]"
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        Block 
dot.gif{
InBlock.gif          BlockType              "S-Function"
InBlock.gif          Name              "S-funkcia realizujuca\nnelinearny syste"
InBlock.gif"m"
InBlock.gif          Ports              [1, 1, 0, 0, 0]
InBlock.gif          Position              [85, 60, 195, 110]
InBlock.gif          FunctionName          "stavp_mimo"
InBlock.gif          Parameters          "n,nin,nout,F,G,H,pp"
InBlock.gif          PortCounts          "[]"
InBlock.gif          SFunctionModules          "''"
ExpandedSubBlockEnd.gif        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        Block 
dot.gif{
InBlock.gif          BlockType              Outport
InBlock.gif          Name              
"Vystup"
InBlock.gif          Position              [
2803831052]
InBlock.gif          Port              
"1"
InBlock.gif          OutputWhenDisabled      held
InBlock.gif          InitialOutput          
"0"
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        Block 
dot.gif{
InBlock.gif          BlockType              Outport
InBlock.gif          Name              
"Stavovy\nvektor"
InBlock.gif          Position              [
280113310127]
InBlock.gif          Port              
"2"
InBlock.gif          OutputWhenDisabled      held
InBlock.gif          InitialOutput          
"[]"
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        Line 
dot.gif{
InBlock.gif          SrcBlock              
"Demux"
InBlock.gif          SrcPort              
2
InBlock.gif          DstBlock              
"Stavovy\nvektor"
InBlock.gif          DstPort              
1
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        Line 
dot.gif{
InBlock.gif          SrcBlock              
"Demux"
InBlock.gif          SrcPort              
1
InBlock.gif          DstBlock              
"Vystup"
InBlock.gif          DstPort              
1
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        Line 
dot.gif{
InBlock.gif          SrcBlock              
"S-funkcia realizujuca\nnelinearny syste"
InBlock.gif
"m"
InBlock.gif          SrcPort              
1
InBlock.gif          DstBlock              
"Demux"
InBlock.gif          DstPort              
1
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        Line 
dot.gif{
InBlock.gif          SrcBlock              
"Vstup"
InBlock.gif          SrcPort              
1
InBlock.gif          DstBlock              
"S-funkcia realizujuca\nnelinearny syste"
InBlock.gif
"m"
InBlock.gif          DstPort              
1
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif      }

ExpandedBlockEnd.gif    }

值得注意的是其中一个s-function子模块: stavp_mimo,其实这个子模块才是最核心的地方,打开这个文件发现果然是一个标准的s-function模块:
None.gif function [sys,x0,str,ts]  =  stavp_mimo(t,x,u,flag,n,nin,nout,F,G,H,pp)
None.gif
None.gif
%  NelinSys  -  a program tool  for  analysis and synthesis of nonlinear control systems
None.gif
%             based on MATLAB / Simulink  5.2
None.gif
%
None.gif
%  (C)  2002 - 2005 , Martin Ondera (eskimo@pobox.sk) (Martin.Ondera@stuba.sk)
None.gif
None.gif
%  This program  is  free software; you can redistribute it and / or
None.gif
%  modify it under the terms of the GNU General Public License
None.gif
%   as  published by the Free Software Foundation; either version  2
None.gif
%  of the License, or (at your option) any later version.
None.gif
%
None.gif
%  This program  is  distributed  in  the hope that it will be useful,
None.gif
%  but WITHOUT ANY WARRANTY; without even the implied warranty of
None.gif
%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
None.gif
%  GNU General Public License  for  more details.
None.gif
%
None.gif
%  You should have received a copy of the GNU General Public License
None.gif
%  along with  this  program;  if  not, write to the Free Software
None.gif
%  Foundation, Inc.,  59  Temple Place  -  Suite  330 , Boston, MA   02111 - 1307 , USA.
None.gif
%
None.gif
%  Please, see the LICENSE.TXT file to read the full license.
None.gif
None.gif
switch  flag,
None.gif
None.gif
%   ===========================  Inicializacna cast s - funkcie   ==============================   %
None.gif
case   0
None.gif
None.gif   
%  Definicia stavov, vstupov a vystupov nelinearneho systemu  %
None.gif   sizes 
=  simsizes;
None.gif   sizes.NumContStates 
=  n;
None.gif   sizes.NumDiscStates 
=   0 ;
None.gif   sizes.NumOutputs 
=  nout + n;
None.gif   sizes.NumInputs 
=  nin;
None.gif   sizes.DirFeedthrough 
=   0 ;
None.gif   sizes.NumSampleTimes 
=   1 ;
None.gif   sys 
=  simsizes(sizes);
None.gif
None.gif   
%  Inicializacia pociatocnych podmienok  %
None.gif   x0 
=  pp;
None.gif
None.gif   
%  Inicializacia  " str "  ako prazdna matica  %
None.gif   str 
=  [];
None.gif   
None.gif   
%  Sample times  in  TS  %
None.gif   ts 
=  [ 0   0 ];
None.gif
None.gif
%   ==========================  Vypocet podla  1 . stavovej rovnice  ==========================   %
None.gif
case   1
None.gif   sys 
=  eval(sym(F))  +  eval(sym(G))  *  u;
None.gif
None.gif
%   ==========================  Vypocet podla  2 . stavovej rovnice  ==========================   %
None.gif
case   3
None.gif   sys(
1 :nout,:)  =  eval(sym(H));     %  Ako vystup bloku sa berie nielen vystup systemudot.gif   %
None.gif   sys(nout
+ 1 :nout + n,:)  =  x;         %  dot.gif ale aj cely stavovy vektor nelinearneho systemu  %
None.gif
None.gif
%   =================================  Nepouzite priznaky  ==================================   %
ExpandedBlockStart.gifContractedBlock.gif
case   dot.gif {249}
None.gif   sys 
=  [];
None.gif   
None.gif
%   =================================  Spracovanie chyby  ===================================   %
None.gifotherwise
None.gif   error([
' Unknown flag =  ' ,num2str(flag)]);
None.gifend
ok,现在分析结束。以后有了新的进展,我会随时汇报。
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
For a useful introduction that will help you start using Simulink quickly, take a look at “Running a Demo Model” in Chapter 2. Browse around the model, double-click on blocks that look interesting, and you will quickly get a sense of how Simulink works. If you want a quick lesson in building a model, see “Building a Simple Model” in Chapter 2. Chapter 3 describes in detail how to build and edit a model. It also discusses how to save and print a model and provides some useful tips. Chapter 4 describes how Simulink performs a simulation. It covers simulation parameters and the integration solvers used for simulation, including some of the strengths and weaknesses of each solver that should help you choose the appropriate solver for your problem. It also discusses multirate and hybrid systems. Chapter 5 discusses Simulink and MATLAB features useful for viewing and analyzing simulation results. Chapter 6 discusses methods for creating your own blocks and using masks to customize their appearance and use. Chapter 7 describes subsystems whose execution depends on triggering signals. Chapter 8 provides reference information for all Simulink blocks. Chapter 9 provides information about how Simulink works, including information about zero crossings, algebraic loops, and discrete and hybrid systems. Chapter 10 provides reference information for commands you can use to create and modify a model from the MATLAB command window or from an M-file. Chapter 11 explains how to use the Simulink debugger to debug Simulink models. It also documents debugger commands. Appendix A lists model and block parameters. This information is useful with the get_param and set_param commands, described in Chapter 10. Appendix B describes the format of the file that stores model information. Although we have tried to provide the most complete and up-to-date information in this manual, some information may have changed after it was completed. Please check the Known Software and Documentation Problems delivered with your Simulink system, for the latest release notes.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值