Write Script-Based Test Using Local Functions
This example shows how to write a script-based test that uses local functions as helper
functions. The example function approximates the sine and cosine of an angle. The script-
based test checks the approximation using local functions to check for equality within a
tolerance.
Create approxSinCos Function to Test
Create this function in a file, approxSinCos.m, in your current MATLAB folder. This
function takes an angle in radians and approximates the sine and cosine of the angle
using Taylor series.
function [sinA,cosA] = approxSinCos(x)
% For a given angle in radians, approximate the sine and cosine of the angle
% using Taylor series.
sinA = x;
cosA = 1;
altSign = -1;
for n = 3:2:26
sinA = sinA + altSign*(x^n)/factorial(n);
cosA = cosA + altSign*(x^(n-1))/factorial(n-1);
altSign = -altSign;
end
Create Test Script
In your current MATLAB folder, create a new script, approxSinCosTest.m.
Note: Including functions in scripts requires MATLAB® R2016b or later.
%% Test 0rad
% Test expected values of 0
[sinApprox,cosApprox] = approxSinCos(0);
assertWithAbsTol(sinApprox,0)
assertWithRelTol(cosApprox,1)
%% Test 2pi
% Test expected values of 2pi
[sinApprox,cosApprox] = approxSinCos(2*pi);
assertWithAbsTol(sinApprox,0)
Write Script-Based Test Using Local Functions