Main Content

Verify a MATLAB Algorithm

This tutorial shows how to use MATLAB® Test™ to verify a MATLAB algorithm. This tutorial uses a project that contains a MATLAB algorithm, MATLAB tests, and requirements. In this tutorial, you follow these steps to run the tests, collect coverage, verify requirements, and deploy the algorithm as C code:

  1. Verify Code by Running Tests: Verify the algorithm by using the MATLAB Test Manager to run tests and view results.

  2. Collect Coverage for Tests and Address Missing Coverage: Collect coverage and add coverage for lines of source code that are uncovered by writing new tests.

  3. Verify Requirements and Address Missing Traceability: Verify requirements that are linked to tests and add traceability for unlinked requirements.

  4. Generate C Code and Test for Equivalence: Deploy the algorithm as C code and test the generated code for functional equivalence.

Examine Project

This tutorial uses the MATLABShortestPath project.

openProject("MATLABShortestPath");

The project contains:

  • Requirement sets, located in the requirements folder

  • A MATLAB algorithm, located in the src folder

  • MATLAB tests, located in the tests folder

  • A script to demonstrate running the MATLAB algorithm, located in the scripts folder

  • Links from MATLAB code lines to requirements, stored in SLMX files in the src and tests folders

Use the Shortest Path Function

The shortest_path function tests the validity of the inputs to the function and then uses the Djikstra algorithm to calculate the number of edges in the shortest path between two nodes on a graph. The inputs to the function are an adjacency matrix that represents a graph, the starting node, and the ending node. For example, consider this adjacency matrix that represents a graph with six nodes.

A = [0 1 0 0 1 0;
    1 0 1 0 0 0;
    0 1 0 1 0 0;
    0 0 1 0 1 1;
    1 0 0 1 0 0;
    0 0 0 1 0 0];

Create a graph from the matrix and plot it.

G = graph(A);
plot(G,EdgeLabel=G.Edges.Weight)

The figure shows a pentagon with an additional line segment that connects to the tip of the pentagon. Node 1 is diametrically opposed to the tip and node 6 is at the end of the segment connected to the tip.

Calculate the number of edges in the shortest path between nodes 1 and 6.

pathLength = shortest_path(A,1,6)
pathLength = 
3

See Also

Apps

Related Topics