Tips for Defining System Objects - MATLAB & Simulink (original) (raw)

A System object™ is a specialized MATLAB® object that is optimized for iterative processing. Use System objects when you need to run an object multiple times or process data in a loop. When defining your own System object, use the following suggestions to help your System object run more quickly.

General

Inputs and Outputs

Using ~ as an Input Argument in Method Definitions

All methods, except static methods, expect the System object handle as the first input argument. You can use any name for your System object handle. The code inserted by the MATLAB Editor menu usesobj.

In many examples, instead of passing in the object handle, ~ is used to indicate that the object handle is not used in the function. Using ~ instead of an object handle prevents warnings about unused variables.

Properties

Text Comparisons

Do not use character vector comparisons or character vector-based switch statements in the stepImpl method. Instead, create a method handle insetupImpl. This handle points to a method in the same class definition file. Use that handle in a loop in stepImpl.

This example shows how to use method handles and cached local variables in a loop to implement an efficient object. In setupImpl, choosemyMethod1 or myMethod2 based on a character vector comparison and assign the method handle to the pMethodHandle property. Because there is a loop in stepImpl, assign thepMethodHandle property to a local method handle,myFun, and then use myFun inside the loop.

classdef MyClass < matlab.System function setupImpl(obj) if strcmp(obj.Method, 'Method1') obj.pMethodHandle = @myMethod1; else obj.pMethodHandle = @myMethod2; end end function y = stepImpl(obj,x) myFun = obj.pMethodHandle; for p=1:1000 y = myFun(obj,x) end end end function y = myMethod1(x) y = x+1; end function y = myMethod2(x) y = x-1; end end

For System objects being included in Simulink, add the StrictDefaults attribute. This attribute sets all the MutableImpl methods to return false by default.

Code Generation

For information about System objects and code generation, see System Objects in MATLAB Code Generation (MATLAB Coder).