Generate Code for User-Defined System Objects - MATLAB & Simulink (original) (raw)
How To Create A User-Defined System object
To create a user-defined System object™ and generate code:
- Create a class that subclasses from matlab.System.
- Define one of the following sets of methods:
setupImpl
andstepImpl
setupImpl
,outputImpl
, andupdateImpl
- Optionally, if your System object has private state properties, define the
resetImpl
method to initialize them to zero. - Write a top-level design function that creates an instance of your System object and calls the object, or calls the
output
andupdate
methods.
Note
TheresetImpl
method runs automatically during System object initialization. For HDL code generation, you cannot call the publicreset
method. - Write a test bench function that exercises the top-level design function.
- Generate HDL code.
User-Defined System object Example
This example shows how to generate HDL code for a user-defined System object that implements the setupImpl
andstepImpl
methods.
In a writable folder, create a System object,
CounterSysObj
, which subclasses frommatlab.System
. Save the code asCounterSysObj.m
.
classdef CounterSysObj < matlab.System
properties (Nontunable)
Threshold = int32(1)
end
properties (Access=private)
State
Count
end
methods
function obj = CounterSysObj(varargin)
setProperties(obj,nargin,varargin{:});
end
endmethods (Access=protected)
function setupImpl(obj, ~)
% Initialize states
obj.Count = int32(0);
obj.State = int32(0);
end
function y = stepImpl(obj, u)
if obj.Threshold > u(1)
obj.Count(:) = obj.Count + int32(1); % Increment count
end
y = obj.State; % Delay output
obj.State = obj.Count; % Put new value in state
end
end
end
ThestepImpl
method implements the System object functionality. The setupImpl
method defines the initial values for the persistent variables in the System object.
2. Write a function that uses this System object and save it as myDesign.m
. This function is your DUT.
function y = myDesign(u)
persistent obj
if isempty(obj)
obj = CounterSysObj('Threshold',5);
end
y = obj(u);
end
3. Write a test bench that calls the DUT function and save it asmyDesign_tb.m
.
clear myDesign
for ii=1:10
y = myDesign(int32(ii));
end
4. Generate HDL code for the DUT function as you would for any other MATLAB® code, but skip fixed-point conversion.