Verify Equivalence of MATLAB Code and Generated Code
This step of the example shows how to prepare the algorithm for deployment so that it can run outside of the MATLAB® environment by generating C code from the MATLAB code and testing that the generated code is functionally equivalent to the MATLAB source code.
Examine Equivalence Test for Heart Rate Calculation
The heartRateCalc
MATLAB algorithm calculates the heart rate during the ECG analysis.
To prepare the algorithm for deployment, add an equivalence test:
In the project pane, right-click the
testsEquivalencefolder and select New > Test Class.Name the file
heartRateEquivalenceTest.m.Open the file. The file contains the default code for a test class.
Delete the code in the file and copy and paste this test code. Then, save the test. In the Editor tab, click Save.
classdef heartRateEquivalenceTest < matlabtest.coder.TestCase methods (Test,TestTags={'equivtest'}) function testHeartRate(testCase) % Load data data = load("ECGData.mat"); patientId = 64; signal = data.ECGData.Data(patientId, 1:4096); freq = data.Fs; % Build code generation artifact buildResults = build(testCase, ... "heartRateCalc", ... Configuration = "lib", ... Inputs = {signal,freq}); % Execute built artifact executionResults = execute(testCase,buildResults); % Compare against MATLAB execution tol = 1e-10; verifyExecutionMatchesMATLAB(testCase,executionResults, ... AbsTol=tol); end end end
Alternatively, you can author your own equivalence test by creating a test for
the heartRateCalc file and completing the test. For more
information, see Generate Tests for MATLAB Source Code.
The testHeartRate equivalence test:
Generates C code from the
heartRateCalcMATLAB algorithm by using the input values from the ECG data.Executes the generated code by using the same inputs as the code generation.
Verifies that the execution of the generated code matches the execution of the MATLAB code within the allowable tolerance.
Run Equivalence Test
To run the testHeartRate equivalence test, open the MATLAB Test Manager. In the Project tab, in the Tools menu, under Apps, click MATLAB Test Manager. Display the heartRateEquivalenceTest test by clicking the Not Run button.

The test manager contains the equivalence test, but the test has not run. To run the test and update the generated code coverage results for the project, run all of the tests in the project.
Clear the filter by clicking Clear filters. Run the tests
by clicking the Run button
. The testHeartRate
equivalence test passes.