Как исправить ошибки в матлаб

Main Content

Note

As of version 7.5, MATLAB® supports error handling that
is based on the MException class. Calling rethrow with
a structure argument, as described on this page, is now replaced by
calling rethrow with an MException object, as described
on the reference page for rethrow. rethrow called with
a structure input will be removed in a future version.

Syntax

rethrow(errorStruct)

Description

rethrow(errorStruct)
reissues the error specified by errorStruct. The
currently running function terminates and control returns to the keyboard
(or to any enclosing catch block). The errorStruct argument
must be a MATLAB structure containing at least the message and identifier fields:

Fieldname

Description

message

Text of the error message

identifier

Identifier for the error

stack

Information about the error from the program stack

For information about error identifiers, see MException.

Examples

rethrow is usually used in conjunction with try, catch statements
to reissue an error from a catch block after performing catch-related
operations. For example,

try
   do_something
catch
   do_cleanup
   rethrow(previous_error)
end

Tips

The errorStruct input can contain the field stack,
identical in format to the output of the dbstack command.
If the stack field is present, the stack of the
rethrown error will be set to that value. Otherwise, the stack will
be set to the line at which the rethrow occurs.

Extended Capabilities

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

This function fully supports thread-based environments. For
more information, see Run MATLAB Functions in Thread-Based Environment.

Version History

Introduced before R2006a

Main Content

Generate, catch, and respond to warnings and errors

To make your code more robust, check for edge cases and problematic
conditions. The simplest approach is to use an if or
switch statement to check for a specific condition,
and then issue an error or warning. try/catch statements
allow you to catch and respond to any error.

MATLAB Language Syntax

try, catch Execute statements and catch resulting errors

Functions

error Throw error and display message
warning Display warning message
lastwarn Last warning message
assert Throw error if condition false
onCleanup Cleanup tasks upon function completion

Topics

  • Issue Warnings and Errors

    To flag unexpected conditions when running a program, issue a warning. To flag
    fatal problems within the program, throw an error. Unlike warnings, errors halt
    the execution of a program.

  • Suppress Warnings

    Your program might issue warnings that do not always adversely affect
    execution. To avoid confusion, you can hide warning messages during execution by
    changing their states from 'on' to
    'off'.

  • Restore Warnings

    You can save the warning current states, modify warning states, and restore
    the original warning states. This technique is useful if you temporarily turn
    off some warnings and later reinstate the original settings.

  • Change How Warnings Display

    You can control how warnings appear in MATLAB®, including the display of warning suppression information and
    stack traces.

  • Use try/catch to Handle Errors

    Use a try/catch statement to execute code after your
    program encounters an error.

  • Clean Up When Functions Complete

    It is a good programming practice to leave your program environment in a clean
    state that does not interfere with any other program code.

Обзор

Неважно, как тщательно вы планируете и тестируете программы, которые вы написали, они не могут всегда запускаться так же гладко как ожидалось, когда выполняется при различных условиях. Это всегда — хорошая идея включать проверку ошибок в программы, чтобы гарантировать надежную операцию при всех условиях.

В MATLAB® программное обеспечение, можно решить, как программы отвечают на различные типы ошибок. Можно хотеть предложить пользователю более вход, отображение расширенная ошибка или предупреждение информации, или возможно повторить вычисление с помощью значений по умолчанию. Возможности обработки ошибок в MATLAB помогают вашей проверке программ на особое состояние ошибки и выполняют соответствующий код в зависимости от ситуации.

То, когда MATLAB обнаруживает серьезный отказ в команде или программе, это запускается, это собирает информацию о том, что происходило во время ошибки, отображает сообщение, чтобы помочь пользователю изучить то, что пошло не так, как надо и отключает команду или программу. Это называется throwing an exception. Можно получить исключение при вводе команд в командной строке MATLAB или при выполнении кода программы.

Получение исключения в командной строке

Если вы получаете исключение в подсказке MATLAB, у вас есть несколько опций о том, как иметь дело с нею аналогичный описанному ниже.

Определение отказа из сообщения об ошибке

Выполните сообщение об ошибке, которое отобразил MATLAB. Большинство сообщений об ошибке пытается объяснить, по крайней мере, мгновенную причину отказа программы. Часто существует достаточная информация, чтобы определить причину и что необходимо сделать, чтобы исправить ситуацию.

Рассмотрение провального кода

Если функция, в которой произошла ошибка, реализована как файл программы MATLAB, сообщение об ошибке должно включать линию, которая выглядит примерно так:

surf

Error using surf (line 49)
Not enough input arguments.

Текст включает имя функции, которое выдало ошибку (surf, в этом случае), и показывает провальный номер строки в программном файле этой функции. Кликните по номеру строки; MATLAB открывает файл и располагает курсор в местоположении в файле где порожденная ошибка. Можно смочь определить причину ошибки путем исследования этой линии и кода, который предшествует ему.

Продвижение через код в отладчик

Можно использовать Отладчик MATLAB, чтобы продвинуться через провальный код. Кликните по подчеркнутому тексту ошибки, чтобы открыть файл в редакторе MATLAB в или около точки ошибки. Затем кликните по дефису в начале той линии, чтобы установить точку останова в том местоположении. Когда вы повторно выполняете свою программу, MATLAB приостанавливает выполнение в точке останова и позволяет вам продвинуться через код программы. Команда dbstop on error также полезно в нахождении точки ошибки.

См. документацию относительно Отладки Файлы кода MATLAB для получения дополнительной информации.

Получение исключения в коде программы

Когда вы написали свою собственную программу в программном файле, вы можете исключения catch и попытка обработать или разрешить их вместо того, чтобы позволить вашей программе завершать работу. Когда вы отлавливаете исключение, вы прерываете нормальный процесс завершения и вводите блок кода, который справляется с дефектной ситуацией. Этот блок кода называется catch block.

Некоторые вещи, которые вы можете хотеть сделать в блоке выгоды:

  • Исследуйте информацию, которая была получена об ошибке.

  • Соберите дополнительную информацию, чтобы сообщить пользователю.

  • Попытайтесь выполнить задачу под рукой некоторым другим способом.

  • Очистите любые нежелательные побочные эффекты ошибки.

Когда вы достигаете конца блока выгоды, можно или продолжить выполнять программу, если это возможно, или отключать ее.

Используйте MException возразите, чтобы получить доступ к информации об исключении в вашей программе. Для получения дополнительной информации смотрите, Отвечают на Исключение.

Генерация нового исключения

Когда ваш код программы обнаруживает условие, которое или заставит программу привести к сбою или привести к недопустимым результатам, это должно выдать исключение. Эта процедура

  • Сохраняет информацию о том, что пошло не так, как надо и что код выполнял во время ошибки.

  • Собирает любую другую уместную информацию об ошибке.

  • Дает MATLAB команду выдавать исключение.

Используйте MException возразите, чтобы получить информацию об ошибке. Для получения дополнительной информации смотрите, Выдают Исключение.

При
обнаружении ошибок в выражениях или
командах MATLAB указывает на наличие
ошибки. Из текста иногда можно понять
сущность ошибки, но часто комментарии
бывают настолько общими, что трудно
установить место и содержание ошибки.
Надо отличать предупреждение
об ошибке от сообщения
о ней. Предупреждения
(обычно после слова Warning)
не останавливают вычисления и лишь
предупреждают о том, что ответ может
быть ошибочным.

Пример
предупреждения:

>>
sin(0)/0

Warning:
Divide
by
zero.

ans =

NaN

При
сообщении
об ошибке
красного
цвета
(после
знаков ???) MATLAB не выдает решение. Вычислим,
например, значение с помощью встроенной
элементарной функции sqrt
(квадратный корень), введя выражение

>>
sqr(2)

???
Undefined function or variable ‘sqr’.

Это
сообщение об ошибке говорит о том (на
английском языке), что не определена
функция или переменная и указывает на
sqr.

Устранение
ошибки наиболее целесообразно не путем
набора нового правильного выражения,
а редактированием ошибочного.

Существует несколько
способов возврата в строку ввода ранее
введенных команд.

Первый
способ

– с помощью клавиш <↑>
и <↓>
(см. разд. 1.2).

При
вычислении значения обнаружена
синтаксическая
ошибка:

не определена функция sqr.
Клавишей <↑> вернем команду >>
sqr(2) в командную строку. Отредактируем
ее: после sqr
вставим t
и нажмем клавишу <Enter>:

>> sqrt(2)

ans =

1.4142

Второй
способ

– копирование из окна Command
History.

Для
активизации окна Command
History
необходимо
войти в меню View
командного
окна, выбрать
вкладку с одноименным названием и
щелкнуть на ней левой кнопкой мыши
(поставить галочку). В этом окне
отображаются дата и время каждого сеанса
работы в MATLAB, а также перечень команд,
вводимых в течение каждого сеанса (рис.
1.4).

Если
в окне Command
History
дважды щелкнуть левой кнопкой мыши на
какой — либо команде, эта команда будет
выполнена. Это равнозначно вводу данной
команды в командное окно и последующему
нажатию клавиши <Enter>
(рис. 1.4).

Рис. 1.4

Если
щелкнуть на какой — либо команде окна
Command
History
левой
кнопкой мыши, то данная команда становится
текущей (на синем фоне). Можно выделить
нужную последовательность команд при
помощи комбинации клавиш <Shift>+<↑>,
<
Shift>+<↓>.
При щелчке правой кнопкой мыши на
выделенной области окна Command
History
появляется
всплывающее меню. Выбор пункта Copy
приводит к копированию выделенной
последовательности в буфер обмена
Windows.
При щелчке правой кнопкой мыши на области
окна Command
Window
появляется всплывающее меню. Выбор
пункта Paste
приводит к вставке скопированной
последовательности команд в командную
строку. Весь вставленный в командную
строку набор команд отправляется на
выполнение нажатием клавиши <Enter>.

До
нажатия клавиши <Enter>
содержимое набора можно редактировать,
используя обычные приемы редактирования,
общие для Windows
— приложений, в том числе и с помощью
мыши. Можно вносить в команды необходимые
изменения, удалять лишние команды и
добавлять новые. При редактировании
клавиши <↑>
и
<↓>

могут использоваться для перемещения
между строками набора.

Третий
способ

– копирование из содержимого текстового
поля рабочего окна.

В
текстовом поле можно выделить с помощью
мыши любую команду и копировать ее в
буфер обмена операционной системы
Windows,
а затем вставить в командную строку.
Выделение и вставка производится теми
же средствами, что и в других Windows
— приложениях.

При
вычислениях любое арифметическое
выражение набирается с клавиатуры в
командной строке. Редактор MATLAB укажет
на синтаксические ошибки. Но он не
обнаружит так называемые семантические
ошибки
,
когда, например, пользователь ошибочно
заменит знаки операций <+> на <–>
или неверной расстановкой скобок изменит
общий порядок выполнения операций и т.
д.

MATLAB
совместно с пакетом ToolBox
Symbolic
Math
(Глава 7) предоставляет возможность
визуального контроля введенного
выражения.

Пусть требуется
вычислить значение выражения

F=

при
x
= 0,1,
y
= 0,2
.

Введем
значения переменных x
и y.
Наберем с клавиатуры арифметическое
выражение F
и вычислим его значение, нажав клавишу
<Enter>.
Редактор MATLAB синтаксических ошибок
ввода не обнаружил. В результате получим
F
=

7,2111
(рис. 1.5).

В
третьей командной строке редактируется
предыдущая команда (<↑>)
для придания арифметическому выражению
F
статуса символьного с помощью команды
sym
(разд.
7.1). Выведенное в командное окно символьное
выражение F
синтаксически совпадает с арифметическим.

Рис. 1.5

Далее
команда pretty(F)
(см.
разд. 7.1) выводит в командное окно
символьное выражение F
в виде, близком к математической формуле.
Выведенная и исходная формулы не
совпадают. Предполагаемая ошибка ввода
– знаменатель исходной дроби не заключен
в скобки.

В
пятой командной строке редактируется
третья команда (<↑↑>)
для устранения ошибки ввода.

Затем
команда pretty(F)
отображает в командном окне исправленное
выражение. Теперь выведенная формула
совпадает с исходной.

В седьмой командной
строке редактируется пятая команда
(<↑↑>) для придания исправленному
символьному выражению статуса
арифметического. Седьмая команда
вычисляет правильный результат F =— 2,6904.

Иногда появляется
совершенно неожиданный или явно
неправильный результат. Так, если вы
попытаетесь вычислить приx
= -8
, набирая

>> x=-8;r=x^(1/3)

r=

1.0000 + 1.7321i

ответ, который система
MATLABсоздает, не похож на
ожидаемый результат-2. Тем не менее,
полученный результат является кубическим
корнем из-8, что подтверждается
возведением этого результата в куб:

>> r^3

ans =

-8.0000 + 0.0000i

Дело в том, что
многозначная функция имеет в комплексной
плоскости три ветви, а уравнение x3
= -8
– три разных значения корня:

>> solve(‘x^3=-8’)

ans =

[ -2]

[ 1-i*3^(1/2)]

[ 1+i*3^(1/2)]

Система MATLABвоспринимает для отрицательногоxкак значение

.

Поэтому для получения
ожидаемого результата при вычислении
, x = -8, надо набирать

>> x=-8;r=sign(x)*abs(x)^(1/3)

r=

-2

Это обстоятельство
надо обязательно учитывать, например,
при построении графика функции y
=
.

Соседние файлы в папке OKMEC

  • #
  • #

The MATLAB® Code Analyzer can automatically check your code for coding problems. You
can view warning and error messages about your code, and modify your file based on the
messages. The messages are updated automatically and continuously so you can see if your
changes address 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, on the Home tab, in the
Environment section, click
Preferences. Select > , and then select the Enable integrated warning
and error messages
check box. Set the
Underlining option to Underline warnings and
errors
.

When continuous code checking is enabled, MATLAB displays warning and error messages about your code in the Editor and
Live Editor. For example, the sample file lengthofline.m contains
several errors and warnings. Copy the code into the Editor and save the file as
lengthofline.m.

 lengthofline.m Code

View Code Analyzer Status for File

When you open a file in the Editor or Live Editor, the message indicator at the
top of the indicator bar shows the overall Code Analyzer status for the file.

Message Indicator Description
Red error symbol
Preferences. Select > , and then select the Enable integrated warning
and error messages
check box. Set the
Underlining option to Underline warnings and
errors
.

When continuous code checking is enabled, MATLAB displays warning and error messages about your code in the Editor and
Live Editor. For example, the sample file lengthofline.m contains
several errors and warnings. Copy the code into the Editor and save the file as
lengthofline.m.

 lengthofline.m Code

View Code Analyzer Status for File

When you open a file in the Editor or Live Editor, the message indicator at the
top of the indicator bar shows the overall Code Analyzer status for the file.

Message Indicator Description
Red error symbol

File contains syntax errors or other significant
issues.

Yellow warning symbol

File contains warnings or opportunities for improvement,
but no errors.

Green check mark symbol

File contains warnings or opportunities for improvement,
but no errors.

Green check mark symbol

File contains no errors, warnings, or opportunities for
improvement.

For example, in lengthofline.m, the message indicator is Red error symbol, meaning that the file contains at least one
error.

lengthofline file in the Editor with the red error symbol displayed in the indicator bar, meaning that the file contains at least one
error.

lengthofline file in the Editor with the red error symbol displayed in the indicator bar

View Code Analyzer Messages

To go to the first code fragment containing a message, click the message
indicator. The identified code fragment is underlined in either red for errors or
orange for warnings and improvement opportunities. If the file contains an error,
clicking the message indicator brings you to the first error.

For example, in lengthofline.m, when you click the message
indicator, the cursor moves to line 47, where the first error occurs. MATLAB displays the errors for that line next to the error marker in the
indicator bar. Multiple messages can represent a single problem or multiple
problems. Addressing one message might address all of them. Or, after you address
one, the other messages might change or what you need to do can become
clearer.

lengthofline file in the Editor after clicking the message indicator. Three errors display next to the error marker in the indicator bar.

To go to the next code fragment containing a message, click the message indicator.
You also can click a marker in the indicator bar to go to the line that the marker
represents. For example, click the first marker in the indicator bar in
lengthofline.m. The cursor moves to the beginning of line
21.

To view the message for a code fragment, move the mouse pointer within the
underlined code fragment. Alternatively, you can position your cursor within the
underlined code fragment and press Ctrl+M. If additional
information is available for the message, the message includes a
Details button. Click the button to display the
additional information and any suggested user actions.

lengthofline file in the Editor showing a warning message with a details button

To go to the next code fragment containing a message, click the message indicator.
You also can click a marker in the indicator bar to go to the line that the marker
represents. For example, click the first marker in the indicator bar in
lengthofline.m. The cursor moves to the beginning of line
21.

To view the message for a code fragment, move the mouse pointer within the
underlined code fragment. Alternatively, you can position your cursor within the
underlined code fragment and press Ctrl+M. If additional
information is available for the message, the message includes a
Details button. Click the button to display the
additional information and any suggested user actions.

lengthofline file in the Editor showing a warning message with a details button

Fix Problems in Code

For each message in your code file, modify the code to address the problem noted
in the message. As you modify the code, the message indicator and underlining are
updated to reflect changes you make, even if you do not save the file.

For example, on line 47 in lengthofline.m, the message suggests
a delimiter imbalance. When you move the arrow keys over each delimiter, MATLAB does not appear to indicate a mismatch. However, code analysis detects
the semicolon in data{3}(;) and interprets it as the end of a
statement.

lengthofline file in the Editor after clicking the message indicator. Three errors display next to the error marker in the indicator bar.

To fix the problem in line 47, change data{3}(;) to
data{3}(:). The single change addresses all of the messages
on line 47, and the underline no longer appears for the line. Because the change
removes the only error in the file, the message indicator at the top of the bar
changes from Red error symbol

To fix the problem in line 47, change data{3}(;) to
data{3}(:). The single change addresses all of the messages
on line 47, and the underline no longer appears for the line. Because the change
removes the only error in the file, the message indicator at the top of the bar
changes from Red error symbol to Yellow warning symbol, indicating that only warnings and potential
improvements remain.

For some messages, MATLAB suggests an automatic fix that you can apply to fix the problem. If an
automatic fix is available for a problem, the code fragment is highlighted and the
message includes a Fix button.

lengthofline file in the Editor showing a warning message with a fix button, indicating that only warnings and potential
improvements remain.

For some messages, MATLAB suggests an automatic fix that you can apply to fix the problem. If an
automatic fix is available for a problem, the code fragment is highlighted and the
message includes a Fix button.

lengthofline file in the Editor showing a warning message with a fix button

For example, on line 27 in lengthofline.m, place the mouse over
the underlined and highlighted code fragment prod. The displayed
message includes a Fix button.

If you know how to fix the problem, perhaps from prior experience, click the
Fix button or press Alt+Enter. If you
are unfamiliar with the problem, right-click the highlighted code. The first item in
the context menu shows the suggested fix. Select the item to apply the fix.

lengthofline file in the Editor showing the context menu. The first item in the menu is the suggested fix.

If multiple instances of a problem exist, MATLAB might offer to apply the suggested fix for all instances of the
problem. To apply the fix for all instances of a problem, right-click the
highlighted code and select Fix All (n)
Instances of This Issue
. This option is not available for all
suggested fixes.

After you modify the code to address all the messages or disable designated
messages, the message indicator becomes green. See the example file,
lengthofline2.m, with all messages addressed.

 lengthofline2.m Code

Analyze Files Using the Code Analyzer App

Since R2022b

You can create a report of Code Analyzer messages for all files in a folder using
the Code
Analyzer
app.

To open the app:

  • MATLAB Toolstrip: On the Apps tab, under
    MATLAB, click the app icon: Code Analyzer App Icon

If multiple instances of a problem exist, MATLAB might offer to apply the suggested fix for all instances of the
problem. To apply the fix for all instances of a problem, right-click the
highlighted code and select Fix All (n)
Instances of This Issue
. This option is not available for all
suggested fixes.

After you modify the code to address all the messages or disable designated
messages, the message indicator becomes green. See the example file,
lengthofline2.m, with all messages addressed.

 lengthofline2.m Code

Analyze Files Using the Code Analyzer App

Since R2022b

You can create a report of Code Analyzer messages for all files in a folder using
the Code
Analyzer
app.

To open the app:

  • MATLAB Toolstrip: On the Apps tab, under
    MATLAB, click the app icon: Code Analyzer App Icon.

  • MATLAB command prompt: Enter codeAnalyzer.

Code Analyzer app showing an overall summary of code issues and code health details

Identify and Store Issues in Files With codeIssues Object

Since R2022b

You can use codeIssues to programmatically find and store issues in code. The
codeIssues object stores issues found by the MATLAB Code Analyzer. The issues found in one or more specified files or
folders can be sorted and filtered, either programmatically on the command line or
interactively in the Code Analyzer app.

For example, you can generate a codeIssues object containing
the issues in a specified file:

issues = codeIssues("test.m")
issues = 

  codeIssues with properties:

                         Date: 18-Oct-2022 14:18:54
                      Release: "R2023a"
                        Files: "C:MyCodetest.m"
    CodeAnalyzerConfiguration: "active"
                       Issues: [3×10 table]
             SuppressedIssues: [0×11 table]


    Issues table preview

    Location    Severity    Fixability                                            Description                                             CheckID    LineStart    LineEnd    ColumnStart    ColumnEnd       FullFilename   
    ________    ________    __________    ____________________________________________________________________________________________    _______    _________    _______    ___________    _________    __________________

    "test.m"      info        manual      "Variable appears to change size on every loop iteration. Consider preallocating for speed."    AGROW          3           3            1             3        "C:MyCodetest.m"
    "test.m"      info        auto        "Add a semicolon after the statement to hide the output (in a script)."                         NOPTS          6           6            3             3        "C:MyCodetest.m"
    "test.m"      info        auto        "string('...') is not recommended. Use "..." instead."                                          STRQUOT        8           8            1            13        "C:MyCodetest.m"

Analyze Files Using the Code Issues tool in MATLAB Online

In MATLAB
Online™
, you can use the Code Issues tool to view error and warning messages
about your code. The Code Issues tool displays the coding problems found by the
MATLAB Code Analyzer as it automatically checks your code.

To open the Code Issues tool, go to the Editor or
Live Editor tab, and in the Analyze
section, click
Code Issues. By default, the Code Issues tool opens on the
right side of the desktop. To hide the Code Issues tool, click the Code Issues
icon in the sidebar.

Code Issues tool showing 0 errors and 13 warnings found in the lengthofline.m file. The MATLAB Online desktop right sidebar shows the Code Issues icon.

Identify and Store Issues in Files With codeIssues Object

Since R2022b

You can use codeIssues to programmatically find and store issues in code. The
codeIssues object stores issues found by the MATLAB Code Analyzer. The issues found in one or more specified files or
folders can be sorted and filtered, either programmatically on the command line or
interactively in the Code Analyzer app.

For example, you can generate a codeIssues object containing
the issues in a specified file:

issues = codeIssues("test.m")
issues = 

  codeIssues with properties:

                         Date: 18-Oct-2022 14:18:54
                      Release: "R2023a"
                        Files: "C:MyCodetest.m"
    CodeAnalyzerConfiguration: "active"
                       Issues: [3×10 table]
             SuppressedIssues: [0×11 table]


    Issues table preview

    Location    Severity    Fixability                                            Description                                             CheckID    LineStart    LineEnd    ColumnStart    ColumnEnd       FullFilename   
    ________    ________    __________    ____________________________________________________________________________________________    _______    _________    _______    ___________    _________    __________________

    "test.m"      info        manual      "Variable appears to change size on every loop iteration. Consider preallocating for speed."    AGROW          3           3            1             3        "C:MyCodetest.m"
    "test.m"      info        auto        "Add a semicolon after the statement to hide the output (in a script)."                         NOPTS          6           6            3             3        "C:MyCodetest.m"
    "test.m"      info        auto        "string('...') is not recommended. Use "..." instead."                                          STRQUOT        8           8            1            13        "C:MyCodetest.m"

Analyze Files Using the Code Issues tool in MATLAB Online

In MATLAB
Online™
, you can use the Code Issues tool to view error and warning messages
about your code. The Code Issues tool displays the coding problems found by the
MATLAB Code Analyzer as it automatically checks your code.

To open the Code Issues tool, go to the Editor or
Live Editor tab, and in the Analyze
section, click
Code Issues. By default, the Code Issues tool opens on the
right side of the desktop. To hide the Code Issues tool, click the Code Issues
icon in the sidebar.

Code Issues tool showing 0 errors and 13 warnings found in the lengthofline.m file. The MATLAB Online desktop right sidebar shows the Code Issues icon.

You can change what messages display in the Code Issues tool using the options at
the top of the tool:

  • Show messages for the current file or all open
    files
    — Use the drop-down list at the top-left of the
    Code Issues tool to select whether to show the errors and warnings for
    the current file or for all open files. For example, to show errors and
    warnings for all open files, in the drop-down list, select
    Open Files.

  • Show or hide errors and warnings
    Use the Errors button and Warnings button
    at the top-right of the Code Issues
    tool to show or hide errors and warnings. For example, to show only
    errors, click the Errors button on and the Warnings button
    off.

  • Filter messages by text — Use the
    search field below the drop-down list to filter the list of messages by
    text. For example, to display only messages that contain the word
    Variable, enter the word
    Variable in the search field.

Adjust Code Analyzer Message Indicators and Messages

You can specify which type of coding issues are underlined to best suit your
current development stage. For example, when first coding, you might prefer to
underline only errors, because warnings can be distracting. To change the
underlining preferences, on the Home tab, in the
Environment section, click
Preferences. Select > , and then select an Underlining option.

You also can adjust what messages you see when analyzing your code. Code analysis
does not provide perfect information about every situation. 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 a specific line, you can
suppress them. For example, the first message on line 48 of the sample file
lengthofline.m 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.

You can suppress (turn off) the indicators for warning and error messages in these
ways:

  • Suppress an instance of a message in the current file.

  • Suppress all instances of a message in the current file.

  • Suppress all instances of a message in all files.

You cannot suppress error messages such as syntax errors.

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, to suppress the message on line 48 in the sample file
lengthofline.m, right-click the first underline on line
48 and select > .

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 the
message disappear.

If a line contains two messages that you do not want to display, right-click
each underline separately and select the appropriate entry from the context
menu. The %#ok syntax expands. For example, suppressing both
messages for line 48 in the sample file lengthofline.m 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 suppressed message 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, to suppress all instances of the message on line 48
in the sample file lengthofline.m, right-click the first
underline on line 48 and select > .

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 a line contains two messages that you do not want to display anywhere in
the current file, right-click each underline separately and select the
appropriate entry from the context menu. The %#ok syntax
expands. For the example, suppressing both messages for line 48 in the sample
file lengthofline.m 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, to suppress all instances in all files of the message on line 48 in the
sample file lengthofline.m, right-click the first underline
on line 48 and select > . This option modifies the Code Analyzer preferences.

If you know which messages you want to suppress, you can disable them directly
using Code Analyzer preferences:

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

    Preferences.

  2. Select > .

  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 set options to enable or disable certain Code Analyzer messages, 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. The settings
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.

To save settings to a file:

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

    Preferences.

  2. Select > .

  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.

  2. Select > .

  3. Open the Active settings list and select
    .

  4. Choose from any of your settings files.

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

Enable custom checks and configure existing checks

Since R2023a

You can configure existing checks displayed in the MATLAB editor by the Code
Analyzer and add custom checks by placing a file named
codeAnalyzerConfiguration.json in a resources folder. The
configuration file is effective in the folder containing the resources folder and
any subfolders.

You can modify existing Code Analyzer checks, including whether the check is
enabled and its severity, message text, and parameters if the check has any, such as
to limit the number of input and output arguments for a function. You can also
create custom checks that trigger when specific functions are used. For more
information on configuring Code Analyzer checks, see Configure Code Analyzer.

Validate your codeAnalyzerConfiguration.json configuration file
for proper formatting by using the function matlab.codeanalysis.validateConfiguration.

Understand Code Containing Suppressed Messages

If you receive code that contains suppressed messages, you might want to review
the messages without having 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>.

  • The messages are cleared in the Code Analyzer preferences pane.

  • The messages are disabled by default.

To determine why messages are suppressed call codeIssues with the file as the input.

issues = codeIssues("myFile.m")

The output, issues, will have a property,
SuppressedIssues, contains a table listing all the
suppressed issues within the file. Review the message associated with each issue to
understand why it is suppressed/

Understand the Limitations of Code Analysis

Code analysis is a valuable tool, but it has some limitations:

  • Code analysis sometimes 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.

  • Code analysis sometimes produces messages that do not apply to your
    situation.

    Clicking the Details button to display
    additional information for a message can help you determine if the
    message applies to your situation. Error messages are almost always
    problems. However, many warnings are suggestions to look at something in
    the code that is unusual, 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 more information, see Adjust Code Analyzer Message Indicators and Messages.

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 code 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 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 this argument 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 can do various checks. For example, code
analysis 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 MATLAB 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. Changing this preference also
changes the setting in the Editor. Similarly, changing the setting in the Editor
changes this preference. However, if the Code Analyzer preferences are open when you
modify the setting in the Editor, the changes are not reflected in the Preferences
window. Whether you change the setting in the Editor or the Preferences window, the
change applies to the Editor and the Code Analyzer Report.

To enable MATLAB
Compiler™
deployment messages:

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

    Preferences.

  2. Select > .

  3. Click the down arrow next to the search field, and then select > .

  4. Click the Enable Category button to the right of
    the MATLAB Compiler (Deployment) Messages category
    title.

  5. Clear individual messages that you do not want to display for your
    code.

  6. Decide if you want to save these settings, so you can reuse them the 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.

See Also

Code
Analyzer
| codeIssues | checkcode

Related Topics

  • MATLAB Code Analyzer Report
  • Code Analyzer Preferences
  • Configure Code Analyzer
  • Index of Code Analyzer Checks

External Websites

  • Programming: Structuring Code (MathWorks Teaching Resources)

Понравилась статья? Поделить с друзьями:
  • Как исправить ошибки в маникюре
  • Как исправить ошибки в маникюре
  • Как исправить ошибки в русском предложении онлайн
  • Как исправить ошибки в рисунке
  • Как исправить ошибки в речи детей