Undefined function matlab error

Troubleshoot error message related to undefined function or variable.

Possible Solutions

Verify Spelling of Function or Variable Name

One of the most common causes is misspelling the function or variable name.
Especially with longer names or names containing similar characters (such as the
letter l and numeral one), it is easy to make mistakes and
hard to detect them.

Often, when you misspell a MATLAB function, a suggested function name appears in the Command Window.
For example, this command fails because it includes an uppercase letter in the
function name:

Undefined function or variable 'accumArray'.
 
Did you mean:
>> accumarray

When this happens, press Enter to execute the suggested
command or Esc to dismiss it.

Verify Inputs Correspond to the Function Syntax

Object methods are typically called using function syntax: for instance
method(object,inputs). Alternatively, they can be called
using dot notation: for instance object.method(inputs). One
common error is to mix these syntaxes. For instance, you might call the method
using function syntax, but to provide inputs following dot notation syntax and
leave out the object as an input: for instance,
method(inputs). To avoid this, when calling an object
method, make sure you specify the object first, either through the first input
of function syntax or through the first identifier of dot notation.

Make Sure Function Name Matches File Name

When you write a function, you establish its name when you write its function
definition line. This name should always match the name of the file you save it
to. For example, if you create a function named curveplot,

function curveplot(xVal, yVal)
     - program code -

then you should name the file containing that function
curveplot.m. If you create a pcode file for the function,
then name that file curveplot.p. In the case of conflicting
function and file names, the file name overrides the name given to the function.
In this example, if you save the curveplot function to a file
named curveplotfunction.m, then attempts to invoke the
function using the function name will fail:

curveplot
Undefined function or variable 'curveplot'.

If you encounter this problem, change either the function name or file name so
that they are the same.

To Locate the file that defines this function, use the MATLAB
Find Files utility as follows:

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

    Find Files.

  2. Under , enter
    *.m

  3. Under , enter
    the function name.

  4. Click the Find button

Make Sure Necessary Toolbox Is Installed and Correct Version

If you are unable to use a built-in function from MATLAB or its toolboxes, make sure that the function is installed and is
the correct version.

If you do not know which toolbox contains the function you need, search for
the function documentation at https://www.mathworks.com/help. The toolbox name
appears at the top of the function reference page. Alternatively, for steps to
identify toolboxes that a function depends on, see Identify Program Dependencies.

Once you know which toolbox the function belongs to, use the ver function to see which
toolboxes are installed on the system from which you run MATLAB. The ver function displays a list of all
currently installed MathWorks® products. If you can locate the toolbox you need in the output
displayed by ver, then the toolbox is installed. If you
cannot, you need to install it in order to use it. For help with installing
MathWorks products, see Install License Manager on License Server.

Verify Path Used to Access Function Toolbox

Tip

If you have a custom file path, this step will delete it.

The MATLAB search path is a subset of all the folders in the file system.
MATLAB uses the search path to locate files used with MathWorks products efficiently. For more information, see What Is the MATLAB Search Path?.

If the function you are attempting to use is part of a toolbox, then verify
that the toolbox is available using ver.

Because MATLAB stores the toolbox information in a cache file, you need to first
update this cache and then reset the path.

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

    Preferences.

    The Preference dialog box appears.

  2. On the > page, select Update Toolbox Path
    Cache
    .

  3. On the Home tab, in the
    Environment section, select

    .

    The Set Path dialog box opens.

  4. Select Default.

    A small dialog box opens warning that you will lose your current path
    settings if you proceed. Select Yes if you decide
    to proceed.

Run ver to see if the toolbox is installed. If not, you
may need to reinstall this toolbox to use this function. For more information
about installing a toolbox, see How do I install additional toolboxes into an existing installation of
MATLAB.

Once ver shows your toolbox, run the following command to
see if you can find the function:

which -all <functionname>

replacing <functionname>
with the name of the function. If MATLAB finds your function file, it presents you with the path to it. You
can add that file to the path using the addpath function. If
it does not, make sure the necessary toolbox is installed, and that it is the
correct version.

Confirm The License Is Active

If you are unable to use a built-in function from a MATLAB toolbox and have confirmed that the toolbox is installed, make
sure that you have an active license for that toolbox. Use license to display currently active licenses.
For additional support for managing licenses, see Manage Your Licenses.

Ошибка твердости: неопределенная функция или переменная

Проблема

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

Undefined function or variable 'x'.

Эти ошибки обычно указывают, что MATLAB не может найти конкретную переменную или файл программы MATLAB в текущем каталоге или на пути поиска файлов.

Возможные решения

Проверьте написание имени функции или имени переменной

Одна из наиболее распространенных причин пишет c ошибкой имя функции или имя переменной. Особенно с более длинными именами или именами, содержащими похожие символы (такие как буква l и цифра «один»), легко сделать ошибки и трудно обнаружить их.

Часто, когда вы пишете функцию MATLAB c ошибкой, предложенное имя функции появляется в Командном окне. Например, эта команда перестала работать, потому что она содержит заглавную букву в имени функции:

Undefined function or variable 'accumArray'.
 
Did you mean:
>> accumarray

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

Проверьте, что входные параметры соответствуют синтаксису функций

Методы объекта обычно называются с помощью синтаксиса функций: например, method(object,inputs). В качестве альтернативы они могут быть названы с помощью записи через точку: например, object.method(inputs). Одна распространенная ошибка должна смешать эти синтаксисы. Например, вы можете вызвать метод с помощью синтаксиса функций, но обеспечить входные параметры после синтаксиса записи через точку и не учесть объект как вход: например, method(inputs). Чтобы избежать это, при вызове метода объекта, убеждается, что вы задаете объект сначала, или через первый вход синтаксиса функций или через первый идентификатор записи через точку.

Убедитесь, что имя функции совпадает с именем файла

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

function curveplot(xVal, yVal)
     - program code -

затем необходимо назвать файл, содержащий эту функцию curveplot.m. Если вы создаете a pcode файл для функции, затем назовите тот файл curveplot.p. В случае конфликтной функции и имен файлов, имя файла заменяет имя, данное функции. В этом примере, если вы сохраняете curveplot функционируйте в файл с именем curveplotfunction.m, то попытка обратиться к функции по имени будет неудачной:

curveplot
Undefined function or variable 'curveplot'.

Если вы столкнулись с этой проблемой, измените имя функции либо файла так, чтобы они совпали.

Чтобы Определить местоположение файла, который задает эту функцию, используйте утилиту Find Files MATLAB можно следующим образом:

  1. На вкладке Home, в разделе File, нажимают
    Find Files.

  2. Под введите имя функции.

  3. Нажмите кнопку Find

Убедитесь, что необходимый тулбокс установлен и правильная версия

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

Если вы не знаете, какой тулбокс содержит необходимую функцию, обратитесь к поиску по функциям в https://www.mathworks.com/help. Имя тулбокса появляется наверху страницы ссылки на функцию. В качестве альтернативы для шагов, чтобы идентифицировать тулбоксы, от которых зависит функция, смотрите, Идентификация программных зависимостей.

Если вы знаете, какому тулбоксу функция принадлежит, используйте ver функция, чтобы видеть, какие тулбоксы установлены в системе, от которой вы запускаете MATLAB. ver функционируйте отображает список всех в настоящее время установленных продуктов MathWorks®. Если можно определить местоположение тулбокса, вам нужно в выводе, отображенном ver, затем тулбокс установлен. Если вы не можете, необходимо установить его для того, чтобы использовать его. Если вы не можете, необходимо установить его для того, чтобы использовать его. Для справки с установкой Продуктов Mathworks смотрите Установку и Лицензирование.

Проверьте путь, используемый к тулбоксу функции доступа

Совет

Если у вас будет пользовательский путь к файлу, этот шаг удалит его.

Путь поиска файлов MATLAB является подмножеством всех папок в файловой системе. MATLAB использует путь поиска файлов, чтобы определить местоположение файлов, используемых с Продуктами Mathworks эффективно. Для получения дополнительной информации смотрите то, Что Путь поиска файлов MATLAB?.

Если функция, которую вы пытаетесь использовать, является частью тулбокса, то проверьте, что тулбокс является доступным использованием ver.

Поскольку MATLAB хранит информацию тулбокса в файле кэша, необходимо сначала обновить этот кэш и затем сбросить путь.

  1. На вкладке «Главная страница (Home)» в разделе «Конфигурация (Environment)» нажмите «Настройки (Preferences)».

    Диалоговое окно Preference появляется.

  2. На странице > выберите Update Toolbox Path Cache.

  3. На вкладке Home, в разделе Environment, выбирают
    .

    Диалоговое окно Set Path открывается.

  4. Выберите Default.

    Маленькое диалоговое окно открывает предупреждение, что вы потеряете свои текущие настройки пути, если вы продолжите. Выберите Yes, если вы решаете продолжить.

Запущенный ver видеть, установлен ли тулбокс. В противном случае вы, возможно, должны переустановить этот тулбокс, чтобы использовать эту функцию. Для получения дополнительной информации о том, чтобы установить тулбокс, смотрите, Как я установил дополнительные тулбоксы в существующую установку MATLAB.

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

which -all <functionname>

заменяя <functionname> именем функции. Если MATLAB находит ваш файл функции, он дарит вам путь к нему. Можно добавить что файл в путь с помощью addpath функция. Если это не делает, убедитесь, что необходимый тулбокс установлен, и что это — правильная версия.

Подтвердите, что лицензия активна

Если вы не можете использовать встроенную функцию от тулбокса MATLAB и подтвердили, что тулбокс установлен, убедитесь, что у вас есть активная лицензия на тот тулбокс. Используйте license отобразить в настоящее время активные лицензии. Для дополнительной поддержки лицензий управления смотрите, Управляют Вашими Лицензиями.

Содержание

  1. Error undefined function or variable matlab
  2. Possible Solutions
  3. Verify Spelling of Function or Variable Name
  4. Verify Inputs Correspond to the Function Syntax
  5. Make Sure Function Name Matches File Name
  6. Make Sure Necessary Toolbox Is Installed and Correct Version
  7. Verify Path Used to Access Function Toolbox
  8. Confirm The License Is Active
  9. MATLAB Command
  10. Error undefined function or variable matlab
  11. Possible Solutions
  12. Verify Spelling of Function or Variable Name
  13. Verify Inputs Correspond to the Function Syntax
  14. Make Sure Function Name Matches File Name
  15. Make Sure Necessary Toolbox Is Installed and Correct Version
  16. Verify Path Used to Access Function Toolbox
  17. Confirm The License Is Active
  18. MATLAB Command
  19. Error undefined function or variable matlab
  20. Possible Solutions
  21. Verify Spelling of Function or Variable Name
  22. Verify Inputs Correspond to the Function Syntax
  23. Make Sure Function Name Matches File Name
  24. Make Sure Necessary Toolbox Is Installed and Correct Version
  25. Verify Path Used to Access Function Toolbox
  26. Confirm The License Is Active
  27. MATLAB Command

Error undefined function or variable matlab

You may encounter the following error message, or something similar, while working with functions or variables in MATLAB ® :

These errors usually indicate that MATLAB cannot find a particular variable or MATLAB program file in the current directory or on the search path.

Possible Solutions

Verify Spelling of Function or Variable Name

One of the most common causes is misspelling the function or variable name. Especially with longer names or names containing similar characters (such as the letter l and numeral one), it is easy to make mistakes and hard to detect them.

Often, when you misspell a MATLAB function, a suggested function name appears in the Command Window. For example, this command fails because it includes an uppercase letter in the function name:

When this happens, press Enter to execute the suggested command or Esc to dismiss it.

Verify Inputs Correspond to the Function Syntax

Object methods are typically called using function syntax: for instance method(object,inputs) . Alternatively, they can be called using dot notation: for instance object.method(inputs) . One common error is to mix these syntaxes. For instance, you might call the method using function syntax, but to provide inputs following dot notation syntax and leave out the object as an input: for instance, method(inputs) . To avoid this, when calling an object method, make sure you specify the object first, either through the first input of function syntax or through the first identifier of dot notation.

Make Sure Function Name Matches File Name

When you write a function, you establish its name when you write its function definition line. This name should always match the name of the file you save it to. For example, if you create a function named curveplot ,

then you should name the file containing that function curveplot.m . If you create a pcode file for the function, then name that file curveplot.p . In the case of conflicting function and file names, the file name overrides the name given to the function. In this example, if you save the curveplot function to a file named curveplotfunction.m , then attempts to invoke the function using the function name will fail:

If you encounter this problem, change either the function name or file name so that they are the same.

To Locate the file that defines this function, use the MATLAB Find Files utility as follows:

On the Home tab, in the File section, click Find Files.

Under Find files named, enter *.m

Under Find files containing text, enter the function name.

Click the Find button

Make Sure Necessary Toolbox Is Installed and Correct Version

If you are unable to use a built-in function from MATLAB or its toolboxes, make sure that the function is installed and is the correct version.

If you do not know which toolbox contains the function you need, search for the function documentation at https://www.mathworks.com/help . The toolbox name appears at the top of the function reference page. Alternatively, for steps to identify toolboxes that a function depends on, see Identify Program Dependencies.

Once you know which toolbox the function belongs to, use the ver function to see which toolboxes are installed on the system from which you run MATLAB. The ver function displays a list of all currently installed MathWorks ® products. If you can locate the toolbox you need in the output displayed by ver , then the toolbox is installed. If you cannot, you need to install it in order to use it. For help with installing MathWorks products, see Install License Manager on License Server.

Verify Path Used to Access Function Toolbox

Tip

If you have a custom file path, this step will delete it.

The MATLAB search path is a subset of all the folders in the file system. MATLAB uses the search path to locate files used with MathWorks products efficiently. For more information, see What Is the MATLAB Search Path?.

If the function you are attempting to use is part of a toolbox, then verify that the toolbox is available using ver .

Because MATLAB stores the toolbox information in a cache file, you need to first update this cache and then reset the path.

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

The Preference dialog box appears.

On the MATLAB > General page, select Update Toolbox Path Cache.

On the Home tab, in the Environment section, select Set Path.

The Set Path dialog box opens.

A small dialog box opens warning that you will lose your current path settings if you proceed. Select Yes if you decide to proceed.

Run ver to see if the toolbox is installed. If not, you may need to reinstall this toolbox to use this function. For more information about installing a toolbox, see How do I install additional toolboxes into an existing installation of MATLAB.

Once ver shows your toolbox, run the following command to see if you can find the function:

replacing with the name of the function. If MATLAB finds your function file, it presents you with the path to it. You can add that file to the path using the addpath function. If it does not, make sure the necessary toolbox is installed, and that it is the correct version.

Confirm The License Is Active

If you are unable to use a built-in function from a MATLAB toolbox and have confirmed that the toolbox is installed, make sure that you have an active license for that toolbox. Use license to display currently active licenses. For additional support for managing licenses, see Manage Your Licenses.

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Источник

Error undefined function or variable matlab

You may encounter the following error message, or something similar, while working with functions or variables in MATLAB ® :

These errors usually indicate that MATLAB cannot find a particular variable or MATLAB program file in the current directory or on the search path.

Possible Solutions

Verify Spelling of Function or Variable Name

One of the most common causes is misspelling the function or variable name. Especially with longer names or names containing similar characters (such as the letter l and numeral one), it is easy to make mistakes and hard to detect them.

Often, when you misspell a MATLAB function, a suggested function name appears in the Command Window. For example, this command fails because it includes an uppercase letter in the function name:

When this happens, press Enter to execute the suggested command or Esc to dismiss it.

Verify Inputs Correspond to the Function Syntax

Object methods are typically called using function syntax: for instance method(object,inputs) . Alternatively, they can be called using dot notation: for instance object.method(inputs) . One common error is to mix these syntaxes. For instance, you might call the method using function syntax, but to provide inputs following dot notation syntax and leave out the object as an input: for instance, method(inputs) . To avoid this, when calling an object method, make sure you specify the object first, either through the first input of function syntax or through the first identifier of dot notation.

Make Sure Function Name Matches File Name

When you write a function, you establish its name when you write its function definition line. This name should always match the name of the file you save it to. For example, if you create a function named curveplot ,

then you should name the file containing that function curveplot.m . If you create a pcode file for the function, then name that file curveplot.p . In the case of conflicting function and file names, the file name overrides the name given to the function. In this example, if you save the curveplot function to a file named curveplotfunction.m , then attempts to invoke the function using the function name will fail:

If you encounter this problem, change either the function name or file name so that they are the same.

To Locate the file that defines this function, use the MATLAB Find Files utility as follows:

On the Home tab, in the File section, click Find Files.

Under Find files named, enter *.m

Under Find files containing text, enter the function name.

Click the Find button

Make Sure Necessary Toolbox Is Installed and Correct Version

If you are unable to use a built-in function from MATLAB or its toolboxes, make sure that the function is installed and is the correct version.

If you do not know which toolbox contains the function you need, search for the function documentation at https://www.mathworks.com/help . The toolbox name appears at the top of the function reference page. Alternatively, for steps to identify toolboxes that a function depends on, see Identify Program Dependencies.

Once you know which toolbox the function belongs to, use the ver function to see which toolboxes are installed on the system from which you run MATLAB. The ver function displays a list of all currently installed MathWorks ® products. If you can locate the toolbox you need in the output displayed by ver , then the toolbox is installed. If you cannot, you need to install it in order to use it. For help with installing MathWorks products, see Install License Manager on License Server.

Verify Path Used to Access Function Toolbox

Tip

If you have a custom file path, this step will delete it.

The MATLAB search path is a subset of all the folders in the file system. MATLAB uses the search path to locate files used with MathWorks products efficiently. For more information, see What Is the MATLAB Search Path?.

If the function you are attempting to use is part of a toolbox, then verify that the toolbox is available using ver .

Because MATLAB stores the toolbox information in a cache file, you need to first update this cache and then reset the path.

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

The Preference dialog box appears.

On the MATLAB > General page, select Update Toolbox Path Cache.

On the Home tab, in the Environment section, select Set Path.

The Set Path dialog box opens.

A small dialog box opens warning that you will lose your current path settings if you proceed. Select Yes if you decide to proceed.

Run ver to see if the toolbox is installed. If not, you may need to reinstall this toolbox to use this function. For more information about installing a toolbox, see How do I install additional toolboxes into an existing installation of MATLAB.

Once ver shows your toolbox, run the following command to see if you can find the function:

replacing with the name of the function. If MATLAB finds your function file, it presents you with the path to it. You can add that file to the path using the addpath function. If it does not, make sure the necessary toolbox is installed, and that it is the correct version.

Confirm The License Is Active

If you are unable to use a built-in function from a MATLAB toolbox and have confirmed that the toolbox is installed, make sure that you have an active license for that toolbox. Use license to display currently active licenses. For additional support for managing licenses, see Manage Your Licenses.

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Источник

Error undefined function or variable matlab

You may encounter the following error message, or something similar, while working with functions or variables in MATLAB ® :

These errors usually indicate that MATLAB cannot find a particular variable or MATLAB program file in the current directory or on the search path.

Possible Solutions

Verify Spelling of Function or Variable Name

One of the most common causes is misspelling the function or variable name. Especially with longer names or names containing similar characters (such as the letter l and numeral one), it is easy to make mistakes and hard to detect them.

Often, when you misspell a MATLAB function, a suggested function name appears in the Command Window. For example, this command fails because it includes an uppercase letter in the function name:

When this happens, press Enter to execute the suggested command or Esc to dismiss it.

Verify Inputs Correspond to the Function Syntax

Object methods are typically called using function syntax: for instance method(object,inputs) . Alternatively, they can be called using dot notation: for instance object.method(inputs) . One common error is to mix these syntaxes. For instance, you might call the method using function syntax, but to provide inputs following dot notation syntax and leave out the object as an input: for instance, method(inputs) . To avoid this, when calling an object method, make sure you specify the object first, either through the first input of function syntax or through the first identifier of dot notation.

Make Sure Function Name Matches File Name

When you write a function, you establish its name when you write its function definition line. This name should always match the name of the file you save it to. For example, if you create a function named curveplot ,

then you should name the file containing that function curveplot.m . If you create a pcode file for the function, then name that file curveplot.p . In the case of conflicting function and file names, the file name overrides the name given to the function. In this example, if you save the curveplot function to a file named curveplotfunction.m , then attempts to invoke the function using the function name will fail:

If you encounter this problem, change either the function name or file name so that they are the same.

To Locate the file that defines this function, use the MATLAB Find Files utility as follows:

On the Home tab, in the File section, click Find Files.

Under Find files named, enter *.m

Under Find files containing text, enter the function name.

Click the Find button

Make Sure Necessary Toolbox Is Installed and Correct Version

If you are unable to use a built-in function from MATLAB or its toolboxes, make sure that the function is installed and is the correct version.

If you do not know which toolbox contains the function you need, search for the function documentation at https://www.mathworks.com/help . The toolbox name appears at the top of the function reference page. Alternatively, for steps to identify toolboxes that a function depends on, see Identify Program Dependencies.

Once you know which toolbox the function belongs to, use the ver function to see which toolboxes are installed on the system from which you run MATLAB. The ver function displays a list of all currently installed MathWorks ® products. If you can locate the toolbox you need in the output displayed by ver , then the toolbox is installed. If you cannot, you need to install it in order to use it. For help with installing MathWorks products, see Install License Manager on License Server.

Verify Path Used to Access Function Toolbox

Tip

If you have a custom file path, this step will delete it.

The MATLAB search path is a subset of all the folders in the file system. MATLAB uses the search path to locate files used with MathWorks products efficiently. For more information, see What Is the MATLAB Search Path?.

If the function you are attempting to use is part of a toolbox, then verify that the toolbox is available using ver .

Because MATLAB stores the toolbox information in a cache file, you need to first update this cache and then reset the path.

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

The Preference dialog box appears.

On the MATLAB > General page, select Update Toolbox Path Cache.

On the Home tab, in the Environment section, select Set Path.

The Set Path dialog box opens.

A small dialog box opens warning that you will lose your current path settings if you proceed. Select Yes if you decide to proceed.

Run ver to see if the toolbox is installed. If not, you may need to reinstall this toolbox to use this function. For more information about installing a toolbox, see How do I install additional toolboxes into an existing installation of MATLAB.

Once ver shows your toolbox, run the following command to see if you can find the function:

replacing with the name of the function. If MATLAB finds your function file, it presents you with the path to it. You can add that file to the path using the addpath function. If it does not, make sure the necessary toolbox is installed, and that it is the correct version.

Confirm The License Is Active

If you are unable to use a built-in function from a MATLAB toolbox and have confirmed that the toolbox is installed, make sure that you have an active license for that toolbox. Use license to display currently active licenses. For additional support for managing licenses, see Manage Your Licenses.

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Источник

MathWorks Support Team

I am receiving one of the following error messages. How can I resolve this issue?

Undefined function or variable ‹Name›.

Unrecognized function or variable ‹Name›.

Undefined function or method ‹Name› for input arguments of type ‹ClassName›.

采纳的回答

MathWorks Support Team

MATLAB does not recognize the specified string as the name of a function on the MATLAB path or as a variable. The above error messages can be caused by:

1) Trying to use a variable that has not been defined before this line of code executes.

>> x=1:10;

>> t=x.^2;

>> plot(x,y)

Undefined function or variable ‘y’.

2) A typographical error when typing a function or variable name. However, later versions of MATLAB try to resolve these typos with “Did you mean” suggestions. For example,

>> foo = 42;

>> fo0

Undefined function or variable ‘fo0’.

Did you mean:

>> foo

3) The wrong case for a function or variable name. Later versions of MATLAB try to resolve these typos with “Did you mean” suggestions.

4) Changing directories so that a function you used is no longer on the MATLAB path.

5) Trying to use a function for which you are not licensed or that belongs to a MathWorks toolbox that isn’t installed. In later versions of MATLAB, this is not an “Undefined function or variable” error, and MATLAB lets you know that you are either not licensed to use the function or the appropriate toolbox is not installed.

6) Trying to use a function that belongs to a third-party toolbox that isn’t installed.

7) Trying to use a function that does not yet exist in your version of MATLAB.

8) Trying to use a function that has been removed from your version of MATLAB. In later versions of MATLAB, this is not an “Undefined function or variable” error, and MATLAB lets you know the new, preferred function to use.

9) Trying to use a variable that gets cleared from the workspace because your script or function contains «clear all» or «clearvars».

10) Calling an object method without an object as the first input.

11) Using a MEX function that is compiled on a platform different from the one in use.

Try the following:

1) Verify that the undefined function or variable is visible (it is on the path or in the current workspace) and that it has been defined before this line of code executes. If the undefined identifier is a function, the ‘which‘ function can help you verify that it is visible to the function where the error occurs:https://www.mathworks.com/help/matlab/ref/which.html

2) Verify that the function that you are trying to use is available in your version of MATLAB using the built-in documentation (>> doc). If you cannot find it in our documentation, the function may have been added in a later release of MATLAB, or it may be part of a third-party toolbox that is external to MathWorks.

3) If you are trying to use a function that should be available in your version of MATLAB, from a MathWorks toolbox that you have installed and licensed for, there may be a problem with your MATLAB search path. Run the following MATLAB commands to restore it:

>> restoredefaultpath

>> rehash toolboxcache

>> savepath

See our documentation for more tips:


更多回答(56 个)

Alex Alex

Undefined function or variable ‘shaperead’. On the description page for this function it says «Introduced before R2006a». I use MATLAB R2015b- academic use. Does that mean that the function is not available for student license? How can I perform this kind of check in the future? Many thanks, Alex.


Saadia Talay

Undefined function or variable ‘lgemri’ when I enter the following:

[X,meta]=nrrdread(lgemri);

The lgemri is a file in nrrd format.


Iman Tahamtan

I am facing this error when running y_lambda=lambda: Undefined function or variable ‘lambda’.


ishwarya ramesh

Undefined function or variable ‘drivingScenario’. why do i get this error i just need a clear explanation


Liliana Malik

why do i get Undefined function or variable ‘pixelLabelDatastore’ and Undefined function or variable ‘batchNormalizationLayer’


tim jelly

When trying to make a GUI i get the error:

Undefined function or variable ‘radioChanged’

Error while evaluating ButtonGroup SelectionChangedFcn.

I dont have «radioChanged» in my code so how do I fix this, thanks


Francisco Santamaría

for i=1:(npop+1)

dron(i,:)=rand(1,nvar).*(xmax-xmin)+xmin;

cost(i)=CostfunctA3(dron(i,:));

dron_cost(i,:)=[dron(i,:) cost(i)]

end

When trying to make a run i get the following error:

Undefined function or variable ‘CostfunctA3’.


Waqas Waqas Ul Hussan

hi

I am getting this problem in Matlab when plotting the graphs with shaded area.

Undefined function or variable ‘jbfill’.

These below are my code lines. error is in line 127 below.


Dhruba Raj Dhakal

Why this error occurs when I use antenna toolbox???


David Akin

Same error but using a Mathworks example. Here’s the contents of fact.m

function f = fact(n)

f = prod(1:n);

end

Located here:

/opt/software/MATLAB/2018a/toolbox/local/fact.m

When trying to use:

>> y=fact(5);

Undefined function or variable ‘fact’.

I cd’ed to the directory containing the file before starting MATLAB and it’s in the search path:

>> path

MATLABPATH

/opt/software/MATLAB/2018a/toolbox/local

.

.

.

Any suggestions?

>> dos(‘cat /opt/software/MATLAB/2018a/toolbox/local/fact.m’);

function f = fact(n)

f = prod(1:n);

end


David Akin

It’s an example only, as I’ve got some code from a colleage (a collection of .m files) I’d like to use. However it’s not finding the functions. Thank you though.


michael

(Matlab R14)

Something strange is that when I try to call some function from toolbox (communication) I’m getting that it is not existing.

Even when I’m going to %MATLABROOT%toolboxcommcomm where the m file is existing, I still can’t run it.

Please suggest what is the issue


Darrell

I have seen this issue before with other functions. As stated before, first check that the function name is spelled correctly and that the function is located in the matlab search path. Assuming those two things check, then delete the path where the function is located, then reset the path. I would also will restart Matlab. I’m not sure why, but this seems to correct the problem.


Al3jandro

Hi.

I’m making this rutine, but i cant get values of K, how can I resolve this issue?

clear;

clc;

A=xlsread(‘ANÁLISIS DE ESTRUCTURAS _ INPUT2’,‘BARRAS’,‘B1:B6’);

I=xlsread(‘ANÁLISIS DE ESTRUCTURAS _ INPUT2’,‘BARRAS’,‘C1:C6’);

E=xlsread(‘ANÁLISIS DE ESTRUCTURAS _ INPUT2’,‘BARRAS’,‘D1:D6’);

W=xlsread(‘ANÁLISIS DE ESTRUCTURAS _ INPUT2’,‘BARRAS’,‘u1:u6’);

L=xlsread(‘ANÁLISIS DE ESTRUCTURAS _ INPUT2’,‘BARRAS’,‘Q1:Q6’);

a=xlsread(‘ANÁLISIS DE ESTRUCTURAS _ INPUT2’,‘BARRAS’,‘R1:R6’);

n=xlsread(‘ANÁLISIS DE ESTRUCTURAS _ INPUT2’,‘BARRAS’,‘V3’);

nGDL=xlsread(‘ANÁLISIS DE ESTRUCTURAS _ INPUT2’,‘NUDOS’,‘J2’);

GDLG=xlsread(‘ANÁLISIS DE ESTRUCTURAS _ INPUT2’,‘BARRAS’,‘K2:P4’);

for i=1:n

A=A(i);

I=I(i);

E=E(i);

L=L(i);

a=a(i);

KL(i)=[E*A/L 0 0 -E*A/L 0 0;0 12*E*I/L^3 6*E*I/L^2 0 -12*E*I/L^3 6*E*I/L^2;0 6*E*I/L^2 4*E*I/L 0 -6*E*I/L^2 2*E*I/L;-E*A/L 0 0 E*A/L 0 0;0 -12*E*I/L^3 -6*E*I/L^2 0 12*E*I/L^3 -6*E*I/L^2;0 6*E*I/L^2 2*E*I/L 0 -6*E*I/L^2 4*E*I/L];

T(i)=[cos(a) sin(a) 0 0 0 0;-sin(a) cos(a) 0 0 0 0;0 0 1 0 0 0;0 0 0 cos(a) sin(a) 0;0 0 0 -sin(a) cos(a) 0;0 0 0 0 0 1];

KG(i)=T(i)’*KL(i)*T(i);

G=[GDLG(i,1) GDLG(i,2) GDLG(i,3) GDLG(i,4) GDLG(i,5) GDLG(i,6)];

KT=zeros(nGDL,nGDL);

KT(G,G)=KG(i);

if i==1

K=zeros(nGDL,nGDL);

end

K=K+KT;

end

disp(K)


clpi

Hello !

I have a matlab function which at a certain point calculates sin(2*pi*freq*t_array) (t_array in an array of size (1,2000).

I tried to call this function via matlab.engine but I got the error message: «Undefined function ‘sin’ for input argument of type ‘int64’ «

I wanted to add the file ‘sin.m’ to my working directory but it is not a function script, it is a simple text.

I would be very grateful of any help

Thank you !


Regina Vivian Barli

Hello, I happen to stumble upon similar problem.

So I have been trying to use matlab for video stabilising, but keep getting this error:

Undefined function or variable ‘cvexEstStabilizationTform’.

even though I have followed Matlab’s instruction by running a command by clicking

edit cvexEstStabilizationTform.m

Can anyone please suggest me what to do?

Kind regards

Vivian


Ashwanth Ramesh

I am trying to upload audio data into matlab using audioDatastore funtion and the same error pops up. Please help!

Screenshot (102).png


Sara Alkhaldi

The functions stepseq, impseq, and nextpow2 do not work in the MATLAB R2018B and I don’t know why. Can someone please help?

Screen Shot 2020-01-29 at 4.15.16 PM.png


abood qamar

can please help me to solve this problem


apri zulham

i need help!!

Undefined function or variable ‘imaghwinfo’.

Error in CAMERA_MATLAB>pushbutton1_Callback (line 81)

Error in gui_mainfcn (line 95)

Error in CAMERA_MATLAB (line 42)

gui_mainfcn(gui_State, varargin{:});

matlab.graphics.internal.figfile.FigFile/read>@(hObject,eventdata)CAMERA_MATLAB(‘pushbutton1_Callback’,hObject,eventdata,guidata(hObject))


CS

Undefined function or variable ‘readmatrix’.

I have a basic_matrix.txt file including

I want to read the contents of this file (basic_matrix.txt). When I write

M = readmatrix(‘basic_matrix.txt’)

MATLAB gives an error as

Undefined function or variable ‘readmatrix’.

M = readmatrix(‘basic_matrix.txt’)

Does anyone know what the reason is?

Any help would be appreciated.


Alex Backer

This happened to me with mean and median when I indvertently called it mean(variable,:) instead of mean(variable,1).


José Moctezuma Rodríguez Santillán

Undefined function or variable ‘isfile’. You cannot find the isfile function in MATLAB R2015. any alternative to replace? this is my code;

options = weboptions(‘Username’, ‘insertusername’, ‘Password’, ‘insertpassword’);

cd = day(datetime((year-1),12,31) + days(jd));

filename = [‘SST’ num2str(year) ‘_’ num2str(jd) ‘.nc’];

fprintf(‘already have the file |%s|n’,filename);

url=[‘https://data.nodc.noaa.gov/ghrsst/L4/GLOB/JPL_OUROCEAN/G1SST/2016/’ num2str(year) ‘/’ num2str(jd)];

outname=websave(filename,url,options);

fprintf(‘got weather data file |%s|n’,outname);


Yinying Wang

Help!

I received «undefined function ‘string2char’ for ‘char’ type input arguments«.

This error occurs only when I use mphload(‘filename’) in an exe file. When in a .m file this line works well. I thought maybe mphload use ‘string2char’ function whatever its input argument type is. I use mphload(«filename») instead. It still doesn’t work…


Joey Porter

Hi all,

I’ve had this error after a newly created function would give this error even though it was in the correct path and was user-defined (so no problem with needing the correct toolbox or licencing).

The name of the function and the file name you save it as MUST BE THE SAME.

I had saved my function a different name and therefore gave this error. This tip isn’t in the accepted answer’s response so give this a try.


soufiane kabiri

hi everyone, i hope you’ll help me with that

i have the same error «Undefined function or variable ‘HMMem‘»

this the code:

function [Q, g, l] = HMMbaumwelch(y, nu, tol, maxIt, Q, g)

Q = [0.8, 0.2; 0.1, 0.9];

g = [0.25 0.25 0.25 0.25; 0.05 0.05 0.45 0.45];

[x,y] = HMMsample(nu, Q, g, n);

global myfilter mysmoother

if nargin<4, maxIt = 100; end

if nargin<3, tol = 1e-4; end

k = length(nu); r = max(y); n = length(y);

Y = zeros(n, r); Y(sub2ind([n, r], 1:n, y))=1;

if nargin<5, Q = rand(k); Q = Q ./ (sum(Q, 2)*ones(1, k)); end

if nargin<6, g = rand(k, r); g = g ./ (sum(g, 2)*ones(1, r)); end

it = 0; oldQ = Q; oldg = g+tol+1;

while ((norm(oldQ(:)-Q(:), 1) + norm(oldg-g, 1) > tol) && (it<maxIt))

[phi, c] = myfilter(y, nu, Q, g);

beta = mysmoother(y, Q, g, c);

N =Q.*(phi(:, 1:(end-1))*(beta(:, 2:end).*g(:, y(2:end))./(ones(k, 1)*c(2:end)))’);

Q = N ./ (sum(N, 2) * ones(1, k));

g = M ./ (sum(M, 2) * ones(1, r));


islam dib

Undefined function or variable ‘seriallist’.

release 2013b

what’s wrong ?


AMAR Abdelhamid

hello

i have this problem :

Error using mphload

Cannot find COMSOL server

how can i sole it, please.


Muhd Farkhan

Hello, I’m having the same problem, here’s my coding

where the error is at X = data_fault; , Im still new , do teach me

autoenc = tranAutoencoder(X);

XReconstructed = predict (autoenc,X);

mseError = mse(X-XReconstructed)


Eamon Devlin

I have a probelm:

I have a list of varibles defined at the top of my script but when I am trying to create a function the defined variables (which are in the workspace too) are not being recognised.

function [r_m] = fluidcalcs()

r_m = input(‘Rate of Change of Fluid Mass (kg/s)?nn’);

disp(‘Invalid Entry — Maximum Fluid Mass is 4kgnn’);

r_m = input(‘Rate of Change of Fluid Mass (kg/s)?nn’);

In this case the ‘t_total’ variable is not being recognised. The code works fine if I replace the variable name with the value. But the varables need to be changed each time so having a set value isn’t what I want.

Any solutions?


Evelin Ponce

Maybe you should try to look for the function on the ‘Add Ons’ section so you could find the package which contains the function you need. All you have to do is to install the package.


khallad jobah

rigid3d function is not defined

my code : rigid3d(eye(3), [0 0 0])


JITHIN P M

While running a mathlab code for Beamforming am getting the error as mentiond below,

» Unrecognized function or variable ‘m_proj’ «

Anyone who knows abouth this please help me to solve the issue. Due to this error my whole work is pending. Kindly please help me out.


Feng Chen

Hi, I get the following error. Looking for solutions

Unrecognized function or variable ‘xVOCap’.

Error in YTOwrapper (line 53)

res(ii).ap_auc = xVOCap(res(ii).rec, res(ii).prec);


Rupam Jaiswal

Unrecognized function or variable ‘CentroidTermX’.

what can i do?


Arnaud Yossa potawe

Anyone who knows abouth this please help me to solve the issue. Due to this error my whole work is pending. Kindly please help me out.


MEGHA GUPTA

Unrecognized function or variable ‘gen_gfdm’ how to solve this problem in matlab simulator


Amy Morris

I am getting ‘Unrecognized function or variable ‘dicm2nii» when trying to use dicm2nii . Any suggestions for why this function isn’t working?


ABHISHEK MAURYA

while running vanet in matlab2021a in ubuntu desktop i am getting this error, I don’t have any idea why this is happenning. Any valuable suggestion is welcome. Thank you!

Checking app_wsmp2msg_mex

Checking phy_waveform2psdu_data_mex

phy_waveform2psdu_data_mex not found.

Unrecognized function or variable ‘helperSubcarrierIndices’.

Error in phy_channelpacketDetection_data (line 17)

[data,pilots] = helperSubcarrierIndices(cfgnonHT,‘HT’);

Error in fcn_codeGen (line 28)

[pktOffset,cfgnonHT,outWaveform] = phy_channelpacketDetection_data(inWaveform,SNR,PSDULength);

Error in vanet_init (line 155)

Error in fcn_runModel (line 24)

Error in vanet>runButton_Callback (line 187)

fcn_runModel(simTime,roadtype,minVehicleNum,maxVehicleNum,gap,simRound,errBar,macTXT,appTXT,mapUI)

Error in gui_mainfcn (line 95)

gui_mainfcn(gui_State, varargin{:});

Error in matlab.graphics.internal.figfile.FigFile/read>@(hObject,eventdata)vanet(‘runButton_Callback’,hObject,eventdata,guidata(hObject))

Error while evaluating UIControl Callback.


Mariya Ali

Hi!

I am getting an error calculating the lyaprosen. The error I get is

Unrecognized function or variable ‘dist’.

Error in lyaprosen (line 106)


Gonzalo Cruz Torrijos

>>fibonacci(n) Unrecognized function or variable ‘n’.


Liam Cawley

Why do I get an undefined function error when using it as function input? It’s a parameter, why would I need to initialize it? I also did intialize it but nothinh changed. Pic attached.


Kevin T

Hi!

Here is my code:

[data] = rdsamp(‘ecgfile’);

save (‘TEST101.mat’, ‘data’);

My code runs fine but when I convert my code to a executable file (.exe) and open the .exe file, it shows:

‘Undefined function ‘getWfdbClass’ for inputs arguements of type ‘char».

It seems like my .exe file doesn’t involve wfdb toolbox.

Any ideas how to solve this? I would be very grateful of any help.

Thank you!


Fatima Elmalla

I’m trying to run this code

tform=fitgeotrans(movingPoints, fixedPoints,‘affin’);

ref=imwarp(mov,tform,‘OutputView’,h);

but this error showed up :

Unrecognized function or variable ‘movingPoints’.

Error in diff_trial2 (line 15)

tform=fitgeotrans(movingPoints, fixedPoints,’affin’);

how can I solve this error?

Thanks in advance.


Indhu Priyadharshini Govindasamy

Hello @Walter Roberson,

I am trying to call matlab workspace variable in python using matlab engine API

method one

eng.eval(‘a = simout;’,nargout=0)

eng.eval(‘b = tout;’,nargout=0)

method two

mpi = eng.workspace[‘simout’]

i used these lines of code

i can get simout values in python but for tout i am getting this error

matlab.engine.MatlabExecutionError: Unrecognized function or variable ‘tout’.

could you please help me?


Taras Kryvyy

I am having a similar issue. «Unrecognized function or variable ‘bint’.» What should I install?


Ameer Zainy

Undefined function ‘math’ for input arguments of type ‘double’.


Don Roshan Sanjeewa Subasinghe

I try to run this code and got a error as:

Unrecognized function or variable ‘gg’.

train = trainRCNNObjectDetector(lable,gg,options,‘NegativeOverlapRange’,[0 0.3]);

Code:

sample1={‘stop4.jpg’;‘stop6.jpg’};

sample2={[552,220,1049,861];[666,236,1057,845]};

lable = table(sample1,sample2)

imdir = fullfile(‘D:MSC EITSEM_4ME700MatlabDeepObjects’)

options = trainingOptions(‘sgdm’,‘MiniBatchSize’,22,‘InitialLearnRate’,1e-6,‘MaxEpochs’,8)

train = trainRCNNObjectDetector(lable,gg,options,‘NegativeOverlapRange’,[0 0.3]);

[bbox,score,lable]=detect(train,a,‘MiniBatchSize’,22);

annotation=sprintf(‘%s: (Confidence=%f)’,lable(idx),score);

detectimg=insertObjectAnnotation(a,‘rectangle’,bbox,annotation)

How can i solvethis error? Please anyone help me.


Zong-Jhen Ye

Hi there,

I tried to plot by «bubblechart» and derive the error code:

Undefined function ‘bubblechart’ for input arguments of type ‘double’.

My Matlab is 2020a with the code in the end. Can anyone give me some suggestion? Maybe «bubblechart» is not available for 2020a? Thank you very much.


Ngoc Nguyen

Hello everyone,

I am trying to use function «joindata» but the outcome has an error:

>> table1=table([1;2;3],[151.04;151.08;151.11], [3.2634e+05;1.6518e+05;1.1548e+05], ‘VariableNames’, [«id», «mz», «sp58»]);

table2=table([0;1;2;4],[150.09;151.04;151.08;151.09], [217504.6;122152.8;561438.7;88868.3], ‘VariableNames’, [«id», «mz», «sp59»]);

table12 = joindata(table2,table1, ‘Keys’, [«id», «mz»]);

Undefined function or variable ‘joindata’.

I am using MATLAB (individual) version 2018b for academic use.

Can any one please help me solve this problem?

Thank you very much!


Nimit

Hello,

While using Matlab getting ‘Unrecognized function or variable ‘arena_str’. Any suggestions for why this function isn’t working?


Dam

Hello matlab community, I’m having trouble sorting out what is wrong with the following code. I keep getting the error ‘Undefined function or variable ‘timescope»

gainScope = timescope( …

‘SampleRate’,rayChan.SampleRate, …

‘TimeSpanSource’,»Property»,…

‘TimeSpan’,bitsPerFrame/2/rayChan.SampleRate, … % One frame span

‘Name’,»Multipath Gain», …

‘ChannelName’,[«Rayleigh»,»Rician»], …

‘ShowGrid’,true, …

‘YLimits’,[-40 10], …

‘YLabel’,»Gain (dB)»);

Undefined function or variable ‘timescope’.


Retech

Unrecognized function or variable ‘im_org’.


Partha Dey

I am trying to delect and classify thermal image object. I have used Deep Network Designer and trained FLIR thermal dataset using DarkNet53. Before it was working fine with public dataset but now does not work after train the private dataset. Getting same issue Unrecognized variable.

lgraph = connectLayers(lgraph,«leakyrelu50»,«res22/in1»);

lgraph = connectLayers(lgraph,«res22»,«conv51»);

lgraph = connectLayers(lgraph,«res22»,«res23/in2»);

lgraph = connectLayers(lgraph,«leakyrelu52»,«res23/in1»);

[net, traininfo] = trainNetwork(augimdsTrain,lgraph,opts);

I = imread(‘NEWFLIRPERSON1.jpg’);

I = imresize(I, [256 256]);

[YPred,probs] = classify(net,I);

Error:

Unrecognized function or variable ‘net’.

Error in TrainedNetwork (line 454)

[YPred,probs] = classify(net,I);

Can anyone please help me? Thank you in advance.


Muhammad

CL alpha dy = zeros(4,1);

v = sqrt(y(3).^2+y(4).^2);

dy(3) = -alpha*v.*(CD*y(3)+CL*y(4));

dy(4) = alpha*v.*(-CD*y(4)+CL*y(3))-g;

[T,Y] = ode45(‘ballf’,[0 2.5],[x0,z0,v0x,v0z]);

Can someone help me with this coding, Please?

I gott this coding from this website.

https://math.libretexts.org/Bookshelves/Differential_Equations/A_First_Course_in_Differential_Equations_for_Scientists_and_Engineers_(Herman)/03%3A_Numerical_Solutions/3.05%3A_Numerical_Applications/3.5.03%3A_The_Flight_of_Sports_Balls


Cathy Wong

Hi, I tried to get the value of the defined variable «‘COR’ from the MathWorks function, however, got the error message as » Unrecognized function or variable ‘COR’.»

function [wcorr,wcorrCI,Pval,NJ] = modwtcorr(w1,w2,varargin)

[Mathworks copyright code removed — see modwtcorr.m function]

Can someone please help to get the value of COR from the function? Thanks a lot.

另请参阅

类别

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

发生错误

由于页面发生更改,无法完成操作。请重新加载页面以查看其更新后的状态。

Translated by Microsoft

MATLAB error: undefined function or variable

  • MATLAB error: undefined function or variable
    • Common causes of errors
    • My solution

Recently, I was preparing for a mathematical modeling competition, and I encountered a problem in learning MATLAB:Undefined function or variable'myGcd'
MATLAB
Google tried a few solutions but still didn’t solve it.
Refer to the official documentation and found no problems (in fact, I did not see it at the beginning)
Xiaobai is really tired.

Common causes of errors

First lookMATLAB official documentation

These errors usually indicate that MATLAB cannot find a specific variable or MATLAB program file in the current directory or search path. The root cause may be one of the following reasons:

  • The name of the function is misspelled.
  • The function name is different from the name of the file containing the function.
  • The toolbox to which the function belongs is not installed.
  • The search path of the function has been changed.
  • Functions are part of your toolbox without a license.

When encountering such errors, please follow the instructions in this sectionstepTo solve the problem.

  1. Verify spelling of function name
  2. Make sure the function name matches the file name
  3. Make sure the toolbox is installed
  4. Verify the path used to access the function

There is no specific explanation here, please move to the official website for details:MATLAB-common errors when calling functions

My solution

I was a bit anxious at that time, and the documents were all skipped (I really have to look at the documents seriously!!!), I first tried steps 1, 4 and the results did not solve the problem.
 4
Finally, I settled down and looked at several scripts I wrote, which wrote two functions, one is myFun, the other is myGcd, I was thinking why my myFun can Yes, my myGcd will not work. Looked at the clues! My myGcdFunction name and file name are different! This is the second article in the help file given by MATLAB.

IChange the file name to the same as the function name and use it normally, No problem anymore!

Minor problems delay more than half a day, hey, I hope my experience will help you!

# The transpose operators

  • .' is the correct way to transpose a vector or matrix in MATLAB.
  • ' is the correct way to take the complex conjugate transpose (a.k.a. Hermitian conjugate) of a vector or matrix in MATLAB.

Note that for the transpose .', there is a period in front of the apostrophe. This is in keeping with the syntax for the other element-wise operations in MATLAB: * multiplies matrices, .* multiplies elements of matrices together. The two commands are very similar, but conceptually very distinct. Like other MATLAB commands, these operators are «syntactical sugar» that gets turned into a «proper» function call at runtime. Just as == becomes an evaluation of the eq (opens new window) function, think of .' as the shorthand for transpose (opens new window). If you would only write ' (without the point), you are in fact using the ctranspose (opens new window) command instead, which calculates the complex conjugate transpose (opens new window), which is also known as the Hermitian conjugate (opens new window), often used in physics. As long as the transposed vector or matrix is real-valued, the two operators produce the same result. But as soon as we deal with complex numbers (opens new window), we will inevitably run into problems if we do not use the «correct» shorthand. What «correct» is depends on your application.

Consider the following example of a matrix C containing complex numbers:

Let’s take the transpose using the shorthand .' (with the period). The output is as expected, the transposed form of C.

Now, let’s use ' (without the period). We see, that in addition to the transposition, the complex values have been transformed to their complex conjugates as well.

To sum up, if you intend to calculate the Hermitian conjugate, the complex conjugate transpose, then use ' (without the period). If you just want to calculate the transpose without complex-conjugating the values, use .' (with the period).

# Do not name a variable with an existing function name

There is already a function sum() (opens new window). As a result, if we name a variable with the same name

and if we try to use the function while the variable still exists in the workspace

we will get the cryptic error:

clear() (opens new window) the variable first and then use the function

How can we check if a function already exists to avoid this conflict?

Use which() (opens new window) with the -all flag:

This output is telling us that sum is first a variable and that the following methods (functions) are shadowed by it, i.e. MATLAB will first try to apply our syntax to the variable, rather than using the method.

# Be aware of floating point inaccuracy

Floating-point numbers cannot represent all real numbers. This is known as floating point inaccuracy.

There are infinitely many floating points numbers and they can be infinitely long (e.g. π), thus being able to represent them perfectly would require infinitely amount of memory. Seeing this was a problem, a special representation for «real number» storage in computer was designed, the IEEE 754 standard (opens new window). In short, it describes how computers store this type of numbers, with an exponent and mantissa, as,

floatnum = sign * 2^exponent * mantissa

With limited amount of bits for each of these, only a finite precision can be achieved. The smaller the number, smaller the gap between possible numbers (and vice versa!). You can try your real numbers in this online demo (opens new window).

Be aware of this behavior and try to avoid all floating points comparison and their use as stopping conditions in loops. See below two examples:

# Examples: Floating point comparison done WRONG:

It is poor practice to use floating point comparison as shown by the precedent example. You can overcome it by taking the absolute value of their difference and comparing it to a (small) tolerance level.

Below is another example, where a floating point number is used as a stopping condition in a while loop:**

It misses the last expected loop (0.3 <= 0.3).

# Example: Floating point comparison done RIGHT:

Several things to note:

  • As expected, now x and y are treated as equivalent.
  • In the example above, the choice of tolerance was done arbitrarily. Thus, the chosen value might not be suitable for all cases (especially when working with much smaller numbers). Choosing the bound intelligently can be done using the eps (opens new window) function, i.e. N*eps(max(x,y)), where N is some problem-specific number. A reasonable choice for N, which is also permissive enough, is 1E2 (even though, in the above problem N=1 would also suffice).

# Further reading:

See these questions for more information about floating point inaccuracy:

  • Why is 24.0000 not equal to 24.0000 in MATLAB? (opens new window)
  • Is floating point math broken? (opens new window)

# What you see is NOT what you get: char vs cellstring in the command window

This a basic example aimed at new users. It does not focus on explaining the difference between char and cellstring.

It might happen that you want to get rid of the ' in your strings, although you never added them. In fact, those are artifacts that the command window uses to distinguish between some types.

A string (opens new window) will print

A cellstring (opens new window) will print

Note how the single quotes and the indentation are artifacts to notify us that c is a cellstring rather than a char. The string is in fact contained in the cell, i.e.

# Undefined Function or Method X for Input Arguments of Type Y

This is MATLAB’s long-winded way of saying that it cannot find the function that you’re trying to call. There are a number of reasons you could get this error:

# That function was introduced after your current version of MATLAB

The MATLAB online documentation provides a very nice feature which allows you to determine in what version a given function was introduced. It is located in the bottom left of every page of the documentation:

enter image description here (opens new window)

Compare this version with your own current version (ver (opens new window)) to determine if this function is available in your particular version. If it’s not, try searching the archived versions of the documentation (opens new window) to find a suitable alternative in your version.

# You don’t have that toolbox!

The base MATLAB installation has a large number of functions; however, more specialized functionality is packaged within toolboxes and sold separately by the Mathworks. The documentation for all toolboxes is visible whether you have the toolbox or not so be sure to check and see if you have the appropriate toolbox.

To check which toolbox a given function belongs to, look to the top left of the online documentation to see if a specific toolbox is mentioned.

enter image description here (opens new window)

You can then determine which toolboxes your version of MATLAB has installed by issuing the ver (opens new window) command which will print a list of all installed toolboxes.

If you do not have that toolbox installed and want to use the function, you will need to purchase a license for that particular toolbox from The Mathworks.

# MATLAB cannot locate the function

If MATLAB still can’t find your function, then it must be a user-defined function. It is possible that it lives in another directory and that directory should be added to the search path (opens new window) for your code to run. You can check whether MATLAB can locate your function by using which (opens new window) which should return the path to the source file.

# The use of «i» or «j» as imaginary unit, loop indices or common variable.

# Recommendation

Because the symbols i and j can represent significantly different things in MATLAB, their use as loop indices has split the MATLAB user community since ages. While some historic performance reasons could help the balance lean to one side, this is no longer the case and now the choice rest entirely on you and the coding practices you choose to follow.

The current official recommendations from Mathworks are:

    — Since `i` is a function, it can be overridden and used as a variable. However, it is best to avoid using `i` and `j` for variable names if you intend to use them in complex arithmetic.
    — For speed and improved robustness in complex arithmetic, use `1i` and `1j` instead of `i` and `j`.

# Default

In MATLAB, by default, the letters i (opens new window) and j (opens new window) are built-in function names, which both refer to the imaginary unit in the complex domain.

So by default i = j = sqrt(-1).

and as you should expect:

# Using them as a variable (for loop indices or other variable)

MATLAB allows using built-in function name as a standard variable. In this case the symbol used will not point to the built-in function any more but to your own user defined variable. This practice, however, is not generally recommended as it can lead to confusion, difficult debugging and maintenance (see other example do-not-name-a-variable-with-an-existing-function-name (opens new window)).

If you are ultra pedantic about respecting conventions and best practices, you will avoid using them as loop indices in this language. However, it is allowed by the compiler and perfectly functional so you may also choose to keep old habits and use them as loop iterators.

Note that loop indices do not go out of scope at the end of the loop, so they keep their new value.

In the case you use them as variable, make sure they are initialised before they are used. In the loop above MATLAB initialise them automatically when it prepare the loop, but if not initialised properly you can quickly see that you may inadvertently introduce complex numbers in your result.

If later on, you need to undo the shadowing of the built-in function (=e.g. you want i and j to represent the imaginary unit again), you can clear the variables:

You understand now the Mathworks reservation about using them as loop indices if you intend to use them in complex arithmetic. Your code would be riddled with variable initialisations and clear commands, best way to confuse the most serious programmer (yes you there!…) and program accidents waiting to happen.

If no complex arithmetic is expected, the use of i and j is perfectly functional and there is no performance penalty.

# Using them as imaginary unit:

If your code has to deal with complex numbers, then i and j will certainly come in handy. However, for the sake of disambiguation and even for performances, it is recommended to use the full form instead of the shorthand syntax. The full form is 1i (or 1j).

They do represent the same value sqrt(-1), but the later form:

  • is more explicit, in a semantic way.
  • is more maintainable (someone looking at your code later will not
    have to read up the code to find whether i or j was a variable or
    the imaginary unit).
  • is faster (source: Mathworks).

Note that the full syntax 1i is valid with any number preceding the symbol:

This is the only function which you can stick with a number without an operator between them.

# Pitfalls

While their use as imaginary unit OR variable is perfectly legal, here is just a small example of how confusing it could get if both usages get mixed:

Let’s override i and make it a variable:

Now i is a variable (holding the value 3), but we only overrid the shorthand notation of the imaginary unit, the full form is still interpreted correctly:

Which now lets us build the most obscure formulations. I let you assess the readability of all the following constructs:

As you can see, each value in the array above return a different result. While each result is valid (provided that was the initial intent), most of you will admit that it would be a proper nightmare to read a code riddled with such constructs.

# Not enough input arguments

Often beginning MATLAB developers will use MATLAB’s editor to write and edit code, in particular custom functions with inputs and outputs. There is a Run button at the top that is available in recent versions of MATLAB:

enter image description here (opens new window)

Once the developer finishes with the code, they are often tempted to push the Run button. For some functions this will work fine, but for others they will receive a Not enough input arguments error and be puzzled about why the error occurs.

The reason why this error may not happen is because you wrote a MATLAB script or a function that takes in no input arguments. Using the Run button will run a test script or run a function assuming no input arguments. If your function requires input arguments, the Not enough input arguments error will occur as you have written a functions that expects inputs to go inside the function. Therefore, you cannot expect the function to run by simply pushing the Run button.

To demonstrate this issue, suppose we have a function mult that simply multiplies two matrices together:

In recent versions of MATLAB, if you wrote this function and pushed the Run button, it will give you the error we expect:

There are two ways to resolve this issue:

# Method #1 — Through the Command Prompt

Simply create the inputs you need in the Command Prompt, then run the function using those inputs you have created:

# Method #2 — Interactively through the Editor

Underneath the Run button, there is a dark black arrow. If you click on that arrow, you can specify the variables you would like to get from the MATLAB workspace by typing the way you want to call the function exactly as how you have seen in method #1. Be sure that the variables you are specifying inside the function exist in the MATLAB workspace:

# Using length for multidimensional arrays

A common mistake MATLAB coders have, is using the length function for matrices (as opposed to vectors, for which it is intended). The length function, as mentioned in its documentation (opens new window), «returns the length of the largest array dimension» of the input.

For vectors, the return value of length has two different meanings:

  1. The total number of elements in the vector.
  2. The largest dimension of the vector.

Unlike in vectors, the above values would not be equal for arrays of more than one non-singleton (i.e. whose size is larger than 1) dimension. This is why using length for matrices is ambiguous. Instead, using one of the following functions is encouraged, even when working with vectors, to make the intention of the code perfectly clear:

  1. size(A) (opens new window) — returns a row vector whose elements contain the amount of elements along the corresponding dimension of A.
  2. numel(A) (opens new window) — returns the number of elements in A. Equivalent to prod(size(A)).
  3. ndims(A) (opens new window) — returns the number of dimensions in the array A. Equivalent to numel(size(A)).

This is especially important when writing «future-proof», vectorized (opens new window) library functions, whose inputs are not known in advance, and can have various sizes and shapes.

# Watch out for array size changes

Some common operations in MATLAB, like differentiation or integration, output results that have a different amount of elements than the input data has. This fact can easily be overlooked, which would usually cause errors like Matrix dimensions must agree. Consider the following example:

Let’s say we want to plot these results. We take a look at the array sizes and see:

But:

The array is one element shorter!

Now imagine you have measurement data of positions over time and want to calculate jerk(t), you will get an array 3 elements less than the time array (because the jerk is the position differentiated 3 times).

And then operations like:

return errors, because the matrix dimensions do not agree.

To calculate operations like above you have to adjust the bigger array size to fit the smaller one. You could also run a regression (polyfit) with your data to get a polynomial for your data.

# Dimension Mismatch Errors

Dimension mismatch errors typically appear when:

  • Not paying attention to the shape of returned variables from function/method calls. In many inbuilt MATLAB functions, matrices are converted into vectors to speed up the calculations, and the returned variable might still be a vector rather than the matrix we expected. This is also a common scenario when logical masking (opens new window) is involved.
  • Using incompatible array sizes while invoking implicit array expansion (opens new window).

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

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

Example

This is MATLAB’s long-winded way of saying that it cannot find the function that you’re trying to call. There are a number of reasons you could get this error:

That function was introduced after your current version of MATLAB

The MATLAB online documentation provides a very nice feature which allows you to determine in what version a given function was introduced. It is located in the bottom left of every page of the documentation:

enter image description here

Compare this version with your own current version (ver) to determine if this function is available in your particular version. If it’s not, try searching the archived versions of the documentation to find a suitable alternative in your version.

You don’t have that toolbox!

The base MATLAB installation has a large number of functions; however, more specialized functionality is packaged within toolboxes and sold separately by the Mathworks. The documentation for all toolboxes is visible whether you have the toolbox or not so be sure to check and see if you have the appropriate toolbox.

To check which toolbox a given function belongs to, look to the top left of the online documentation to see if a specific toolbox is mentioned.

enter image description here

You can then determine which toolboxes your version of MATLAB has installed by issuing the ver command which will print a list of all installed toolboxes.

If you do not have that toolbox installed and want to use the function, you will need to purchase a license for that particular toolbox from The Mathworks.

MATLAB cannot locate the function

If MATLAB still can’t find your function, then it must be a user-defined function. It is possible that it lives in another directory and that directory should be added to the search path for your code to run. You can check whether MATLAB can locate your function by using which which should return the path to the source file.

Понравилась статья? Поделить с друзьями:
  • Undefined external error как исправить
  • Undefined external error fl studio
  • Undefined error telegram
  • Undefined error network error traceid не указан
  • Undefined error log