8.1 M语言控制模型的仿真

M语言与Simulink结合的方式:

  • 在Simulink模型或模块中使用回调函数
  • 在M语言中调用与模型相关的命令,控制模型的建立,设置模块的属性,增删信号线,以及运行模型仿真等

为了调用和操作Simulink模型,M语言中最常用的函数有sim、set_param、get_param。

8.1.1 sim控制模型仿真及参数配置

(1)simOut=sim('model','ParameterName1',value1,'ParameterName2',value2,...);

对名为model的模型进行仿真,仿真时将其参数通过[参数名,参数值]的方式进行配置。

simOut是一个Simulink.SimulationOutput对象,包含了仿真的输出:仿真采样时间、状态值和信号值。

  1. sim_out=sim('mymodel','SimulationMode','Normal','stoptime','30');

(2)simOut=sim('model',ParameterStruct);

仿真时通过结构体变量配置参数。

  1. param_struct=struct('SimulationMode','Normal','stoptime','30');
  2. sim_out=sim('mymodel',param_struct);

(3)simOut=sim('model',ConfigSet);

仿真时通过配置集合来配置参数。

  1. getActiveConfigSet() %获取模型的配置集合变量
  2. attachConfigSet() %绑定参数配置集合到模型
  3. setActiveConfigSet() %激活模型的某个参数配置

对ConfigSet对象进行参数获取/设定也使用set_param()/get_param()。

(4)sim('model');

当不需要该表模型的参数配置,也不关心模型仿真的输出时,可以直接sim。

使用上述命令运行仿真时,并不修改模型的配置,而是通过sim函数暂时设置某个参数应用于此次仿真,仿真后模型的配置参数仍然保持之前的设定不受影响。

当希望观察模型参数配置不同对仿真结果有何影响时,直接使用多个sim语句带上不同的参数配置作为M脚本运行即可。

示例:

Data Export选Array。

  1. param_struct1.SaveState = 'on';
  2. param_struct1.StateSaveName = 'xout1';
  3. param_struct1.SaveOutput = 'on';
  4. param_struct1.OutputSaveName = 'yout1';
  5. param_struct1.SolverType = 'Fixed-step';
  6. param_struct1.Solver = 'FixedStepDiscrete';
  7. param_struct1.FixedStep = '0.01';
  8. sim_out1 = sim('mymodel',param_struct1);
  9. param_struct2 = param_struct1;
  10. param_struct2.FixedStep = '2';
  11. param_struct2.OutputSaveName ='yout2';
  12. sim_out2 = sim('mymodel',param_struct2);
  13. t1 = get(sim_out1, 'tout');
  14. t2 = get(sim_out2, 'tout');
  15. y1 = get(sim_out1, 'yout1');
  16. y2 = get(sim_out2, 'yout2');
  17. figure;
  18. title('Sim a model with different config parameters');
  19. subplot(211);
  20. plot(t1,y1);
  21. xlabel('time(s)');
  22. ylabel('yout1');
  23. subplot(212);
  24. plot(t2,y2);
  25. xlabel('time(s)');
  26. ylabel('yout2');

8.1.2 set_param控制模型仿真过程

  1. set_param(object,param1,value1,param2,value2,...);
  • object:模型或模块对象,既可以使用路径表示,也可以使用句柄表示;
  • paramX:模型或模块的参数名;
  • valueX:对应于paramX的参数值。

获取参数则使用get_param(object,param),每次只能获取一个参数的值。

有一个参数名为SimulationCommand,可由set_param设置不同的值来控制模型仿真的过程。

功能说明
start 启动模型仿真
pause 暂停模型仿真
step 单步执行仿真
continue 继续模型放着
stop 停止模型仿真

例:在仿真过程中某些时刻改变某些参数的值。

  1. set_param('mymodel','SolverType','Fixed-step','Solver','FixedStepDiscrete','FixedStep','0.1');
  2. set_param('mymodel', 'SimulationCommand', 'start');
  3. set_param('mymodel', 'SimulationCommand', 'pause');
  4. set_param('mymodel', 'SimulationCommand', 'step');
  5. pause(0.2);
  6. t = get_param('mymodel', 'SimulationTime') % get current simulation time
  7. while t~=0
  8. t = get_param('mymodel', 'SimulationTime'); % get current simulation time
  9. if t < 30
  10. set_param('mymodel/Gain', 'Gain','3');
  11. elseif t < 80
  12. set_param('mymodel/Gain', 'Gain','1.5');
  13. else
  14. set_param('mymodel/Gain', 'Gain','-0.3');
  15. end
  16. set_param('mymodel', 'SimulationCommand', 'step');
  17. pause(0.2);
  18. end
  19. set_param('mymodel', 'SimulationCommand', 'stop');

8.2 M语言修改模块属性

  1. set_param('m_control_05','SimulationCommand','start');
  2. scope_h = find_system('m_control_05', 'findall','on','blockType','Scope');
  3. num_scope = length(scope_h);
  4. for ii = 1: num_scope
  5. set(scope_h(ii), 'Open', 'on');
  6. end

8.3 M语言自动建立模型

几个重要的函数:

  1. 模型相关:new_system创建新模型,load_system将模型加载到内存(不可见),open_system打开模型使可视化;
  2. 模块相关:add_block向模型中追加模块,delete_block删除模块,replace_block替换模块;
  3. 信号线相关:add_line在模块输入/输出口之间连线,delete_line将既存的信号线删除。

8.3.1 模型的建立及打开

new_system可以有返回值,返回模型的句柄。

  1. >> h=new_system('new')
  2.  
  3. h =
  4.  
  5. 1.8480e+03

save_system可以与new_system连用而直接将模型保存在硬盘上。

load_system将模型隐式打开。

close_system关闭模型,参数为模型名,不写参数时关闭选中的模型(gcs)。

bdclose all可以无条件关闭所有隐式或显示打开的模型,即使模型存在改动也不提示保存,谨慎使用。

8.3.2 模块的添加、删除及替换

add_block('src','dest')

src指所添加的模块的路径,dest表示这个源模块添加到的目标路径。

  1. add_block('simulink/Sources/Constant','mymodel/Constant')

add_block('src','dest','param1','value1',...)

可以在添加模块的同时对其参数进行设定。

注意:在添加模块时应避免命名的重复,否则会导致错误;在添加模块之前,要先显示或隐式的将模型打开。

replace_block('sys','old_blk','new_blk')

sys为模型名,old_blk为需要被替换的模块类型名,new_blk为用来替换其他模块的模块名。

当模型中被替换的模块类型存在多个模块时,会弹出对话框供用户选择。

替换后模块名没有改变。

  1. replace_block('mymodel','Scope','simulink/Sinks/Out1')

delete_block('blk')将此类模块全部删掉。

8.3.3 信号线的添加及删除

h=add_line('sys','oport','iport')

在模型sys中追加从输出口oport到输入口iport的信号线,并返回其句柄h。

输入输出端口都需要在模块名后追加斜杠和端口序号。

  1. add_block('simulink/Sources/In1','mymodel/In1');
  2. add_block('simulink/Sinks/Out1','mymodel/Out1');
  3. add_line('mymodel','In1/1','Out1/1','autorouting','on');

autorouting可以使连线仅保持水平和竖直两个方向。

8.3.4 M语言自动创建模型

自动创建switch模型。

  1. function varargout = section_model(varargin)
  2. % SECTION_MODEL MATLAB code for section_model.fig
  3. % SECTION_MODEL, by itself, creates a new SECTION_MODEL or raises the existing
  4. % singleton*.
  5. %
  6. % H = SECTION_MODEL returns the handle to a new SECTION_MODEL or the handle to
  7. % the existing singleton*.
  8. %
  9. % SECTION_MODEL('CALLBACK',hObject,eventData,handles,...) calls the local
  10. % function named CALLBACK in SECTION_MODEL.M with the given input arguments.
  11. %
  12. % SECTION_MODEL('Property','Value',...) creates a new SECTION_MODEL or raises the
  13. % existing singleton*. Starting from the left, property value pairs are
  14. % applied to the GUI before section_model_OpeningFcn gets called. An
  15. % unrecognized property name or invalid value makes property application
  16. % stop. All inputs are passed to section_model_OpeningFcn via varargin.
  17. %
  18. % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
  19. % instance to run (singleton)".
  20. %
  21. % See also: GUIDE, GUIDATA, GUIHANDLES
  22.  
  23. % Edit the above text to modify the response to help section_model
  24.  
  25. % Last Modified by GUIDE v2.5 02-Jan-2015 09:24:44
  26.  
  27. % Begin initialization code - DO NOT EDIT
  28. gui_Singleton = 1;
  29. gui_State = struct('gui_Name', mfilename, ...
  30. 'gui_Singleton', gui_Singleton, ...
  31. 'gui_OpeningFcn', @section_model_OpeningFcn, ...
  32. 'gui_OutputFcn', @section_model_OutputFcn, ...
  33. 'gui_LayoutFcn', [] , ...
  34. 'gui_Callback', []);
  35. if nargin && ischar(varargin{1})
  36. gui_State.gui_Callback = str2func(varargin{1});
  37. end
  38.  
  39. if nargout
  40. [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
  41. else
  42. gui_mainfcn(gui_State, varargin{:});
  43. end
  44. % End initialization code - DO NOT EDIT
  45.  
  46. % --- Executes just before section_model is made visible.
  47. function section_model_OpeningFcn(hObject, eventdata, handles, varargin)
  48. % This function has no output args, see OutputFcn.
  49. % hObject handle to figure
  50. % eventdata reserved - to be defined in a future version of MATLAB
  51. % handles structure with handles and user data (see GUIDATA)
  52. % varargin command line arguments to section_model (see VARARGIN)
  53.  
  54. % Choose default command line output for section_model
  55. handles.output = hObject;
  56.  
  57. % Update handles structure
  58. guidata(hObject, handles);
  59.  
  60. % UIWAIT makes section_model wait for user response (see UIRESUME)
  61. % uiwait(handles.figure1);
  62.  
  63. % --- Outputs from this function are returned to the command line.
  64. function varargout = section_model_OutputFcn(hObject, eventdata, handles)
  65. % varargout cell array for returning output args (see VARARGOUT);
  66. % hObject handle to figure
  67. % eventdata reserved - to be defined in a future version of MATLAB
  68. % handles structure with handles and user data (see GUIDATA)
  69.  
  70. % Get default command line output from handles structure
  71. varargout{1} = handles.output;
  72.  
  73. function edit1_Callback(hObject, eventdata, handles)
  74. % hObject handle to edit1 (see GCBO)
  75. % eventdata reserved - to be defined in a future version of MATLAB
  76. % handles structure with handles and user data (see GUIDATA)
  77.  
  78. % Hints: get(hObject,'String') returns contents of edit1 as text
  79. % str2double(get(hObject,'String')) returns contents of edit1 as a double
  80.  
  81. % --- Executes during object creation, after setting all properties.
  82. function edit1_CreateFcn(hObject, eventdata, handles)
  83. % hObject handle to edit1 (see GCBO)
  84. % eventdata reserved - to be defined in a future version of MATLAB
  85. % handles empty - handles not created until after all CreateFcns called
  86.  
  87. % Hint: edit controls usually have a white background on Windows.
  88. % See ISPC and COMPUTER.
  89. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
  90. set(hObject,'BackgroundColor','white');
  91. end
  92.  
  93. function edit2_Callback(hObject, eventdata, handles)
  94. % hObject handle to edit2 (see GCBO)
  95. % eventdata reserved - to be defined in a future version of MATLAB
  96. % handles structure with handles and user data (see GUIDATA)
  97.  
  98. % Hints: get(hObject,'String') returns contents of edit2 as text
  99. % str2double(get(hObject,'String')) returns contents of edit2 as a double
  100.  
  101. % --- Executes during object creation, after setting all properties.
  102. function edit2_CreateFcn(hObject, eventdata, handles)
  103. % hObject handle to edit2 (see GCBO)
  104. % eventdata reserved - to be defined in a future version of MATLAB
  105. % handles empty - handles not created until after all CreateFcns called
  106.  
  107. % Hint: edit controls usually have a white background on Windows.
  108. % See ISPC and COMPUTER.
  109. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
  110. set(hObject,'BackgroundColor','white');
  111. end
  112.  
  113. function edit3_Callback(hObject, eventdata, handles)
  114. % hObject handle to edit3 (see GCBO)
  115. % eventdata reserved - to be defined in a future version of MATLAB
  116. % handles structure with handles and user data (see GUIDATA)
  117.  
  118. % Hints: get(hObject,'String') returns contents of edit3 as text
  119. % str2double(get(hObject,'String')) returns contents of edit3 as a double
  120.  
  121. % --- Executes during object creation, after setting all properties.
  122. function edit3_CreateFcn(hObject, eventdata, handles)
  123. % hObject handle to edit3 (see GCBO)
  124. % eventdata reserved - to be defined in a future version of MATLAB
  125. % handles empty - handles not created until after all CreateFcns called
  126.  
  127. % Hint: edit controls usually have a white background on Windows.
  128. % See ISPC and COMPUTER.
  129. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
  130. set(hObject,'BackgroundColor','white');
  131. end
  132.  
  133. % --------------------------------------------------------------------
  134. function Untitled_1_Callback(hObject, eventdata, handles)
  135. % hObject handle to Untitled_1 (see GCBO)
  136. % eventdata reserved - to be defined in a future version of MATLAB
  137. % handles structure with handles and user data (see GUIDATA)
  138.  
  139. % --------------------------------------------------------------------
  140. function Untitled_2_Callback(hObject, eventdata, handles)
  141. % hObject handle to Untitled_2 (see GCBO)
  142. % eventdata reserved - to be defined in a future version of MATLAB
  143. % handles structure with handles and user data (see GUIDATA)
  144. bdclose all;
  145. threshold = get(handles.edit1,'string');
  146. up_out = get(handles.edit2, 'string');
  147. down_out = get(handles.edit3, 'string');
  148. rel = get(handles.popupmenu1,'Value');
  149.  
  150. mdl_name = 'switch_section';
  151. mdl_handle = new_system(mdl_name);
  152. open_system(mdl_handle);
  153. add_block('simulink/Signal Routing/Switch',[mdl_name,'/Switch']);
  154. add_block('simulink/Commonly Used Blocks/In1',[mdl_name,'/In1'],'Position',[35 213 65 227]);
  155. add_block('simulink/Commonly Used Blocks/Out1',[mdl_name, '/Out1'],'Position',[345 213 375 227]);
  156. add_block('simulink/Commonly Used Blocks/Constant',[mdl_name, '/Constant'],'Position',[125 150 155 180]);
  157. add_block('simulink/Commonly Used Blocks/Constant',[mdl_name, '/Constant1'],'Position',[125 265 155 295]);
  158. if rel == 2
  159. criterial = 'u2 > Threshold';
  160. elseif rel == 1
  161. criterial = 'u2 >= Threshold';
  162. else
  163. criterial = 'u2 ~= 0';
  164. end
  165. set_param([mdl_name,'/Switch'], 'Criteria', criterial, 'Threshold', threshold);
  166. set_param([mdl_name, '/Constant'],'Value', up_out);
  167. set_param([mdl_name, '/Constant1'],'Value', down_out);
  168. autorouting = get(handles.checkbox1, 'value');
  169. if isequal(autorouting, 0)
  170. add_line(mdl_name,'In1/1','Switch/2');
  171. add_line(mdl_name,'Switch/1','Out1/1');
  172. add_line(mdl_name,'Constant/1','Switch/1');
  173. add_line(mdl_name,'Constant1/1','Switch/3');
  174. else
  175. add_line(mdl_name,'In1/1','Switch/2','autorouting','on');
  176. add_line(mdl_name,'Switch/1','Out1/1','autorouting','on');
  177. add_line(mdl_name,'Constant/1','Switch/1','autorouting','on');
  178. add_line(mdl_name,'Constant1/1','Switch/3','autorouting','on');
  179. end
  180.  
  181. % --------------------------------------------------------------------
  182. function Untitled_5_Callback(hObject, eventdata, handles)
  183. % hObject handle to Untitled_5 (see GCBO)
  184. % eventdata reserved - to be defined in a future version of MATLAB
  185. % handles structure with handles and user data (see GUIDATA)
  186. web('http://www.ilovematlab.cn/article-29-1.html');
  187.  
  188. % --------------------------------------------------------------------
  189. function Untitled_4_Callback(hObject, eventdata, handles)
  190. % hObject handle to Untitled_4 (see GCBO)
  191. % eventdata reserved - to be defined in a future version of MATLAB
  192. % handles structure with handles and user data (see GUIDATA)
  193. bdclose all;
  194. close(gcf);
  195.  
  196. % --------------------------------------------------------------------
  197. function Untitled_7_Callback(hObject, eventdata, handles)
  198. % hObject handle to Untitled_7 (see GCBO)
  199. % eventdata reserved - to be defined in a future version of MATLAB
  200. % handles structure with handles and user data (see GUIDATA)
  201.  
  202. % --------------------------------------------------------------------
  203. function Untitled_8_Callback(hObject, eventdata, handles)
  204. % hObject handle to Untitled_8 (see GCBO)
  205. % eventdata reserved - to be defined in a future version of MATLAB
  206. % handles structure with handles and user data (see GUIDATA)
  207. web('http://weibo.com/u/2300570331');
  208.  
  209. % --- Executes on selection change in popupmenu1.
  210. function popupmenu1_Callback(hObject, eventdata, handles)
  211. % hObject handle to popupmenu1 (see GCBO)
  212. % eventdata reserved - to be defined in a future version of MATLAB
  213. % handles structure with handles and user data (see GUIDATA)
  214.  
  215. % Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
  216. % contents{get(hObject,'Value')} returns selected item from popupmenu1
  217. if 3 == get(hObject,'Value')
  218. set(handles.edit1, 'Enable', 'off', 'string','0');
  219. else
  220. set(handles.edit1, 'Enable', 'on');
  221. end
  222.  
  223. % --- Executes during object creation, after setting all properties.
  224. function popupmenu1_CreateFcn(hObject, eventdata, handles)
  225. % hObject handle to popupmenu1 (see GCBO)
  226. % eventdata reserved - to be defined in a future version of MATLAB
  227. % handles empty - handles not created until after all CreateFcns called
  228.  
  229. % Hint: popupmenu controls usually have a white background on Windows.
  230. % See ISPC and COMPUTER.
  231. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
  232. set(hObject,'BackgroundColor','white');
  233. end
  234.  
  235. % --- Executes on button press in checkbox1.
  236. function checkbox1_Callback(hObject, eventdata, handles)
  237. % hObject handle to checkbox1 (see GCBO)
  238. % eventdata reserved - to be defined in a future version of MATLAB
  239. % handles structure with handles and user data (see GUIDATA)
  240.  
  241. % Hint: get(hObject,'Value') returns toggle state of checkbox1

Simulink仿真入门到精通(八) M语言对Simulink模型的自动化操作及配置的更多相关文章

  1. Simulink仿真入门到精通(十四) Simulink自定义环境

    14.1 Simulink环境自定义功能 sl_sustomization.m函数是Simulink提供给用户使用MATLAB语言自定义Simulink标准人机界面的函数机制.若sl_sustomiz ...

  2. Simulink仿真入门到精通(十六) Simulink基于模型设计的工业应用概述

    16.1 Simulink用途概述 在基于模型设计广泛应用于汽车电子嵌入式开发的今天,MBD(Model Besed Design)技术也逐步推广到各种嵌入式控制方面.与传统的嵌入式开发相比,BMD以 ...

  3. Simulink仿真入门到精通(十五) Simulink在流程工业中的仿真应用

    15.1 工业乙醇生产与计算机仿真 乙醇作为可再生清洁能源不仅可以代替四乙基铅作为汽油的防爆剂,还可以制造汽油醇.这一巨大的潜在需求促使人们去寻找提高乙醇工业生产率的途径,使人们着手于发酵工程的研究. ...

  4. Simulink仿真入门到精通(十九) 总结回顾&自我练习

    从2019年12月27到2020年2月12日,学习了Simulink仿真及代码生成技术入门到精通,历时17天. 学习的比较粗糙,有一些地方还没理解透彻,全书梳理总结: Simulink的基础模块已基本 ...

  5. Simulink仿真入门到精通(十七) Simulink代码生成技术详解

    17.1 基于模型的设计 基于模型设计是一种流程,较之传统软件开发流程而言,使开发者能够更快捷.更高效地进行开发.适用范围包括汽车电子信号处理.控制系统.通信行业和半导体行业. V字模型开发流程整体描 ...

  6. Simulink仿真入门到精通(五) Simulink模型的仿真

    5.1 模型的配置仿真 由各种模块所构建的可视化逻辑连接,只是模型的外在表现,模型仿真的核心驱动器是被称作解算器(Solver)的组件,相当于Simulink仿真过程的心脏,驱动着模型仿真,它在每一个 ...

  7. Simulink仿真入门到精通(二) Simulink模块

    2.1 Simulink模块的组成要素 用户构建系统模型时无需直接面对成千上万行的代码,而是通过模块化图形界面以模块化的方式构建,能够使理解变得容易,让大脑减负.通过层次化模块分布将系统功能模块化,而 ...

  8. Simulink仿真入门到精通(十一) 模块的封装

    当用户编写了自定义的S函数或者使用Simulink标准库中的模块搭建子系统后,可以通过封装为其设计显示外观,追加参数对话框. 封装是构建一个以对话框为接口的交互界面的过程,它将复杂的模块逻辑关系隐藏起 ...

  9. Simulink仿真入门到精通(四) Simulink子系统

    4.1 Simulink子系统详解 4.1.1 子系统概述 Simulink根据仿真特性将模块的属性分为两种:虚拟模块和非虚拟模块. 非虚拟模块在仿真过程中起到实际的作用,对其进行编辑或者增加删除操作 ...

随机推荐

  1. Linux把内存挂载成硬盘提高读写速度

    tmpfs是一种虚拟内存文件系统正如这个定义它最大的特点就是它的存储空间在VM里面,这里提一下VM(virtual memory),VM是由linux内核里面的vm子系统管理,现在大多数操作系统都采用 ...

  2. python语法基础-函数-基础-长期维护

    ###############    函数的定义调用,返回值和返回值接收    ############## def mylen(): s = "myname" i = 0 for ...

  3. ORs-5-OR Subgenomes Variation among Birds, Sea Turtle and Alligator

    OR Subgenomes Variation among Birds, Sea Turtle and Alligator 由 该图数据计算每种鸟的relative percentage,得到下图: ...

  4. 7)加了基础控制器Controller.php

    文件目录展示: 改动代码展示: Controller.php <?php /** * Created by PhpStorm. * User: Interact * Date: 2017/8/2 ...

  5. MOOC(7)- case依赖、读取json配置文件进行多个接口请求-模拟接口响应数据(18)

    这里是把传入的请求数据作为响应值返回 # -*- coding: utf-8 -*- # @Time : 2020/2/15 9:47 # @File : do_mock_18.py # @Autho ...

  6. the Uneducated are|anymore|that| so as to |die from|die of|

    定冠词加上某些形容词可以泛指一类人,谓语动词一般用复数形式,the uneducated泛指未受过教育的人, the Uneducated are more to be pitied than bla ...

  7. Android开发之《实现类似Toast可以自动消失的提示栏Tip》

    import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.cont ...

  8. Pycharm 2019 破解激活方法

    转载:https://blog.csdn.net/guofang110/article/details/87793264 使用破解补丁方法虽然麻烦,但是可用激活到2099年,基本上是永久激活了,毕竟在 ...

  9. 将js进行到底:node学习9

    node.js数据库篇--Mongoose ODM 介绍mongoose 几乎所有的语言都有原生数据库连接驱动,这个我们上一回已经了解了,比如java的jdbc,mysql-connector,但是实 ...

  10. LG承认手机业务遭到中国厂商碾压!这是输得心服口服的节奏?

    近日,关于LG手机业退出中国市场的消息传的沸沸洋洋.不少相关媒体也对此事向LG北京办事处求证,得到的结果确实是手机业务退出中国市场.并且据韩媒报道,LG还将会逐渐取消高端手机业务,也就是说未来V系列和 ...