Main Content
Throw error and display message
Syntax
Description
example
error( throws an error andmsg)
displays an error message.
error(msg,A1,...,An)
displays an error message that contains formatting conversion characters, such
as those used with the MATLAB®
sprintf function. Each
conversion character in msg is converted to one of the values
A1,...,An.
error(errID,___)
includes an error identifier on the exception. The identifier enables you to
distinguish errors and to control what happens when MATLAB encounters the errors. You can include any of the input arguments
in the previous syntaxes.
example
error( throws an errorerrorStruct)
using the fields in a scalar structure.
example
error(correction,___)
provides a suggested fix for the exception. You can include any of the input
arguments in the previous syntaxes.
Examples
collapse all
Throw Error
msg = 'Error occurred.';
error(msg)
Throw Error with Formatted Message
Throw a formatted error message with a line break. You must specify more
than one input argument with error if you want
MATLAB to convert special characters (such as n)
in the error message. Include information about the class of variable
n in the error message.
n = 7; if ~ischar(n) error('Error. nInput must be a char, not a %s.',class(n)) end
Error.
Input must be a char, not a double.
If you only use one input argument with error, then
MATLAB does not convert n to a line break.
if ~ischar(n) error('Error. nInput must be a char.') end
Error. nInput must be a char.
Throw an error with an identifier.
if ~ischar(n) error('MyComponent:incorrectType',... 'Error. nInput must be a char, not a %s.',class(n)) end
Error.
Input must be a char, not a double.
Use the MException.last to view the last uncaught
exception.
exception = MException.last
exception =
MException with properties:
identifier: 'MyComponent:incorrectType'
message: 'Error.
Input must be a char, not a double.'
cause: {0x1 cell}
stack: [0x1 struct]
Throw Error Using Structure
Create structure with message and identifier fields. To keep the example
simple, do not use the stack field.
errorStruct.message = 'Data file not found.'; errorStruct.identifier = 'MyFunction:fileNotFound';
errorStruct =
message: 'Data file not found.'
identifier: 'MyFunction:fileNotFound'
Throw the error.
Throw Error with Suggested Fix
Create a function hello that requires one input
argument. Add a suggested input argument "world" to the
error message.
function hello(audience) if nargin < 1 aac = matlab.lang.correction.AppendArgumentsCorrection('"world"'); error(aac, 'MATLAB:notEnoughInputs', 'Not enough input arguments.') end fprintf("Hello, %s!n", audience) end
Call the function without an argument.
Error using hello
Not enough input arguments.
Did you mean:
>> hello("world")
Input Arguments
collapse all
msg — Information about error
text scalar containing format specification
Information about the error, specified as a text scalar containing format
specification. This message displays as the error message. To format the
message, use escape sequences, such as t or
n. You also can use any format specifiers supported
by the sprintf function, such as %s or
%d. Specify values for the conversion specifiers via
the A1,...,An input arguments. For more information, see
Formatting Text.
Note
You must specify more than one input argument with
error if you want MATLAB to convert special characters (such as
t, n, %s,
and %d) in the error message.
Example: 'File not found.'
errID — Identifier for error
text scalar containing component and mnemonic fields
Identifier for the error, specified as a text scalar containing component
and mnemonic fields. Use the error identifier to help identify the source of
the error or to control a selected subset of the errors in your program.
The error identifier includes one or more component
fields and a mnemonic field. Fields must be separated
with colon. For example, an error identifier with a component field
component and a mnemonic field
mnemonic is specified as
'component:mnemonic'. The component and mnemonic
fields must each begin with a letter. The remaining characters can be
alphanumerics (A–Z, a–z, 0–9) and underscores. No white-space characters can
appear anywhere in errID. For more information, see
MException.
Example: 'MATLAB:singularMatrix'
Example: 'MATLAB:narginchk:notEnoughInputs'
A1,...,An — Values
character vector | string scalar | numeric scalar
Values that replace the conversion specifiers in msg,
specified as a character vector, string scalar, or numeric scalar.
errorStruct — Error reporting information
scalar structure
Error reporting information, specified as a scalar structure. The
structure must contain at least one of these fields.
message |
Error message. For more information, see |
identifier |
Error identifier. For more information, see |
stack |
Stack field for the error. When |
correction — Suggested fix for this exception
matlab.lang.correction.AppendArgumentsCorrection
object | matlab.lang.correction.ConvertToFunctionNotationCorrection
object | matlab.lang.correction.ReplaceIdentifierCorrection
object
Tips
-
When you throw an error, MATLAB captures information about it and stores it in a data structure
that is an object of theMExceptionclass. You can access
information in the exception object by usingtry/catch. Or,
if your program terminates because of an exception and returns control to the
Command Prompt, you can useMException.last. -
MATLAB does not cease execution of a program if an error occurs within a
tryblock. In this case, MATLAB passes control to thecatchblock. -
If all inputs to
errorare empty, MATLAB does not throw an error.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
Has no effect
in standalone code even when run-time error detection is enabled. See Generate Standalone C/C++ Code That Detects and Reports Run-Time Errors (MATLAB Coder).
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.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Usage notes and limitations:
-
This function accepts GPU arrays, but does not run on a GPU.
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Version History
Introduced before R2006a
- Trial Software
- Trial Software
- Product Updates
- Product Updates
error
Выдать ошибку и отобразить сообщение
Синтаксис
Описание
пример
error( выдает ошибку и отображает сообщение об ошибке.msg)
error( отображает сообщение об ошибке, которое содержит символы преобразования форматирования, такие как используемые с MATLAB®msg,A1,...,An)
sprintf функция. Каждый символ преобразования в msg преобразован в одно из значений A1,...,An.
error( включает ошибочный идентификатор на исключении. Идентификатор позволяет вам отличить ошибки и управлять тем, что происходит, когда MATLAB сталкивается с ошибками. Можно включать любой из входных параметров в предыдущих синтаксисах.errID,___)
пример
error( выдает ошибку поля в скалярной структуре.errorStruct)
пример
error( обеспечивает предложенное исправление для исключения. Можно включать любой из входных параметров в предыдущих синтаксисах. correction,___)
Примеры
свернуть все
Бросок ошибки
msg = 'Error occurred.';
error(msg)
Бросок ошибки с форматированным сообщением
Выдайте отформатированное сообщение об ошибке с разрывом строки. Необходимо задать больше чем один входной параметр с error если вы хотите, чтобы MATLAB преобразовал специальные символы (такие как n) в сообщении об ошибке. Включайте информацию о классе переменной n в сообщении об ошибке.
n = 7; if ~ischar(n) error('Error. nInput must be a char, not a %s.',class(n)) end
Error.
Input must be a char, not a double.
Если вы только используете один входной параметр с error, затем MATLAB не преобразует n к разрыву строки.
if ~ischar(n) error('Error. nInput must be a char.') end
Error. nInput must be a char.
Выдайте ошибку с идентификатором.
if ~ischar(n) error('MyComponent:incorrectType',... 'Error. nInput must be a char, not a %s.',class(n)) end
Error.
Input must be a char, not a double.
Используйте MException.last просмотреть последнее неперехваченное исключение.
exception = MException.last
exception =
MException with properties:
identifier: 'MyComponent:incorrectType'
message: 'Error.
Input must be a char, not a double.'
cause: {0x1 cell}
stack: [0x1 struct]
Бросок структуры ошибки
Создайте структуру с полями идентификатора и сообщением. Чтобы сохранить пример простым, не используйте поле стека.
errorStruct.message = 'Data file not found.'; errorStruct.identifier = 'MyFunction:fileNotFound';
errorStruct =
message: 'Data file not found.'
identifier: 'MyFunction:fileNotFound'
Выдайте ошибку.
Выдайте ошибку с предложенным исправлением
Создайте функциональный hello это требует одного входного параметра. Добавьте предложенный входной параметр "world" к сообщению об ошибке.
function hello(audience) if nargin < 1 aac = matlab.lang.correction.AppendArgumentsCorrection('"world"'); error(aac, 'MATLAB:notEnoughInputs', 'Not enough input arguments.') end fprintf("Hello, %s!n", audience) end
Вызовите функцию без аргумента.
Error using hello (line 4)
Not enough input arguments.
Did you mean:
>> hello("world")
Входные параметры
свернуть все
msg — Информация об ошибке
вектор символов | строковый скаляр
Информация об ошибке в виде вектора символов или строкового скаляра. Это индикаторы сообщения как сообщение об ошибке. Чтобы отформатировать сообщение, используйте escape-последовательности, такие как t или n. Также можно использовать любые спецификаторы формата, поддержанные sprintf функция, такая как %s или %d. Задайте значения для спецификаторов преобразования через A1,...,An входные параметры. Для получения дополнительной информации см. Форматирующий текст.
Примечание
Необходимо задать больше чем один входной параметр с error если вы хотите, чтобы MATLAB преобразовал специальные символы (такие как tNS, и %d) в сообщении об ошибке.
Пример: 'File not found.'
errID — Идентификатор для ошибки
вектор символов | строковый скаляр
Идентификатор для ошибки в виде вектора символов или строкового скаляра. Используйте ошибочный идентификатор, чтобы помочь идентифицировать источник ошибки или управлять выбранным подмножеством ошибок в вашей программе.
Ошибочный идентификатор включает одно или несколько полей компонента и мнемоническое поле. Поля должны быть разделены двоеточием. Например, ошибочный идентификатор с полем component компонента и мнемоническое поле mnemonic задан как 'component:mnemonic'. И мнемонические поля компонента должны каждый начаться с буквы. Оставшиеся символы могут быть буквенно-цифровым индикатором (A–Z, a–z, 0–9) и символы нижнего подчеркивания. Никакие пробельные символы не могут появиться нигде в errID. Для получения дополнительной информации смотрите MException.
Пример: 'MATLAB:singularMatrix'
Пример: 'MATLAB:narginchk:notEnoughInputs'
A1,...,An Значения
вектор символов | строковый скаляр | числовой скаляр
Значения, которые заменяют спецификаторы преобразования в msgВ виде вектора символов, строкового скаляра или числового скаляра.
errorStruct — Информация о сообщении об ошибке
скалярная структура
Информация о сообщении об ошибке в виде скалярной структуры. Структура должна содержать по крайней мере одно из этих полей.
message |
Сообщение об ошибке. Для получения дополнительной информации смотрите |
identifier |
Ошибочный идентификатор. Для получения дополнительной информации смотрите |
stack |
Поле стека для ошибки. Когда |
correction — Предложенное исправление для этого исключения
matlab.lang.correction.AppendArgumentsCorrection возразите | matlab.lang.correction.ConvertToFunctionNotationCorrection возразите | matlab.lang.correction.ReplaceIdentifierCorrection объект
Советы
-
Когда вы выдаете ошибку, MATLAB получает информацию об этом и хранит ее в структуре данных, которая является объектом
MExceptionкласс. Можно получить доступ к информации в объекте исключения при помощиtry/catch. Или, если ваша программа завершает работу из-за исключения и возвращает управление в Командную строку, можно использоватьMException.last. -
MATLAB не прекращает осуществление программы, если ошибка происходит в
tryблок. В этом случае MATLAB передает управление кcatchблок. -
Если все входные параметры к
errorпусты, MATLAB не выдает ошибку.
Расширенные возможности
Генерация кода C/C++
Генерация кода C и C++ с помощью MATLAB® Coder™.
Указания и ограничения по применению:
Не оказывает влияния в автономном коде, даже когда обнаружение ошибки времени выполнения включено. Смотрите Генерируют Автономный Код C/C++, Который Обнаруживает и Ошибки времени выполнения Отчетов (MATLAB Coder).
Основанная на потоке среда
Запустите код в фоновом режиме с помощью MATLAB® backgroundPool или ускорьте код с Parallel Computing Toolbox™ ThreadPool.
Эта функция полностью поддерживает основанные на потоке среды. Для получения дополнительной информации смотрите функции MATLAB Запуска в Основанной на потоке Среде.
Массивы графического процессора
Ускорьте код путем работы графического процессора (GPU) с помощью Parallel Computing Toolbox™.
Указания и ограничения по применению:
-
Эта функция принимает массивы графического процессора, но не работает на графическом процессоре.
Для получения дополнительной информации смотрите функции MATLAB Запуска на графическом процессоре (Parallel Computing Toolbox).
Представлено до R2006a
assert
Throw error if condition false
Syntax
Description
example
assert( throwscond)
an error if cond is false.
example
assert( throwscond,msg)
an error and displays the error message, msg, if cond is
false.
assert( displayscond,msg,A1,...,An)
an error message that contains formatting conversion characters, such
as those used with the MATLAB® sprintf function,
if cond is false. Each conversion character in msg is
converted to one of the values A1,...,An.
example
assert(cond,errID,msg)
throws an error, displays the error message, msg, and
includes an error identifier on the exception, if cond is
false. The identifier enables you to distinguish errors and to control what
happens when MATLAB encounters the errors.
assert(cond,errID,msg,A1,...,An)
includes an error identifier on the exception and displays a formatted error
message.
Examples
collapse all
Value in Expected Range
Assert that the value, x, is greater
than a specified minimum value.
minVal = 7; x = 26; assert(minVal < x)
The expression evaluates as true, and the assertion passes.
Assert that the value of x is between
the specified minimum and maximum values.
maxVal = 13; assert((minVal < x) && (x < maxVal))
Error using assert Assertion failed.
The expression evaluates as false. The assertion fails and MATLAB throws
an error.
Expected Data Type
Assert that the product of two numbers is a
double-precision number.
a = 13; b = single(42); c = a*b; assert(isa(c,'double'),'Product is not type double.')
Error using assert Product is not type double.
Enhance the error message to display the data type of c.
assert(isa(c,'double'),'Product is type %s, not double.',class(c))
Error using assert Product is type single, not double.
Expected Code Conditions
Use the assert function to test for
conditions that should not happen in normal code execution. If the
coefficients are numeric, the computed roots should be numeric. A
quadratic equation using the specified coefficients and computed roots
should be zero.
function x = quadraticSolver(C) validateattributes(C,{'numeric'},{'size',[1 3]}) a = C(1); b = C(2); c = C(3); x(1) = (-b+sqrt(b^2-4*a*c))/(2*a); x(2) = (-b-sqrt(b^2-4*a*c))/(2*a); assert(isnumeric(x),'quadraticSolver:nonnumericRoots',... 'Computed roots are not numeric') y1 = a*x(1)^2+b*x(1)+c; y2 = a*x(2)^2+b*x(2)+c; assert(y1 == 0,'quadraticSolver:root1Error','Error in first root') assert(isequal(y2,0),'quadraticSolver:root2Error','Error in second root') end
Input Arguments
collapse all
cond — Condition to assert
MATLAB expression
Condition to assert, specified as a valid MATLAB expression. This expression must be logical or convertible to
a logical. If cond is false, the
assert function throws an error.
cond can include relational operators (such as
< or ==) and logical operators
(such as &&, ||, or
~). Use the logical operators and
and or to create compound expressions. MATLAB evaluates compound expressions from left to right, adhering to
operator precedence rules.
Example: a<0
Example: exist('myfunction.m','file')
msg — Information about assertion failure
character vector | string scalar
Information about the assertion failure, specified as a character vector or string scalar. This message displays as the error message. To format the message, use escape sequences, such as t or n. You also can use any format specifiers supported by the sprintf function, such as %s or %d. Specify values for the conversion specifiers via the A1,...,An input arguments. For more information, see Formatting Text.
Note
You must specify more than one input argument with assert if
you want MATLAB to convert special characters (such as t, n, %s,
and %d) in the error message.
Example: 'Assertion condition failed.'
A1,...,An — Numeric, character, or string arrays
arrays
Numeric, character, or string arrays. This input argument provides the values that correspond to and replace the conversion specifiers in msg.
errID — Identifier for assertion failure
character vector | string scalar
Identifier for the assertion failure, specified as a character vector or
string scalar. Use the identifier to help identify the source of the error
or to control a selected subset of the errors in your program.
The error identifier includes one or more component
fields and a mnemonic field. Fields must be separated
with colon. For example, an error identifier with a component field
component and a mnemonic field
mnemonic is specified as
'component:mnemonic'. The component and mnemonic
fields must each begin with a letter. The remaining characters can be
alphanumerics (A–Z, a–z, 0–9) and underscores. No white-space characters can
appear anywhere in errID. For more information, see
MException.
Example: 'MATLAB:singularMatrix'
Example: 'MATLAB:narginchk:notEnoughInputs'
Tips
-
When you issue an error, MATLAB captures information
about it and stores it in a data structure that is an object of theMExceptionclass.
You can access information in the exception object by usingtry/catch.
Or, if your program terminates because of an exception and returns
control to the Command Prompt, you can useMException.last. -
If an assertion failure occurs within a
tryblock, MATLAB does
not cease execution of the program. In this case, MATLAB passes
control to thecatchblock.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
-
Generates specified error messages at compile time
only if all input arguments are constants
or depend on constants. Otherwise, generates specified error messages
at run time. -
If called with more than 1 argument, has no
effect in standalone code even when
run-time error detection is enabled. See Generate Standalone C/C++ Code That Detects and Reports Run-Time Errors (MATLAB Coder). -
To use the
assertfunction to specify properties
of primary function inputs or set preconditions on primary function
inputs, see Rules for Using assert Function (MATLAB Coder).
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.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Usage notes and limitations:
-
This function accepts GPU arrays, but does not run on a GPU.
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Version History
Introduced in R2007a
expand all
R2022a: Output displays which assertion threw an error and the location in the
code
When an assertion fails, the error thrown includes the specific assertion that
failed and the location in the code.
assert
Throw error if condition false
Syntax
Description
example
assert( throwscond)
an error if cond is false.
example
assert( throwscond,msg)
an error and displays the error message, msg, if cond is
false.
assert( displayscond,msg,A1,...,An)
an error message that contains formatting conversion characters, such
as those used with the MATLAB® sprintf function,
if cond is false. Each conversion character in msg is
converted to one of the values A1,...,An.
example
assert(cond,errID,msg)
throws an error, displays the error message, msg, and
includes an error identifier on the exception, if cond is
false. The identifier enables you to distinguish errors and to control what
happens when MATLAB encounters the errors.
assert(cond,errID,msg,A1,...,An)
includes an error identifier on the exception and displays a formatted error
message.
Examples
collapse all
Value in Expected Range
Assert that the value, x, is greater
than a specified minimum value.
minVal = 7; x = 26; assert(minVal < x)
The expression evaluates as true, and the assertion passes.
Assert that the value of x is between
the specified minimum and maximum values.
maxVal = 13; assert((minVal < x) && (x < maxVal))
Error using assert Assertion failed.
The expression evaluates as false. The assertion fails and MATLAB throws
an error.
Expected Data Type
Assert that the product of two numbers is a
double-precision number.
a = 13; b = single(42); c = a*b; assert(isa(c,'double'),'Product is not type double.')
Error using assert Product is not type double.
Enhance the error message to display the data type of c.
assert(isa(c,'double'),'Product is type %s, not double.',class(c))
Error using assert Product is type single, not double.
Expected Code Conditions
Use the assert function to test for
conditions that should not happen in normal code execution. If the
coefficients are numeric, the computed roots should be numeric. A
quadratic equation using the specified coefficients and computed roots
should be zero.
function x = quadraticSolver(C) validateattributes(C,{'numeric'},{'size',[1 3]}) a = C(1); b = C(2); c = C(3); x(1) = (-b+sqrt(b^2-4*a*c))/(2*a); x(2) = (-b-sqrt(b^2-4*a*c))/(2*a); assert(isnumeric(x),'quadraticSolver:nonnumericRoots',... 'Computed roots are not numeric') y1 = a*x(1)^2+b*x(1)+c; y2 = a*x(2)^2+b*x(2)+c; assert(y1 == 0,'quadraticSolver:root1Error','Error in first root') assert(isequal(y2,0),'quadraticSolver:root2Error','Error in second root') end
Input Arguments
collapse all
cond — Condition to assert
MATLAB expression
Condition to assert, specified as a valid MATLAB expression. This expression must be logical or convertible to
a logical. If cond is false, the
assert function throws an error.
cond can include relational operators (such as
< or ==) and logical operators
(such as &&, ||, or
~). Use the logical operators and
and or to create compound expressions. MATLAB evaluates compound expressions from left to right, adhering to
operator precedence rules.
Example: a<0
Example: exist('myfunction.m','file')
msg — Information about assertion failure
character vector | string scalar
Information about the assertion failure, specified as a character vector or string scalar. This message displays as the error message. To format the message, use escape sequences, such as t or n. You also can use any format specifiers supported by the sprintf function, such as %s or %d. Specify values for the conversion specifiers via the A1,...,An input arguments. For more information, see Formatting Text.
Note
You must specify more than one input argument with assert if
you want MATLAB to convert special characters (such as t, n, %s,
and %d) in the error message.
Example: 'Assertion condition failed.'
A1,...,An — Numeric, character, or string arrays
arrays
Numeric, character, or string arrays. This input argument provides the values that correspond to and replace the conversion specifiers in msg.
errID — Identifier for assertion failure
character vector | string scalar
Identifier for the assertion failure, specified as a character vector or
string scalar. Use the identifier to help identify the source of the error
or to control a selected subset of the errors in your program.
The error identifier includes one or more component
fields and a mnemonic field. Fields must be separated
with colon. For example, an error identifier with a component field
component and a mnemonic field
mnemonic is specified as
'component:mnemonic'. The component and mnemonic
fields must each begin with a letter. The remaining characters can be
alphanumerics (A–Z, a–z, 0–9) and underscores. No white-space characters can
appear anywhere in errID. For more information, see
MException.
Example: 'MATLAB:singularMatrix'
Example: 'MATLAB:narginchk:notEnoughInputs'
Tips
-
When you issue an error, MATLAB captures information
about it and stores it in a data structure that is an object of theMExceptionclass.
You can access information in the exception object by usingtry/catch.
Or, if your program terminates because of an exception and returns
control to the Command Prompt, you can useMException.last. -
If an assertion failure occurs within a
tryblock, MATLAB does
not cease execution of the program. In this case, MATLAB passes
control to thecatchblock.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
-
Generates specified error messages at compile time
only if all input arguments are constants
or depend on constants. Otherwise, generates specified error messages
at run time. -
If called with more than 1 argument, has no
effect in standalone code even when
run-time error detection is enabled. See Generate Standalone C/C++ Code That Detects and Reports Run-Time Errors (MATLAB Coder). -
To use the
assertfunction to specify properties
of primary function inputs or set preconditions on primary function
inputs, see Rules for Using assert Function (MATLAB Coder).
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.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Usage notes and limitations:
-
This function accepts GPU arrays, but does not run on a GPU.
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Version History
Introduced in R2007a
expand all
R2022a: Output displays which assertion threw an error and the location in the
code
When an assertion fails, the error thrown includes the specific assertion that
failed and the location in the code.
Сообщения об ошибках и исправление ошибок
Важное значение
при диалоге с системой MATLAB имеет
диагностика
ошибок. Вряд
ли есть пользователь, помнящий точное
написание тысяч операторов и функций,
входящих в систему MATLAB и в пакеты
прикладных программ. Поэтому никто не
застрахован от ошибочного написания
математических выражений или команд.
MATLAB диагностирует вводимые команды и
выражения и выдает соответствующие
сообщения об ошибках или предупреждения.
Пример вывода сообщения об ошибке
(деление на 0) только что приводился.
Рассмотрим еще
ряд примеров.
Введем, к примеру,
ошибочное выражение » sqr(2)
и нажмем клавишу
ENTER. Система сообщит об ошибке:
???
Undefined function or variable ‘sqr’.
Это сообщение
говорит о том, что не определена переменная
или функция, и указывает, какая именно
— sqr. В данном случае, разумеется, можно
просто набрать правильное выражение.
Однако в случае громоздкого выражения
лучше воспользоваться редактором. Для
этого достаточно нажать клавишу вниз
для
перелистывания предыдущих строк. В
результате в строке ввода появится
выражение » sqr(2)
с курсором в его конце.
В версии MATLAB 6 можно теперь нажать клавишу
Tab. Система введет подсказку, анализируя
уже введенные символы. Если вариантов
несколько, клавишу Tab придется нажать
еще раз. Из предложенных системой трех
операторов выбираем sqrt. Теперь с помощью
клавиши вниз вновь выбираем нужную
строку и, пользуясь клавишей влево,
устанавливаем курсор после буквы r.
Теперь нажмем клавишу вверх, а затем
клавишу ENTER. Выражение примет следующий
вид:
»
sqrt(2)
ans=
1.4142
В системе MATLAB
внешние определения используются точно
так же, как и встроенные функции и
операторы. Никаких дополнительных
указаний на их применение делать не
надо. Достаточно лишь позаботиться о
том, чтобы используемые определения
действительно существовали в виде
файлов с расширением .m. Впрочем, если
вы забудете об этом или введете имя
несуществующего определения, то система
отреагирует на это звуковым сигналом
(звонком) и выводом сообщения об ошибке:
»
hsin(1)
???
Undefined function or variable ‘hsin’.
»
sinh(1)
ans=
1.1752
В этом примере мы
забыли, какое имя имеет внешняя функция,
вычисляющая гиперболический синус.
Система подсказала, что функция или
переменная с именем hsin не определена
ни как внутренняя, ни как m-функция.
Зато далее мы
видим, что функция с именем sinh есть в
составе функций системы MATLAB — она задана
в виде М-функции.
Между тем в последнем
примере мы не давали системе никаких
указаний на то, что следует искать именно
внешнюю функцию. И это вычисление прошло
так же просто, как вычисление встроенной
функции, такой как sin.
При этом вычисления
происходят следующим образом: вначале
система быстро определяет, имеется ли
введенное слово среди служебных слов
системы. Если да, то нужные вычисления
выполняются сразу, если нет, система
ищет m-файл с соответствующим именем на
диске. Если файла нет, то выдается
сообщение об ошибке, и вычисления
останавливаются. Если же файл найден,
он загружается с жесткого диска в память
машины и исполняется.
Иногда в ходе
вывода результатов вычислений появляется
сокращение NaN (от слов Not a Number — не число).
Оно обозначает неопределенность,
например вида 0/0 или Inf/Inf, где Inf —
системная переменная со значением
машинной бесконечности. Могут появляться
и различные предупреждения об ошибках
(на английском языке). Например, при
делении на 0 конечного/ числа появляется
предупреждение «Warning: Devide by Zero.» («Внимание:
Деление на ноль»).
Вообще говоря, в
MATLAB надо отличать предупреждение
об ошибке
от сообщения
о ней.
Предупреждения
(обычно после
слова Warning) не останавливают вычисления
и лишь предупреждают пользователя о
том, что диагностируемая ошибка способна
повлиять на ход вычислений. Сообщение
об ошибке
(после знаков ???) останавливает вычисления.
Соседние файлы в папке Matlab
- #
- #
20.02.201635.74 Mб80Инженерные расчеты в Mathcad Макаров 2005.djvu
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 file into your current folder and then open it
in the Editor.
copyfile(fullfile(matlabroot,'help','techdoc','matlab_env','examples','lengthofline.m'))
fileattrib('lengthofline.m','+w');
edit('lengthofline.m')
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 |
|---|---|
|
File contains syntax errors or other significant |
|
|
File contains warnings or opportunities for improvement, |
|
|
File contains no errors, warnings, or opportunities for |
For example, in lengthofline.m, the message indicator is
, meaning that the file contains at least one
error.

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.

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.

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.

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
to
, 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.

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. 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.

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. The example file with all messages
addressed has been saved as lengthofline2.m. For example, to open
the corrected version of the sample file lengthofline.m, use this
command:
open(fullfile(matlabroot,'help','techdoc',...
'matlab_env', 'examples','lengthofline2.m'))
Create a Code Analyzer Message Report
You can create a report of Code Analyzer messages for all files in a
folder.
To create a report for all files in a folder:
-
In the Current Folder browser, click the
button. -
Select > .
-
Modify your files based on the messages in the report.
-
Save the modified files.
-
Rerun the report to see if your changes addressed the issues noted in the
messages.
To create a report for an individual MATLAB code file, use the mlintrpt function. For example, to
create a report for the sample file lengthofline.m, enter
mlintrpt('lengthofline.m') in the Command Window.
For more information, see MATLAB Code Analyzer Report.
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. Adding a
statement with semicolon to suppress output (in functions)
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 Code Analyzer
with semicolon to suppress output (in functions)
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 Code
statement with semicolon to suppress output (in functions)
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 Code Analyzer message in the current file. All
functions)
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 Code Analyzer message in the current file,
output (in functions)
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:
-
On the Home tab, in the
Environment section, click

Preferences. -
Select > .
-
Search the messages to find the ones you want to
suppress. -
Clear the check box associated with each message you want to
suppress in all files. -
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:
-
On the Home tab, in the
Environment section, click

Preferences. -
Select > .
-
Enable or disable specific messages or categories of messages.
-
Click the Actions button
, select Save As,
and then save the settings to atxtfile. -
Click OK.
You can reuse these settings for any MATLAB file, or provide the settings file to another user. To use the
saved settings:
-
On the Home tab, in the
Environment section, click

Preferences. -
Select > .
-
Open the Active settings list and select
. -
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.
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:
-
Search the file for the
%#okdirective and create a
list of all the message IDs associated with that directive. -
On the Home tab, in the
Environment section, click

Preferences. -
Select > .
-
In the search field, type
msgid:followed by one of
the message IDs from 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. The
results can provide insight into why the message is suppressed or
disabled.
-
Click the Clear search button
to clear the search field, and then
repeat step 4 for each message ID from step 1. -
To display messages that are disabled by default and disabled in the
Preferences window, click the down arrow to the right of the search
field. Then, select . -
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 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. Code
variable or a function, and assumes it is a function
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
loadfunction, specify the variable
name explicitly in theloadcommand 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:
-
On the Home tab, in the
Environment section, click

Preferences. -
Select > .
-
Click the down arrow next to the search field, and then select > .
-
Click the Enable Category button to the right of
the MATLAB Compiler (Deployment) Messages category
title. -
Clear individual messages that you do not want to display for your
code. -
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
mlintrpt | checkcode
Related Topics
- MATLAB Code Analyzer Report
- Code Analyzer Preferences