Check Code for Errors and Warnings

MATLAB® Code Analyzer can automatically check your code for coding problems.

Automatically Check Code in the Editor and Live Editor — Code Analyzer

You can view warning and error messages about your code, and modify your file based on the messages. The messages update automatically and continuously so you can see if your changes addressed the issues noted in the messages. Some messages offer additional information, automatic code correction, or both.

Enable Continuous Code Checking

To enable continuous code checking in a MATLAB code file in the Editor and Live Editor:

  1. On the Home tab, in the Environment section, click Preferences.

  2. Select MATLAB > Code Analyzer, and then select the Enable integrated warning and error messages check box.

  3. Set the Underlining option to Underline warnings and errors, and then click OK.

Use Continuous Code Checking

You can use continuous code checking in MATLAB code files in the Editor and Live Editor:

  1. Open a MATLAB code file in the Editor or Live Editor. This example uses the sample file lengthofline.m that ships with the MATLAB software:

    1. Open the example file:

      open(fullfile(matlabroot,'help','techdoc','matlab_env',...
           'examples','lengthofline.m'))
      
    2. Save the example file to a folder to which you have write access. For the example, lengthofline.m is saved to C:\my_MATLAB_files.

  2. Examine the message indicator at the top of the message bar to see the Code Analyzer messages reported for the file:

    • Red indicates that syntax errors or other significant issues were detected.

    • Orange indicates warnings or opportunities for improvement, but no errors, were detected.

    • Green indicates no errors, warnings, or opportunities for improvement were detected.

    In this example, the indicator is red, meaning that there is at least one error in the file.

  3. Click the message indicator to go to the next code fragment containing a message. The next code fragment is relative to the current cursor position, viewable in the status bar.

    In the lengthofline example, the first message is at line 21. The cursor moves to the beginning of line 21.

    The code fragment for which there is a message is underlined in either red for errors or orange for warnings and improvement opportunities.

  4. View the message by moving the mouse pointer within the underlined code fragment.

    The message opens in a tooltip and contains a Details button that provides access to additional information by extending the message. Not all messages have additional information.

  5. Click the Details button.

    The window expands to display an explanation and user action.

  6. Modify your code, if needed.

    The message indicator and underlining automatically update to reflect changes you make, even if you do not save the file.

  7. On line 27, hover over prod.

    The code is underlined because there is a warning message, and it is highlighted because an automatic fix is available. When you view the message, it provides a button to apply the automatic fix.

  8. Fix the problem by doing one of the following:

    • If you know what the fix is (from previous experience), click Fix.

    • If you are unfamiliar with the fix, view, and then apply it as follows:

      1. Right-click the highlighted code (for a single-button mouse, press Ctrl+ click), and then view the first item in the context menu.

      2. Click the fix.

        MATLAB automatically corrects the code.

        In this example, MATLAB replaces prod(size(hline)) with numel(hline).

  9. Go to a different message by doing one of the following:

    • To go to the next message, click the message indicator or the next underlined code fragment.

    • To go to a line that a marker represents, click a red or orange line in the indicator bar.

      To see the first error in lengthofline, click the first red marker in the message bar. The cursor moves to the first suspect code fragment in line 47. The Details and Fix buttons are dimmed (or not visible if in MATLAB Online™), indicating that there is no more information about this message and there is no automatic fix.

      Multiple messages can represent a single problem or multiple problems. Addressing one might address all of them, or after addressing one, the other messages might change or what you need to do might become clearer.

  10. Modify the code to address the problem noted in the message—the message indicators update automatically.

    On line 47, the message suggests a delimiter imbalance. To investigate this message, in the Editor or Live Editor, move the arrow key over each of the delimiters to see if MATLAB indicates a mismatch. For instructions on how to enable delimiter matching on arrow, see Set Keyboard Preferences.

    It might appear that there are no mismatched delimiters. However, code analysis detects the semicolon in parentheses: data{3}(;), and interprets it as the end of a statement. The message reports that the two statements on line 47 each have a delimiter imbalance.

    To fix the problem, in line 47, change data{3}(;) to data{3}(:). Now, the underline no longer appears in line 47. The single change addresses the issues in both of the messages for line 47. Because the change removed the only error in the file, the message indicator at the top of the bar changes from red to orange, indicating that only warnings and potential improvements remain.

After modifying the code to address all the messages, or disabling designated messages, the message indicator becomes green. The example file with all messages addressed has been saved as lengthofline2.m. Open the corrected example file with the command:

open(fullfile(matlabroot,'help','techdoc',...
     'matlab_env', 'examples','lengthofline2.m'))

Create a Code Analyzer Message Report

You can create a report of messages for an individual file, or for all files in a folder using one of these methods:

  • Run a report for an individual MATLAB code file:

    1. On the Editor window, click and select Show Code Analyzer Report.

      A Code Analyzer Report appears in the MATLAB Web Browser.

    2. Modify your file based on the messages in the report.

    3. Save the file.

    4. Rerun the report to see if your changes addressed the issues noted in the messages.

    Creating a report for an individual file in the Live Editor is not supported.

  • Run a report for all files in a folder:

    1. On the Current Folder browser, click .

    2. Select Reports > Code Analyzer Report.

    3. Modify your files based on the messages in the report.

      For details, see MATLAB Code Analyzer Report.

    4. Save the modified file(s).

    5. Rerun the report to see if your changes addressed the issues noted in the messages.

Adjust Code Analyzer Message Indicators and Messages

Depending on the stage at which you are in completing a MATLAB file, you might want to restrict the code underlining. You can do this by using the Code Analyzer preference referred to in step 1, in Check Code for Errors and Warnings. For example, when first coding, you might prefer to underline only errors because warnings would be distracting.

Code analysis does not provide perfect information about every situation and sometimes, you might not want to change the code based on a message. If you do not want to change the code, and you do not want to see the indicator and message for that line, suppress them. For the lengthofline example, in line 48, the first message is Terminate statement with semicolon to suppress output (in functions). Adding a semicolon to the end of a statement suppresses output and is a common practice. Code analysis alerts you to lines that produce output, but lack the terminating semicolon. If you want to view output from line 48, do not add the semicolon as the message suggests.

There are a few different ways to suppress (turn off) the indicators for warning and error messages:

You cannot suppress error messages such as syntax errors. Therefore, instructions on suppressing messages do not apply to those types of messages.

Suppress an Instance of a Message in the Current File

You can suppress a specific instance of a Code Analyzer message in the current file. For example, using the code presented in Check Code for Errors and Warnings , follow these steps:

  1. In line 48, right-click at the first underline (for a single-button mouse, press Ctrl+click).

  2. From the context menu, select Suppress 'Terminate statement with semicolon...' > On This Line.

    The comment %#ok<NOPRT> appears at the end of the line, which instructs MATLAB to suppress the Terminate statement with semicolon to suppress output (in functions) Code Analyzer message for that line. The underline and mark in the indicator bar for that message disappear.

  3. If there are two messages on a line that you do not want to display, right-click separately at each underline and select the appropriate entry from the context menu.

    The %#ok syntax expands. For the example, in the code presented in Check Code for Errors and Warnings, ignoring both messages for line 48 adds the comment %#ok<NBRAK,NOPRT> at the end of the line.

    Even if Code Analyzer preferences are set to enable this message, the specific instance of the message suppressed in this way does not appear because the %#ok takes precedence over the preference setting. If you later decide you want to show the Terminate statement with semicolon to suppress output (in functions) Code Analyzer message for that line, delete %#ok<NOPRT> from the line.

Suppress All Instances of a Message in the Current File

You can suppress all instances of a specific Code Analyzer message in the current file. For example, using the code presented in Check Code for Errors and Warnings, follow these steps:

  1. In line 48, right-click at the first underline (for a single-button mouse, press Ctrl+click).

  2. From the context menu, select Suppress 'Terminate statement with semicolon...' > In This File.

The comment %#ok<*NOPRT> appears at the end of the line, which instructs MATLAB to suppress all instances of the Terminate statement with semicolon to suppress output (in functions) Code Analyzer message in the current file. All underlines and marks in the message indicator bar that correspond to this message disappear.

If there are two messages on a line that you do not want to display anywhere in the current file, right-click separately at each underline, and then select the appropriate entry from the context menu. The %#ok syntax expands. For the example, in the code presented in Check Code for Errors and Warnings, ignoring both messages for line 48 adds the comment %#ok<*NBRAK,*NOPRT>.

Even if Code Analyzer preferences are set to enable this message, the message does not appear because the %#ok takes precedence over the preference setting. If you later decide you want to show all instances of the Terminate statement with semicolon to suppress output (in functions) Code Analyzer message in the current file, delete %#ok<*NOPRT> from the line.

Suppress All Instances of a Message in All Files

You can disable all instances of a Code Analyzer message in all files. For example, using the code presented in Check Code for Errors and Warnings, follow these steps:

  1. In line 48, right-click at the first underline (for a single-button mouse, press Ctrl+click).

  2. Select Suppress 'Terminate statement with semicolon...' > In All Files.

This modifies the Code Analyzer preference setting.

If you know which message or messages that you want to suppress, you can disable them directly using Code Analyzer preferences, as follows:

  1. On the Home tab, in the Environment section, click Preferences.

  2. Select MATLAB > Code Analyzer.

  3. Search the messages to find the ones you want to suppress.

  4. Clear the check box associated with each message you want to suppress in all files.

  5. Click OK.

Save and Reuse Code Analyzer Message Settings

You can specify that you want certain Code Analyzer messages enabled or disabled, and then save those settings to a file. When you want to use a settings file with a particular file, you select it from the Code Analyzer preferences pane. That setting file remains in effect until you select another settings file. Typically, you change the settings file when you have a subset of files for which you want to use a particular settings file.

Follow these steps:

  1. On the Home tab, in the Environment section, click Preferences.

    The Preferences dialog box opens.

  2. Select MATLAB > Code Analyzer.

  3. Enable or disable specific messages, or categories of messages.

  4. Click the Actions button , select Save as, and then save the settings to a txt file.

  5. Click OK.

You can reuse these settings for any MATLAB file, or provide the settings file to another user.

To use the saved settings:

  1. On the Home tab, in the Environment section, click Preferences.

    The Preferences dialog box opens.

  2. Select MATLAB > Code Analyzer.

  3. Use the Active Settings drop-down list to select Browse....

    The Open dialog box appears.

  4. Choose from any of your settings files.

    The settings you choose are in effect for all MATLAB files until you select another set of Code Analyzer settings.

Understand Code Containing Suppressed Messages

If you receive code that contains suppressed messages, you might want to review those messages without the need to unsuppress them first. A message might be in a suppressed state for any of the following reasons:

  • One or more %#ok<message-ID> directives are on a line of code that elicits a message specified by <message-ID>.

  • One or more %#ok<*message-ID> directives are in a file that elicits a message specified by <message-ID>.

  • It is cleared in the Code Analyzer preferences pane.

  • It is disabled by default.

To determine the reasons why some messages are suppressed:

  1. Search the file for the %#ok directive and create a list of all the message IDs associated with that directive.

  2. On the Home tab, in the Environment section, click Preferences.

    The Preferences dialog box opens.

  3. Select MATLAB > Code Analyzer.

  4. In the search field, type msgid: followed by one of the message IDs, if any, you found in step 1.

    The message list now contains only the message that corresponds to that ID. If the message is a hyperlink, click it to see an explanation and suggested action for the message. This can provide insight into why the message is suppressed or disabled. The following image shows how the Preferences dialog box appears when you enter msgid:CPROP in the search field.

  5. Click the button to clear the search field, and then repeat step 4 for each message ID you found in step 1.

  6. Display messages that are disabled by default and disabled in the Preferences pane by clicking the down arrow to the right of the search field. Then, click Show Disabled Messages.

  7. Review the message associated with each message ID to understand why it is suppressed in the code or disabled in Preferences.

Understand the Limitations of Code Analysis

Code analysis is a valuable tool, but there are some limitations:

  • Sometimes, it fails to produce Code Analyzer messages where you expect them.

    By design, code analysis attempts to minimize the number of incorrect messages it returns, even if this behavior allows some issues to go undetected.

  • Sometimes, it produces messages that do not apply to your situation.

    When provided with message, click the Detail button for additional information, which can help you to make this determination. Error messages are almost always problems. However, many warnings are suggestions to look at something in the code that is unusual and therefore suspect, but might be correct in your case.

    Suppress a warning message if you are certain that the message does not apply to your situation. If your reason for suppressing a message is subtle or obscure, include a comment giving the rationale. That way, those who read your code are aware of the situation.

    For details, see Adjust Code Analyzer Message Indicators and Messages.

These sections describe code analysis limitations regarding the following:

Distinguish Function Names from Variable Names

Code analysis cannot always distinguish function names from variable names. For the following code, if the Code Analyzer message is enabled, code analysis returns the message, Code Analyzer cannot determine whether xyz is a variable or a function, and assumes it is a function. Code analysis cannot make a determination because xyz has no obvious value assigned to it. However, the program might have placed the value in the workspace in a way that code analysis cannot detect.

function y=foo(x)
   .
   .
   .
   y = xyz(x);
end

For example, in the following code, xyz can be a function, or can be a variable loaded from the MAT-file. Code analysis has no way of making a determination.

function y=foo(x)
    load abc.mat
    y = xyz(x);
end
Variables might also be undetected by code analysis when you use the eval, evalc, evalin, or assignin functions.

If code analysis mistakes a variable for a function, do one of the following:

  • Initialize the variable so that code analysis does not treat it as a function.

  • For the load function, specify the variable name explicitly in the load command line. For example:

     function y=foo(x)
         load abc.mat xyz
         y = xyz(x);
     end

Distinguish Structures from Handle Objects

Code analysis cannot always distinguish structures from handle objects. In the following code, if x is a structure, you might expect a Code Analyzer message indicating that the code never uses the updated value of the structure. If x is a handle object, however, then this code can be correct.

function foo(x)
		x.a = 3;
end

Code analysis cannot determine whether x is a structure or a handle object. To minimize the number of incorrect messages, code analysis returns no message for the previous code, even though it might contain a subtle and serious bug.

Distinguish Built-In Functions from Overloaded Functions

If some built-in functions are overloaded in a class or on the path, Code Analyzer messages might apply to the built-in function, but not to the overloaded function you are calling. In this case, suppress the message on the line where it appears or suppress it for the entire file.

For information on suppressing messages, see Adjust Code Analyzer Message Indicators and Messages.

Determine the Size or Shape of Variables

Code analysis has a limited ability to determine the type of variables and the shape of matrices. Code analysis might produce messages that are appropriate for the most common case, such as for vectors. However, these messages might be inappropriate for less common cases, such as for matrices.

Analyze Class Definitions with Superclasses

Code Analyzer has limited capabilities to check class definitions with superclasses. For example, Code Analyzer cannot always determine if the class is a handle class, but it can sometimes validate custom attributes used in a class if the attributes are inherited from a superclass. When analyzing class definitions, Code Analyzer tries to use information from the superclasses but often cannot get enough information to make a certain determination.

Analyze Class Methods

Most class methods must contain at least one argument that is an object of the same class as the method. But it does not always have to be the first argument. When it is, code analysis can determine that an argument is an object of the class you are defining, and it can do various checks. For example, it can check that the property and method names exist and are spelled correctly. However, when code analysis cannot determine that an object is an argument of the class you are defining, then it cannot provide these checks.

Enable MATLAB Compiler Deployment Messages

You can switch between showing or hiding Compiler deployment messages when you work on a file by changing the Code Analyzer preference for this message category. Your choice likely depends on whether you are working on a file to be deployed. When you change the preference, it also changes the setting in the Editor. The converse is also true— when you change the setting from the Editor, it effectively changes this preference. However, if the dialog box is open at the time you modify the setting in the Editor, you will not see the changes reflected in the Preferences dialog box. Whether you change the setting from the Editor or from the Preferences dialog box, it applies to the Editor and to the Code Analyzer Report.

To enable MATLAB Compiler™ deployment messages:

  1. On the Home tab, in the Environment section, click Preferences.

    The Preferences dialog box opens.

  2. Select MATLAB > Code Analyzer.

  3. Click the down arrow next to the search field, and then select Show Messages in Category > MATLAB Compiler (Deployment) Messages.

  4. Click the Enable Category button.

  5. Clear individual messages that you do not want to display for your code (if any).

  6. Decide if you want to save these settings, so you can reuse them next time you work on a file to be deployed.

The settings txt file, which you can create as described in Save and Reuse Code Analyzer Message Settings, includes the status of this setting.