25. UserDefinedFunctions
25.1 概述
用户自定义功能,提供了比如MatlabFuction,C Caller,S Function等模块可以去编写代码,调用外部函数等。
25.2 MatlatFunction
在Simulink里面使用m语言做功能开发,比较灵活。一些老牌企业可能不允许使用,小公司为了更快开发逻辑会使用。
双击到模块里,对输入和输出可以直接在function上修改,类似m函数。也可以点击到Model Explorer进行添加和设置的操作。
点进来设置。
对模块进行仿真,看到排序是从1到大排的。
也可以用来生成代码。
25.3 MatlabSystem
工作中几乎没见过使用的,与MatlabFunction的区别是,它使用的类,就是面向对象的编程。
直接添加进来会显示没有指定。
如果已经有定义好的类,可以直接加载进来使用。或者可以点击New进行新建。
点击New,自动创建一个模板。
模板代码
classdef untitled3 < matlab.System
% untitled3 Add summary here
%
% This template includes the minimum set of functions required
% to define a System object with discrete state.
% Public, tunable properties
properties
end
properties(DiscreteState)
end
% Pre-computed constants
properties(Access = private)
end
methods(Access = protected)
function setupImpl(obj)
% Perform one-time calculations, such as computing constants
end
function y = stepImpl(obj,u)
% Implement algorithm. Calculate y as a function of input u and
% discrete states.
y = u;
end
function resetImpl(obj)
% Initialize / reset discrete-state properties
end
end
end
修改类的名字并进行保存。
对类进行实现
classdef AddSum < matlab.System
% untitled3 Add summary here
%
% This template includes the minimum set of functions required
% to define a System object with discrete state.
% Public, tunable properties
properties
end
properties(DiscreteState)
end
% Pre-computed constants
properties(Access = private)
data;
end
methods(Access = protected)
function setupImpl(obj)
obj.data = 0;
% Perform one-time calculations, such as computing constants
end
function y = stepImpl(obj,u)
obj.data = obj.data + u;
% Implement algorithm. Calculate y as a function of input u and
% discrete states.
y = obj.data;
end
function resetImpl(obj)
obj.data = 0;
% Initialize / reset discrete-state properties
end
end
end
实例化两个对象。
每调一次step(1),就会累加1.
每调一次step(2),就会累加2。obj1和obj2的结果是独立的。
定义完成以后,可以在Matlab System模块里进行加载。
第一次仿真,结果等于2.
第二次,结果等于4,符合预期。