Generate Code for MATLAB Functions That Use Handle Classes
You can use handle classes in MATLAB® code intended for code generation. Handle classes are classes that derive from the handle superclass. For more information about value classes and handle classes in MATLAB, see Comparison of Handle and Value Classes.
This example shows how to use the codegen command to generate standalone C++ code for a MATLAB function that uses a handle class. You can integrate the generated C++ code into custom C++ code. When using handle classes in MATLAB code for code generation, certain considerations apply. See Class Limitations for Code Generation.
Examine MATLAB Class and Function
Examine the MATLAB handle class ExpMovingAverage. This class smooths a stream of input data by applying an exponential moving average filter. The property Alpha is the smoothing factor, and the property Value stores the current filtered result. The update method processes each new data point, and blends it with the previous average to reduce noise. Because ExpMovingAverage is a handle class, it preserves its internal state between updates, which allows you to filter signals that arrive one sample at a time.
type ExpMovingAverage.mclassdef ExpMovingAverage < handle
properties
Alpha
Value
IsInitialized
end
methods
function obj = ExpMovingAverage(alpha)
obj.Alpha = alpha;
obj.Value = 0;
obj.IsInitialized = false;
end
function update(obj,x)
if ~obj.IsInitialized
obj.Value = x;
obj.IsInitialized = true;
else
obj.Value = obj.Alpha*x+(1-obj.Alpha)*obj.Value;
end
end
function y = getValue(obj)
y = obj.Value;
end
end
end
Examine the MATLAB function filterSignal, which uses the ExpMovingAverage handle class. The function takes an input signal, applies the averaging filter, and returns an output vector of filtered values.
type filterSignalfunction y = filterSignal(x) %#codegen
n = numel(x);
y = zeros(size(x));
ema = ExpMovingAverage(0.1);
for i = 1:n
ema.update(x(i));
y(i) = ema.getValue();
end
end
Generate noisy data that emulates a temperate sensor for 200 time steps. The temperature starts at 20°C and gradually increases. Use the filterSignal function to smooth the noisy data.
time = (1:200)'; raw_temp = 20+0.01*time+0.3*randn(200,1); filtered_temp_ML = filterSignal(raw_temp); plot(raw_temp,"red"); hold on plot(filtered_temp_ML,"blue"); xlabel('Time (s)'); ylabel('Temperature (°C)'); hold off;

Generate and Run MEX Functions
Generate a MEX function for the filterSignal function by using the codegen command. Then, run the generated MEX function to check that the generated code has the same behavior as the original MATLAB code.
It is a best practice to perform this step because you can run the generated MEX function to detect run-time errors that are harder to diagnose in standalone code. For example, the MEX function includes memory integrity checks by default.
By default, the codegen command generates a MEX function in C in the working folder. Use the -lang:C++ option to produce a C++ MEX function. Use the -args option with the coder.typeof function to specify that the input argument to filterSignal is an arbitrarily long column vector of doubles.
codegen -lang:c++ filterSignal -args {coder.typeof(0,[Inf 1])}
Code generation successful.
Test the MEX function with the same input that you passed to the original MATLAB function. The MEX function produces the same output.
filtered_temp_MEX = filterSignal_mex(raw_temp); isequal(filtered_temp_MEX,filtered_temp_ML)
ans = logical
1
Generate and Inspect C++ Code
Generate a C++ static library by using the codegen command with the -config:lib option. Use the same -args syntax that you used to generate the MEX function, and use the -O disable:inline option to prevent the code generator from inlining the class definition.
codegen -config:lib -lang:c++ filterSignal -O disable:inline -args {coder.typeof(0,[Inf 1])}
Warning: Code generation is using a coder.EmbeddedCodeConfig object. Because Embedded Coder is not installed, this might cause some Embedded Coder features to fail. Code generation successful (with warnings): View report
Examine the definition of the C++ class ExpMovingAverage in the file ExpMovingAverage.h.
file = fullfile("codegen","lib","filterSignal","ExpMovingAverage.h"); coder.example.extractLines(file,"// Type Definitions","};",1,0)
// Type Definitions
class ExpMovingAverage {
public:
void update(double x);
double getValue() const;
void init();
double Alpha;
double Value;
boolean_T IsInitialized;