Main Content

MATLAB Design Cyclomatic Complexity

Metric ID

slcomp.MatlabCyclomaticComplexity

Description

The design cyclomatic complexity is the number of possible execution paths through a design. In general, the more paths there are through a design, the more complex the design is. When you keep the design cyclomatic complexity low, the design typically is easier to read, maintain, and test. The design cyclomatic complexity is calculated as the number of decision paths plus one. The metric adds one to account for the execution path represented by the default path. The design cyclomatic complexity includes the default path because the metric identifies each possible outcome from an execution path, including the default outcome.

Use this metric to determine the design cyclomatic complexity of the MATLAB® code in your design.

The MATLAB design cyclomatic complexity is the total number of execution paths through the MATLAB code in a unit or component. The number of execution paths is calculated as the number of MATLAB decisions, MATLAB Decision Count, plus one for the default path. The default path is only counted once per unit or component.

Computation Details

The metric includes the decisions associated with logical operations that might be short-circuited during code execution.

Collection

To collect data for this metric, use getMetrics with the metric identifier slcomp.MatlabCyclomaticComplexity.

Results

For this metric, instances of metric.Result return Value as the MATLAB design cyclomatic complexity of a unit or component.

Examples

Suppose you have a unit that contains only a MATLAB Function block with this code:

function y = fcn(u)
    if u < 0
        % one decision
        y = -1*u;
    else
        % default path
        % zero decisions
        y = u;
    end
end

For an if-else statement, the number of decisions is one because the if statement represents one decision and the else statement represents the default behavior. The execution path follows the default path if no decisions are made.

  • If the input to the MATLAB Function block is less than zero, the output of the MATLAB Function block is the input multiplied by negative one.

  • Otherwise, by default, the output of the MATLAB Function block is equal to the input of the MATLAB Function block.

In this example, the number of MATLAB decisions is one and therefore the MATLAB design cyclomatic complexity of the unit is two. The default path is not included in the number of decisions because no decision is made to reach a default state, but the default path is included in the design cyclomatic complexity.

The value of the MATLAB design cyclomatic complexity represents the two possible execution paths through the unit, either:

  • u < 0 and the output of the MATLAB Function block is the input multiplied by negative one

  • u ≥ 0 and the output of the MATLAB Function block is equal to the input of the MATLAB Function block

See Also

Related Topics