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

摘要:
SimOut是Simulink。SimulationOutput对象包含模拟输出:模拟采样时间、状态值和信号值。param_ struct=结构;sim_ out=sim;simOut=sim;通过在模拟期间配置集合来配置参数。名为SimulationCommand的参数可以通过_ Param设置不同的值来控制模型模拟的过程。
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对象,包含了仿真的输出:仿真采样时间、状态值和信号值。

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

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

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

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

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

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

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

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

(4)sim('model');

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

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

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

示例:

Simulink仿真入门到精通(八) M语言对Simulink模型的自动化操作及配置第1张

Data Export选Array。

param_struct1.SaveState      = 'on';
param_struct1.StateSaveName  = 'xout1';
param_struct1.SaveOutput     = 'on';
param_struct1.OutputSaveName = 'yout1';
param_struct1.SolverType     = 'Fixed-step';
param_struct1.Solver         = 'FixedStepDiscrete';
param_struct1.FixedStep      = '0.01';
sim_out1 = sim('mymodel',param_struct1);
param_struct2 = param_struct1;
param_struct2.FixedStep      = '2';
param_struct2.OutputSaveName ='yout2';
sim_out2 = sim('mymodel',param_struct2);
t1 = get(sim_out1, 'tout');
t2 = get(sim_out2, 'tout');
y1 = get(sim_out1, 'yout1');
y2 = get(sim_out2, 'yout2');
figure;
title('Sim a model with different config parameters');
subplot(211);
plot(t1,y1);
xlabel('time(s)');
ylabel('yout1');
subplot(212);
plot(t2,y2);
xlabel('time(s)');
ylabel('yout2');

Simulink仿真入门到精通(八) M语言对Simulink模型的自动化操作及配置第2张

8.1.2 set_param控制模型仿真过程

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

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

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

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

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

Simulink仿真入门到精通(八) M语言对Simulink模型的自动化操作及配置第3张

set_param('mymodel','SolverType','Fixed-step','Solver','FixedStepDiscrete','FixedStep','0.1');
set_param('mymodel', 'SimulationCommand', 'start');
set_param('mymodel', 'SimulationCommand', 'pause');
set_param('mymodel', 'SimulationCommand', 'step');
pause(0.2);
t = get_param('mymodel', 'SimulationTime')  % get current simulation time
while t~=0
    t = get_param('mymodel', 'SimulationTime');  % get current simulation time
    if t < 30
        set_param('mymodel/Gain', 'Gain','3');
    elseif t < 80
        set_param('mymodel/Gain', 'Gain','1.5');
    else
        set_param('mymodel/Gain', 'Gain','-0.3');
    end
    set_param('mymodel', 'SimulationCommand', 'step');
    pause(0.2);
end
set_param('mymodel', 'SimulationCommand', 'stop');

Simulink仿真入门到精通(八) M语言对Simulink模型的自动化操作及配置第4张

 8.2 M语言修改模块属性
set_param('m_control_05','SimulationCommand','start');
scope_h = find_system('m_control_05', 'findall','on','blockType','Scope');
num_scope = length(scope_h);
for ii = 1: num_scope
    set(scope_h(ii), 'Open', 'on');
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可以有返回值,返回模型的句柄。

>> h=new_system('new')

h =

   1.8480e+03

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

load_system将模型隐式打开。

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

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

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

add_block('src','dest')

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

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为用来替换其他模块的模块名。

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

替换后模块名没有改变。

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

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

8.3.3 信号线的添加及删除

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

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

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

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

Simulink仿真入门到精通(八) M语言对Simulink模型的自动化操作及配置第5张

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

8.3.4 M语言自动创建模型

自动创建switch模型。

function varargout = section_model(varargin)
% SECTION_MODEL MATLAB code for section_model.fig
%      SECTION_MODEL, by itself, creates a new SECTION_MODEL or raises the existing
%      singleton*.
%
%      H = SECTION_MODEL returns the handle to a new SECTION_MODEL or the handle to
%      the existing singleton*.
%
%      SECTION_MODEL('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SECTION_MODEL.M with the given input arguments.
%
%      SECTION_MODEL('Property','Value',...) creates a new SECTION_MODEL or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before section_model_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to section_model_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help section_model

% Last Modified by GUIDE v2.5 02-Jan-2015 09:24:44

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @section_model_OpeningFcn, ...
                   'gui_OutputFcn',  @section_model_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before section_model is made visible.
function section_model_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to section_model (see VARARGIN)

% Choose default command line output for section_model
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes section_model wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = section_model_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double


% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit3_Callback(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit3 as text
%        str2double(get(hObject,'String')) returns contents of edit3 as a double


% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --------------------------------------------------------------------
function Untitled_1_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function Untitled_2_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
bdclose all;
threshold = get(handles.edit1,'string');
up_out = get(handles.edit2, 'string');
down_out = get(handles.edit3, 'string');
rel = get(handles.popupmenu1,'Value');

mdl_name = 'switch_section';
mdl_handle = new_system(mdl_name);
open_system(mdl_handle);
add_block('simulink/Signal Routing/Switch',[mdl_name,'/Switch']);
add_block('simulink/Commonly Used Blocks/In1',[mdl_name,'/In1'],'Position',[35   213    65   227]);
add_block('simulink/Commonly Used Blocks/Out1',[mdl_name, '/Out1'],'Position',[345   213   375   227]);
add_block('simulink/Commonly Used Blocks/Constant',[mdl_name, '/Constant'],'Position',[125   150   155   180]);
add_block('simulink/Commonly Used Blocks/Constant',[mdl_name, '/Constant1'],'Position',[125   265   155   295]);
if rel == 2
    criterial = 'u2 > Threshold';
elseif rel == 1
    criterial = 'u2 >= Threshold';
else
    criterial = 'u2 ~= 0';
end
set_param([mdl_name,'/Switch'], 'Criteria', criterial, 'Threshold', threshold);
set_param([mdl_name, '/Constant'],'Value', up_out);
set_param([mdl_name, '/Constant1'],'Value', down_out);
autorouting = get(handles.checkbox1, 'value');
if isequal(autorouting, 0)
    add_line(mdl_name,'In1/1','Switch/2');
    add_line(mdl_name,'Switch/1','Out1/1');
    add_line(mdl_name,'Constant/1','Switch/1');
    add_line(mdl_name,'Constant1/1','Switch/3');
else
    add_line(mdl_name,'In1/1','Switch/2','autorouting','on');
    add_line(mdl_name,'Switch/1','Out1/1','autorouting','on');
    add_line(mdl_name,'Constant/1','Switch/1','autorouting','on');
    add_line(mdl_name,'Constant1/1','Switch/3','autorouting','on');
end


% --------------------------------------------------------------------
function Untitled_5_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
web('http://www.ilovematlab.cn/article-29-1.html');

% --------------------------------------------------------------------
function Untitled_4_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
bdclose all;
close(gcf);


% --------------------------------------------------------------------
function Untitled_7_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function Untitled_8_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
web('http://weibo.com/u/2300570331');


% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1
if 3 == get(hObject,'Value')
    set(handles.edit1, 'Enable', 'off', 'string','0');
else
    set(handles.edit1, 'Enable', 'on');
end

% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in checkbox1.
function checkbox1_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox1

Simulink仿真入门到精通(八) M语言对Simulink模型的自动化操作及配置第6张

Simulink仿真入门到精通(八) M语言对Simulink模型的自动化操作及配置第7张

免责声明:文章转载自《Simulink仿真入门到精通(八) M语言对Simulink模型的自动化操作及配置》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇usb触摸屏驱动linux文件名乱码解决办法下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Unity3d 内置图形界面系统(Editor GUI)

一、说在前面的 1、unity内置的ui系统,无论是在性能的表现上、功能的强大性上、制作复杂ui的便捷性上,还是其它的一些方面都不如一些第三方的插件来的好,如:NGUI和DF-GUI(PS: 后者比前者要好很哦,推荐!))。 2、虽然UnityGUI不如某些第三方的插件,但是它在做一些简单的测试上,做数据高度上还是要方便一些的;而且如果你要做Inspect...

qt 总结

总结(-) 1> 定时器的使用 QTimer*timer=newQTimer(this); connect(timer,SIGNAL(timeout()),this,SLOT(update())); // 设置定时器回调函数 timer->start(1000); // 启动定时器 2> 得到系统当前时间 QTimetime=QT...

jmeterGUI&amp;amp;非GUI模式之如何减负性能调优

jmeter之如何减负-实现稳定超高并发测试(性能调优)在测试过程中,初学者使用工具不当,添加众多监控组件,非常想看到实时报告,跑不了一会,jmeter就卡死甚至内存耗尽,只得重启,之前的统计报告没了,非常郁闷。 总结下如何正确使用jmeter,有效利用执行资源,小型机器也可以实现高并发负载。 1、优化监听(GUI模式)“查看结果树”,需要勾选“仅日志错误...

gui design studio3 中文帮助(4)用户界面 (中)工具面板

工具面板 工程面板 设计工具条上的工程面板,可以访问工程所有设计文档和图片文件。 在这里你可以快速做如下事情:创建新的工程目录来组织你的文件;创建新的设计文档;复制已有的设计和从剪贴板上导入图片。 你也可以加入其它工程和文件夹得链接,来获得访问它们的所有设计文档和图片文件。这个功能,在你使用库工程的公共组件或使用存在别处的图片时候非常好用。 当你选择...

Unity3d—GUI能量条

1、打开Unity编辑器。2、在脚本文件夹中添加C#脚本,我的是添加了skill_01这个脚本。(要自己设置文件夹,方便管理,不然文件添乱不方便管理) 3、注意,脚本的名字一旦确定就不要去改动,因为一个脚本的名字就是一个类名,改动会容易出现程序的不正确。4、编写对应的脚本代码1 usingSystem.Collections; 2 usingSystem....

数据库并发处理

为什么要有锁? 我们都是知道,数据库中锁的设计是解决多用户同时访问共享资源时的并发问题。在访问共享资源时,锁定义了用户访问的规则。根据加锁的范围,MySQL 中的锁可大致分成全局锁,表级锁和行锁三类。在本篇文章中,会依次介绍三种类型的锁。在阅读本篇文章后,应该掌握如下的内容: 为什么要在备份时使用全局锁? 为什么推荐使用 InnoDB 作为引擎进行备份?...