Матлаб вывод сообщения об ошибке

Main Content

Throw error and display message

Syntax

Description

example

error(msg) throws an error and
displays an error message.

error(msg,A)
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
A.

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(errorStruct) throws an error
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

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

errIDIdentifier 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'

AReplacement value
character vector | string scalar | numeric scalar

Value that replace the conversion specifiers in msg,
specified as a character vector, string scalar, or numeric scalar.

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

identifier

Error identifier. For more information, see
errID.

stack

Stack field for the error. When
errorStruct includes a
stack field,
error uses it to set the stack
field of the error. When you specify
stack, use the absolute file name
and the entire sequence of functions that nests the
function in the stack frame. This character vector is
the same as the one returned by
dbstack('-completenames').

correctionSuggested 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 the MException class. You can access
    information in the exception object by using try/catch. Or,
    if your program terminates because of an exception and returns control to the
    Command Prompt, you can use MException.last.

  • MATLAB does not cease execution of a program if an error occurs within a
    try block. In this case, MATLAB passes control to the catch block.

  • If all inputs to error are 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

error

Выдать ошибку и отобразить сообщение

Синтаксис

Описание

пример

error(msg) выдает ошибку и отображает сообщение об ошибке.

error(msg,A1,...,An) отображает сообщение об ошибке, которое содержит символы преобразования форматирования, такие как используемые с MATLAB®
sprintf функция. Каждый символ преобразования в msg преобразован в одно из значений A1,...,An.

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

пример

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

Сообщение об ошибке. Для получения дополнительной информации смотрите msg.

identifier

Ошибочный идентификатор. Для получения дополнительной информации смотрите errID.

stack

Поле стека для ошибки. Когда errorStruct включает stack поле , error использование это, чтобы установить поле стека ошибки. Когда вы задаете stack, используйте абсолютное имя файла и целую последовательность функций, которая вкладывает функцию в стековом фрейме. Этот вектор символов совпадает с тем, возвращенным dbstack('-completenames').

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

Сообщения об ошибках и исправление ошибок

Важное значение
при диалоге с системой 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

Main Content

Throw error and display message

Syntax

Description

example

error(msg) throws an error and
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(errorStruct) throws an error
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

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

errIDIdentifier 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,...,AnValues
character vector | string scalar | numeric scalar

Values that replace the conversion specifiers in msg,
specified as a character vector, string scalar, or numeric scalar.

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

identifier

Error identifier. For more information, see
errID.

stack

Stack field for the error. When
errorStruct includes a
stack field,
error uses it to set the stack
field of the error. When you specify
stack, use the absolute file name
and the entire sequence of functions that nests the
function in the stack frame. This character vector is
the same as the one returned by
dbstack('-completenames').

correctionSuggested 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 the MException class. You can access
    information in the exception object by using try/catch. Or,
    if your program terminates because of an exception and returns control to the
    Command Prompt, you can use MException.last.

  • MATLAB does not cease execution of a program if an error occurs within a
    try block. In this case, MATLAB passes control to the catch block.

  • If all inputs to error are 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(msg,A1,...,An) отображает сообщение об ошибке, которое содержит символы преобразования форматирования, такие как используемые с MATLAB®
sprintf функция. Каждый символ преобразования в msg преобразован в одно из значений A1,...,An.

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

пример

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

Сообщение об ошибке. Для получения дополнительной информации смотрите msg.

identifier

Ошибочный идентификатор. Для получения дополнительной информации смотрите errID.

stack

Поле стека для ошибки. Когда errorStruct включает stack поле , error использование это, чтобы установить поле стека ошибки. Когда вы задаете stack, используйте абсолютное имя файла и целую последовательность функций, которая вкладывает функцию в стековом фрейме. Этот вектор символов совпадает с тем, возвращенным dbstack('-completenames').

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

Сообщения об ошибках и исправление ошибок

Важное значение
при диалоге с системой 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

I was doing a model for a slider-crank mechanism and I wanted to display an error for when the crank’s length exceeds that of the slider arm. With the crank’s length as r2 and the slider’s as r3, my code went like this:

if r3=<r2
    error('The crank's length cannot exceed that of the slider')
end

I get the error:

???     error('The crank's length cannot exceed that of the slider')
                         |
Error: Unexpected MATLAB expression.

can someone tell me what I’m doing wrong and how to fix it please?

Amro's user avatar

Amro

123k25 gold badges241 silver badges453 bronze badges

asked Dec 13, 2009 at 19:17

Ahmed's user avatar

When you want to use the ' character in a string, you have to precede it with another ' (note the example in the documentation):

if (r3 <= r2)
  error('The crank''s length cannot exceed that of the slider');
end

Also, note the change I made from =< to <=.

answered Dec 13, 2009 at 19:23

gnovice's user avatar

gnovicegnovice

125k15 gold badges256 silver badges358 bronze badges

1

You can print to the error handle as well:

fprintf(2,'The crank''s length cannot exceed that of the slider');

answered Dec 13, 2009 at 19:25

Zaid's user avatar

ZaidZaid

36.4k15 gold badges84 silver badges153 bronze badges

1

I believe the comparison operator should be <= not the other way around, unless that was only a typo in your question

Also you should escape the ' character using ''

answered Dec 13, 2009 at 19:22

Amro's user avatar

AmroAmro

123k25 gold badges241 silver badges453 bronze badges

As far as I’ve seen there is little help out there to help people decipher MATLAB’s error messages. Most of the syntax errors are not difficult to fix once you know what is causing them so this is intended to be a guide to identifying and fixing errors in MATLAB code.

Warnings are also shown here as these often lead to errors later.

Arithmetic errors[edit | edit source]

Usually these are self-explanatory. As a reminder, here are some common functions that cannot be performed and what MATLAB returns (along with a warning for each one):

a/0 = Inf if a > 0, -Inf if a < 0, and NaN if a = 0.
log(0) = -Inf
MATLAB defines 0^0 to be 1.

NaN will very often result in errors or useless results unless measures are taken to avoid propagating them.

???Error using ==> minus
Matrix dimensions must agree.

So check the dimensions of all the terms in your expression. Often it is an indexing mistake that causes the terms to be of different size.
If you are using power function you might add a single dot after the parameter. i.e. y=x.^2 instead of y=x^2

Matrix multiplication requires the number of columns in the first matrix to equal the number of rows in the second. Otherwise, you get the message:

??? Error using ==> mtimes
Inner matrix dimensions must agree.

Note the difference between this error and the previous one. This error often occurs because of indexing issues OR because you meant to use componentwise multiplication but forgot the dot.

Attempting to take the inverse of a singular matrix will result in a warning and a matrix of Infs. It is wise to calculate the determinant before attempting to take the inverse or, better, to use a method that does not require you to take the inverse since its not numerically stable.

Attempting to take a power of a nonsquare matrix results in the error

??? Error using ==> mpower
Matrix must be square.

This is usually because you meant to use componentwise exponentiation and forgot the dot.

Array Indexing errors[edit | edit source]

Array indexing is a key component of MATLAB. One feature is that the names of variables and functions are case sensitive, and that one can alias builtin or user-written functions with variables of the same name. So, if you make an array called abs and you try to call the function abs(1), MATLAB will return the first value in the array abs instead of the value 1. MATLAB will not return an error for this as it is not possible to know for certain that the aliasing of the function wasn’t intentional. Hence, never ever name your variables the same as an existing MATLAB function. Unfortunately, there are so many supplied functions in the base product plus installed toolboxes, remembering all of them is impossible so use which proposedname if you have any doubt the name might be in use previously before defining a new array or function. Later versions of MATLAB with the command completion feature will show the short help information after the opening parenthesis or tab-completion options, using which will aid in avoiding such errors before they arise later in execution by not creating the alias.

Some things are rather obvious but take some practice in avoiding:

You cannot try to access part of an array that does not exist yet.

>> A = [1,3];
>> A(3)
??? Index exceeds matrix dimensions.

Unfortunately, MATLAB doesn’t tell you which variable you exceeded the dimensions on if there’s more than one so you’ll have to check that. This often occurs if, for example, you are using a loop to change which part of an array is accessed, but the loop doesn’t stop before you reach the end of the array. This also happens if you end up with an empty matrix as a result of some operation and then try to access an element inside it.

You cannot try to access a negative, complex, noninteger, or zero part of an array; if you do you get this message:

>> A(-1)
>> A(i)
>> A(1.5)
>> A(0)
??? Subscript indices must either be real positive integers or logicals.

Note that MATLAB arrays are 1-based, not 0-based and are fixed lower dimension, not variable. MATLAB may be able to tell you which index is not real or logical depending on context.

 >> y=3*A(-1)
Attempted to access A(-1); index must be a positive integer or logical. 

The latter being an expression is parsed differently and so has the actual array available in the error message.

Also note that if 0 were a logical 0 (false) then the statement A(0) would not be an indexing error but a logical subscripting expression. In this case the return would be the empty [] array as there are no subscripts matching false in the defined set of [1 2] as A has been defined above. A more useful expression would be something like

>> A(A==3)

Attempting to use non-standard MATLAB syntax in your indexing will often result in the error:

>> A(2::, 2)
??? A(2::, 2)
        |
Error: Unexpected MATLAB operator.

The above could be an example of someone trying to access all rows of A after the first one and the second column, in which case you should use the «end» syntax, as in:

>> A(2:end, 2)
ans = 3

Assignment errors[edit | edit source]

Ah, assignment, that is using the = sign to give a variable, or certain elements of an array, a particular value.

Let’s start with a classic mistake:

>> a = 2;
>> if a = 3
??? if a = 3
         |
Error: The expression to the left of the equals sign is not a valid target for an assignment.

This error occurs because you meant to see if «a» equaled 3, but instead you told MATLAB to assign «a» a value of 3. You cannot do that on the same line that the if/while statement is on. The correct syntax is

>> if a == 3
>> end

This creates no errors (and you can put anything inside the conditional you want).

You cannot have a normal array with two different classes of data inside it. For example,

>> A = @(T) (1+T)
A = 
   @(T) (1+T)
>> A(2) = 3
??? Conversion to function_handle from double is not possible.

For such a purpose you should use cell arrays or struct arrays.

Here’s the tricky one. Take a look at the following code:

>> A = [1,2,3;4,5,6;7,8,9];
>> A(2,:) = [3,5];
??? Subscripted assignment dimension mismatch.
>> A(2,:) = [1,4,5,6];
??? Subscripted assignment dimension mismatch.
>> A(1:2, 1:2) = [1,2,3,4];
??? Subscripted assignment dimension mismatch.

What is happening here? In all three cases, take a look at the dimensions of the left and the right hand sides. In the first example, the left hand side is a 1×3 array but the right side is a 1×2 array. In the second, the left hand side is 1×3 while the right is 1×4. Finally, in the third, the left hand side is 2×2 while the right is 1×4. In all three cases, the dimensions do not match. They must match if you want to replace a specific portion of an existing variable. It doesn’t matter if they have the same number of data points or not (as the third example shows); the dimensions must also be the same, with the exception that if you have a 1xn array on one side and an nx1 on the other MATLAB will automatically transpose and replace for you:

>> A(2,:) = [1;2;3]
A =   1     2     3
      1     2     3
      7     8     9

If you do not want this be aware of it!

Struct array errors[edit | edit source]

Struct arrays are rather complex, and they have a rigid set of rules of what you can and can not do with them. Let us first deal with indexing within struct arrays. Suppose you define the variable «cube» and want to store the volume and the length of one side of two different cubes in a struct array. This can be done as follows:

>> cube(1).side = 1;
>> cube(1).volume = 1;
>> cube(2).side = 2;
>> cube(2).volume = 8;

This seems like a good way of storing data and it is for some purposes. However, suppose you wanted to abstract the volumes from the struct and store them in one array. You cannot do it this way:

>> volumes = cube.volume
??? Illegal right hand side in assignment. Too many elements.

You’ll notice that if you tell MATLAB to display cube.volume, it will display both values, but reassign the variable ans each time, because it is treated as two separate variables. In order to avoid the error, you must format ‘cube.volume’ as an array upon assignment.

>> volumes = {cube.volume}

You can also write in a separate assignment for each cube but this is more adaptable to larger numbers of cubes.

Just like extracting data, you must input the data one at a time, even if it is the same for all instances of the root (cube).

>> cube.volForm = @(S) (S^3)
??? Incorrect number of right hand side elements in dot name assignment.  Missing [] around left hand side is a likely cause.
>> cube(:).volForm = @(S) (S^3)
??? Insufficient outputs from right hand side to satisfy comma separated
list expansion on left hand side.  Missing [] are the most likely cause.

Unfortunately missing [] is not the cause, since adding them causes more errors. The cause is that you cannot assign the same value to all fields of the same name at once, you must do it one at a time, as in the following code:

>> for ii = 1:2
>>   cube(ii).volForm = @(S) (S^3);
>> end
>> cube
ans = 1x2 struct array with fields:
  volume
  side
  volForm

The same volume formula is then found in both cubes. This problem can be alleviated if you do not split the root, which is highly recommended. For example, you can use a struct like this:

>> shapes.cubeVol = @(S) (S^3);
>> shapes.cube(1).vol = 1;
>> shapes.cube(2).vol = 8;

This avoids having to use a loop to put in the formula common to all cubes.

Syntax errors[edit | edit source]

Parenthesis errors[edit | edit source]

Unlike in C++, you are not required to terminate every line with anything but a line break of some sort. However, there are still syntax rules you have to follow. In MATLAB you have to be especially careful with where you put your parenthesis so that MATLAB will do what you want it to.

A very common error is illustrated in the following:

>> A(1
??? A(1
       |
Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.

This error is simple enough, it means you’re missing a parenthesis, or you have too many. Another closely related error is the following:

>> A(1))
??? A(1))
        |
Error: Unbalanced or misused parentheses or brackets.

MATLAB tries to tell you where the missing parenthesis should go but it isn’t always right. Thus for a complex expression you have to go through it very carefully to find your typo. A useful trick is to try to set a breakpoint a line after the offending line. It won’t turn red until the error is corrected, so keep trying to correct it and saving the file until that breakpoint turns red. Of course, after this you have to make sure the parenthesis placement makes sense, otherwise you’ll probably get another error related to invalid indecies or invalid function calls.

String errors[edit | edit source]

There are two ways that you can create a string; use the ‘ string ‘ syntax, or type two words separated by only whitespace (not including line breaks), as in

>> save file.txt variable

In this line, file.txt and variable are passed to the save function as strings. It is an occasional mistake to forget a parenthesis and accidentally try to pass a string to a function that does not accept strings as input:

>> eye 5
??? Error using ==> eye
Only input must be numeric or a valid numeric class name.

These should not be hard to spot because the string is color-coded purple. Things like this occur if you uncomment a line of text and forget to change it.

Forgetting the closing ‘ in the other syntax for a string results in an obvious error:

>> A = 'hi
??? A = 'hi
        |
Error: A MATLAB string constant is not terminated properly.

The unterminated string is color-coded red to let you know that it is not terminated, since it’s otherwise easy to forget.

A common mistake with strings is to try to compare them using the ‘==’ operator. This does not work if the strings are not the same length, because strings are arrays of characters, and to compare arrays with ‘==’ they must be the same size. To compare two strings you must use the strcmp function:

>> 'AA' == 'AaA'
??? Error using ==> eq
Matrix dimensions must agree.
>> strcmp('AA', 'AaA')
ans = 0
>> strcmp('A', 'a')
ans = 0
>> strcmp('AA', 'AA')
ans = 1

Note that MATLAB strings are case sensitive, ‘A’ and ‘a’ are not the same string.

Also beware that the ‘ character for beginning and ending strings is the same character indicating transposition. So if you close a string and don’t begin it, you will most likely end up with an error about an undefined variable (if you’re trying to transpose an undefined variable) or just get really weird results because you transposed something you didn’t intend to.

Other miscellaneous errors[edit | edit source]

You cannot leave trailing functions, and if you do MATLAB gives you an error that is similar but not exactly the same as that for a missing parenthesis, since it doesn’t want to venture a guess:

>> A = 1+3+
??? A = 1+3+
            |
Error: Expression or statement is incomplete or incorrect.

These usually are not hard to spot, and often result from forgetting the «…» necessary to split a line.

The double colon is not the only «unexpected MATLAB operator», there is also «..», «….», and several other typos that generate this error.

If you accidentally type the ` character you get the error:

>> ??? `
       |
Error: The input character is not valid in MATLAB statements or expressions.

This usually occurs because you intended to put a «1» in the equation but missed the key.
Another possibility is that you named your m-file with unusual letters for computers. Like in Germany «ä, ü or ö». Be sure to name your m-files only with usual letters and no capital letters.

Function Calling errors[edit | edit source]

It is quite possible to try to call a function that doesn’t exist, such as:

>> samplemat = [1 2; 1 4]
>> A = eigen(samplemat);
??? Undefined command/function 'eigen'.

This can happen because you do not know the name of the function that performs the operation intended (for example, if you wanted to compute the eigenvalues of matrix «samplemat», you would want to call eig, not eigen). It is often useful to pull up MATLAB’s help (go to help -> product help or type doc into the command prompt) and do a search for the operation you want.

If you’re trying to call a function you created and you get this error, there are several possible reasons:

  1. The m-file must be in one of the paths listed under file -> set path, or must be in your current directory
  2. The m-file must have the same name as the name in the function declaration. You must be aware of this especially if you change the name of your functions, you must also change the name of the file or MATLAB will not find the right function!

If MATLAB finds the function, it will attempt to run it. However, there are several potential pitfalls to avoid in calling functions. It is necessary to know the nature of the input and output arguments of a given function in order to call it. For MATLAB’s built-in functions, this information is found in the documentation, or by typing

>> help functionname

It is a good idea to set up some comments so that the help function can read them in your own code as well, so you can keep track of how all your functions work and what they do at a quick reference. To do this, note that the help function reads only the block of comments directly under the function declaration, so for example, if you write a function like this:

function outvars = myfunc(invars)
% function outvars = myfunc(invars)
% Outputs outvars
% All of this is outputted when you type >> help myfunc 

% But this wouldn't be

save the function as «myfunc.m», and type

>> help myfunc

it will output:

>> function outvars = myfunc(invars)
Outputs outvars
All of this is outputted when you type >> help myfunc

Most functions (not all however) require at least one input argument, and calling it with too few will result in an error:

>> A = ode45()
??? Error using ==> ode45
Not enough input arguments.  See ODE45.

You cannot call a function with too many input arguments either:

>> A = plus(1,2,3)
??? Error using ==> plus
Too many input arguments.

Input arguments must be in a format expected by the function. This will be very function-specific, so see the documentation or help for details on what they expect. For example, the first argument to ODE45 and other ODE solvers has to be the function handle; if you pass arguments in the wrong order you will be given an error to that effect.

You can choose how many of the output arguments you want out of those available by using the bracket notation. You can choose to save fewer outputs than the function offers, but you cannot assign more variables than the function can output:

>> A = [1,2;3,4]
D = eig(A); %one output argument
[V,D] = eig(A); %two output arguments
[V,D,Mistake] = eig(A);
??? Error using ==> eig
Too many output arguments.

All assigned output arguments must also be of the correct class if you are replacing parts of an array that already exists (see the section on assignment for more on this). If you’re creating a new variable with the output, this is not an issue.

Control Flow errors[edit | edit source]

The most common one by far is if you forget the ‘END’, which is an issue in M-file functions. It will tell you that ‘at least one END is missing’ and try to tell you where the loop or conditional statement starts.

If you have too many END statements and more than one function in an M-file, MATLAB may give you a cryptic message about not formatting the functions correctly. This is because all functions in the same M-file must either end with an END statement or not. It doesn’t matter which, but if you have too many END statements in one of the functions, MATLAB will think your function is ending early and will get confused when the next function in line does not have an END statement at the end of it. So if you get this confusing message, look for extra END statements and it should fix your problem. If the message is displayed when publishing, say to an HTML file, the problem may be an erratic hierarchical indentation. Try selecting all and then hitting cntrl-i for automatic indentation to fix the problem.

Having an extra END in a ‘switch’ statement gives a message that you used the ‘case’ keyword illegally, because MATLAB thinks you ended the switch statement early, and ‘case’ has no meaning outside a ‘switch’ statement.

Other errors[edit | edit source]

There are numerous types of errors that do not generate errors from the MATLAB compiler, which have to do with calling the wrong function, using the wrong operation, using the wrong variable, introducing an infinite loop, and so on. These will be the hardest to fix, but with the help of the MATLAB debugger, they will be easier to find. See Debugging M Files for details on how to use the debugger.

Detecting or planning an error[edit | edit source]

No matter how accurate the programming is, errors might happen.
Using debug techniques are to great help, but planning an error or expecting an error could prove to be just as valuable. This includes making a possibly unneeded if block to decide what to do. I.e. if x < 5 do this and x > 5 do something else.
Also inside the big loops add an if block with modulo, like: if not ( mod ( ii , 5 ) ) % do something; end. Now the loop only does a test for every ii counter which can be divided by 5 without any remainder after the division.
Some syntax errors or logical errors inside a loop happens after looping for a long time, if an error happens then the error message is displayed, explaining where it happened but not necessarily why it happened. I.e. vector x is one element shorter than element y, and x .* y could not happen.
This mistake often happens on the last element in the shortest vector, and is quite difficult to discover unless measures are taken. try % do something; catch me me.getReport; then a breakpoint and even disp(me.getReport) will help in this situation. If the error is not fatal the code may even continue, but instead displaying the error as a message or it could be converted to a warning.

Included Matlab tools / functions: warning, lastwarn, disp, try catch, dbstack, rethrow, throwAsCaller and Matlab help on the above functions to discover pros and cons for each method.

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

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

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

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.

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

  1. In the Current Folder browser, click the Show Current Folder Actions arrow button.

  2. Select > .

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

  4. Save the modified files.

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

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:

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

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

    Preferences.

  3. Select > .

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

    search field containing a search string and the resulting search results

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

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

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

Understand the Limitations of Code Analysis

Code analysis is a valuable tool, but 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

mlintrpt | checkcode

Related Topics

  • MATLAB Code Analyzer Report
  • Code Analyzer Preferences

Attached Files Size Limitations

The combined size of all attached files for a job is limited to 4 GB.

File Access and Permissions

Ensuring That Workers on Windows Operating Systems Can Access Files

By default, a worker on a Windows® operating system is installed as a service running as
LocalSystem, so it does not have access to mapped network
drives.

Often a network is configured to not allow services running as
LocalSystem to access UNC or mapped network shares. In
this case, you must run the mjs service under a different user with rights to
log on as a service. See the section Set the User (MATLAB Parallel Server) in the MATLAB®
Parallel Server™
System Administrator’s Guide.

Task Function Is Unavailable

If a worker cannot find the task function, it returns the error message

Error using ==> feval
      Undefined command/function 'function_name'.

The worker that ran the task did not have access to the function
function_name. One solution is to make sure the location
of the function’s file, function_name.m, is included in the
job’s AdditionalPaths property. Another solution is to
transfer the function file to the worker by adding
function_name.m to the AttachedFiles
property of the job.

Load and Save Errors

If a worker cannot save or load a file, you might see the error
messages

??? Error using ==> save
Unable to write file myfile.mat: permission denied.
??? Error using ==> load
Unable to read file myfile.mat: No such file or directory.

In determining the cause of this error, consider the following
questions:

  • What is the worker’s current folder?

  • Can the worker find the file or folder?

  • What user is the worker running as?

  • Does the worker have permission to read or write the file in question?

Tasks or Jobs Remain in Queued State

A job or task might get stuck in the queued state. To investigate the cause of
this problem, look for the scheduler’s logs:

  • Platform LSF® schedulers might send emails with error messages.

  • Microsoft®
    Windows HPC Server (including CCS), LSF®, PBS Pro®, and TORQUE save output messages in a debug log. See the
    getDebugLog reference
    page.

  • If using a generic scheduler, make sure the submit function redirects
    error messages to a log file.

Possible causes of the problem are:

  • The MATLAB worker failed to start due to licensing errors, the
    executable is not on the default path on the worker machine, or is not
    installed in the location where the scheduler expected it to be.

  • MATLAB could not read/write the job input/output files in the
    scheduler’s job storage location. The storage location might not be
    accessible to all the worker nodes, or the user that MATLAB runs as does not have permission to read/write the job
    files.

  • If using a generic scheduler:

    • The environment variable
      PARALLEL_SERVER_DECODE_FUNCTION was not
      defined before the MATLAB worker started.

    • The decode function was not on the worker’s path.

No Results or Failed Job

Task Errors

If your job returned no results (i.e., fetchOutputs(job)
returns an empty cell array), it is probable that the job failed and some of its
tasks have their Error properties set.

You can use the following code to identify tasks with error messages:

errmsgs = get(yourjob.Tasks, {'ErrorMessage'});
nonempty = ~cellfun(@isempty, errmsgs);
celldisp(errmsgs(nonempty));

This code displays the nonempty error messages of the tasks found in the job
object yourjob.

Debug Logs

If you are using a supported third-party scheduler, you can use the getDebugLog function to read
the debug log from the scheduler for a particular job or task.

For example, find the failed job on your LSF scheduler, and read its debug
log:

c = parcluster('my_lsf_profile')
failedjob = findJob(c, 'State', 'failed');
message = getDebugLog(c, failedjob(1))

Connection Problems Between the Client and MATLAB Job Scheduler

For testing connectivity between the client machine and the machines of your
compute cluster, you can use Admin Center. For more information about Admin Center,
including how to start it and how to test connectivity, see Start Admin Center (MATLAB Parallel Server) and Test Connectivity (MATLAB Parallel Server).

Detailed instructions for other methods of diagnosing connection problems between
the client and MATLAB Job Scheduler can be found in some of the Bug Reports listed on the MathWorks Web site.

The following sections can help you identify the general nature of some connection
problems.

Client Cannot See the MATLAB Job Scheduler

If you cannot locate or connect to your MATLAB Job Scheduler with parcluster, the most
likely reasons for this failure are:

  • The MATLAB Job Scheduler is currently not running.

  • Firewalls do not allow traffic from the client to the MATLAB Job Scheduler.

  • The client and the MATLAB Job Scheduler are not running the same version of the
    software.

  • The client and the MATLAB Job Scheduler cannot resolve each other’s short
    hostnames.

  • The MATLAB Job Scheduler is using a nondefault
    BASE_PORT setting as defined in the
    mjs_def file, and the Host
    property in the cluster profile does not specify this port.

MATLAB Job Scheduler Cannot See the Client

If a warning message says that the MATLAB Job Scheduler cannot open a TCP connection to the client computer,
the most likely reasons for this are

  • Firewalls do not allow traffic from the MATLAB Job Scheduler to the client.

  • The MATLAB Job Scheduler cannot resolve the short hostname of the
    client computer. Use pctconfig to change the
    hostname that the MATLAB Job Scheduler will use for contacting the client.

«One of your shell’s init files contains a command that is writing to stdout…»

The example code for generic schedulers with non-shared file systems contacts an
sftp server to handle the file transfer to and from the cluster’s file system. This
use of sftp is subject to all the normal sftp vulnerabilities. One problem that can
occur results in an error message similar to this:

One of your shell's init files contains a command that is writing to stdout,
interfering with RemoteClusterAccess.
The stdout read was:
<some output>

Find and wrap the command with a conditional test, such as

	if ($?TERM != 0) then
		if ("$TERM" != "dumb") then
			<your command>
		endif
	endif

The sftp server starts a shell, usually bash or tcsh, to set your standard read
and write permissions appropriately before transferring files. The server
initializes the shell in the standard way, calling files like .bashrc and .cshrc.
The problem occurs if your shell emits text to standard out when it starts. That
text is transferred back to the sftp client running inside MATLAB, and is interpreted as the size of the sftp server’s response message.

To work around this error, locate the shell startup file code that is emitting the
text, and either remove it or bracket it within if statements to
see if the sftp server is starting the shell:

if ($?TERM != 0) then
    if ("$TERM" != "dumb") then
        /your command/
    endif
endif

You can test this outside of MATLAB with a standard UNIX or Windows sftp command-line client before trying
again in MATLAB. If the problem is not fixed, an error message persists:

Connecting to yourSubmitMachine...
Received message too long 1718579042

If the problem is fixed, you should see:

Connecting to yourSubmitMachine...

I was doing a model for a slider-crank mechanism and I wanted to display an error for when the crank’s length exceeds that of the slider arm. With the crank’s length as r2 and the slider’s as r3, my code went like this:

if r3=<r2
    error('The crank's length cannot exceed that of the slider')
end

I get the error:

???     error('The crank's length cannot exceed that of the slider')
                         |
Error: Unexpected MATLAB expression.

can someone tell me what I’m doing wrong and how to fix it please?

Amro's user avatar

Amro

124k25 gold badges242 silver badges453 bronze badges

asked Dec 13, 2009 at 19:17

Ahmed's user avatar

When you want to use the ' character in a string, you have to precede it with another ' (note the example in the documentation):

if (r3 <= r2)
  error('The crank''s length cannot exceed that of the slider');
end

Also, note the change I made from =< to <=.

answered Dec 13, 2009 at 19:23

gnovice's user avatar

gnovicegnovice

125k15 gold badges256 silver badges359 bronze badges

1

You can print to the error handle as well:

fprintf(2,'The crank''s length cannot exceed that of the slider');

answered Dec 13, 2009 at 19:25

Zaid's user avatar

ZaidZaid

36.6k16 gold badges85 silver badges154 bronze badges

1

I believe the comparison operator should be <= not the other way around, unless that was only a typo in your question

Also you should escape the ' character using ''

answered Dec 13, 2009 at 19:22

Amro's user avatar

AmroAmro

124k25 gold badges242 silver badges453 bronze badges

Сообщения об ошибках и исправление ошибок

Важное значение
при диалоге с системой 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

  • Маткад произошла внутренняя ошибка
  • Маткад ошибка этот индекс массива недопустим для этого массива
  • Маткад ошибка это значение должно быть скалярным
  • Маткад ошибка это вычисление не приближается к решению
  • Маткад ошибка формы этих значений должны совпадать