MATLAB – Функции
Функция – это группа операторов, которые вместе выполняют задачу. В MATLAB функции определены в отдельных файлах. Имя файла и функции должны совпадать.
Функции работают с переменными в их собственном рабочем пространстве, которое также называется локальным рабочим пространством , отдельно от рабочего пространства, к которому вы обращаетесь в командной строке MATLAB, которое называется базовым рабочим пространством .
Функции могут принимать более одного входного аргумента и могут возвращать более одного выходного аргумента.
Синтаксис оператора функции –
пример
Следующая функция с именем mymax должна быть записана в файл с именем mymax.m . Он принимает пять чисел в качестве аргумента и возвращает максимум чисел.
Создайте файл функции с именем mymax.m и введите в него следующий код –
Первая строка функции начинается с ключевого слова function . Это дает название функции и порядок аргументов. В нашем примере функция mymax имеет пять входных аргументов и один выходной аргумент.
Строки комментариев, которые идут сразу после оператора функции, содержат текст справки. Эти строки печатаются при вводе –
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Вы можете вызвать функцию как –
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Анонимные функции
Анонимная функция похожа на встроенную функцию в традиционных языках программирования, определенную в одной инструкции MATLAB. Он состоит из одного выражения MATLAB и любого количества входных и выходных аргументов.
Вы можете определить анонимную функцию прямо в командной строке MATLAB или в функции или скрипте.
Таким образом, вы можете создавать простые функции без необходимости создавать файл для них.
Синтаксис для создания анонимной функции из выражения:
пример
В этом примере мы напишем анонимную функцию с именем power, которая будет принимать два числа в качестве входных данных и возвращать первое число, возведенное в степень второго числа.
Создайте файл сценария и введите в нем следующий код –
Когда вы запускаете файл, он отображает –
Основные и подфункции
Любая функция, кроме анонимной, должна быть определена в файле. Каждый файл функции содержит требуемую первичную функцию, которая появляется первой, и любое количество необязательных подфункций, которые идут после основной функции и используются ею.
Первичные функции могут быть вызваны из-за пределов файла, который их определяет, либо из командной строки, либо из других функций, но подфункции не могут быть вызваны из командной строки или других функций вне файла функции.
Подфункции видны только основной функции и другим подфункциям в файле функций, который их определяет.
пример
Напишем функцию с именем quadratic, которая будет вычислять корни квадратного уравнения. Функция будет принимать три входа: квадратичный коэффициент, линейный коэффициент и постоянный член. Это вернуло бы корни.
Файл функций quadratic.m будет содержать основную функцию quadratic и вспомогательный диск , который вычисляет дискриминант.
Создайте файл функции quadratic.m и введите в него следующий код –
Вы можете вызвать вышеуказанную функцию из командной строки как –
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Вложенные функции
Вы можете определить функции в теле другой функции. Это так называемые вложенные функции. Вложенная функция содержит любой или все компоненты любой другой функции.
Вложенные функции определены в области действия другой функции и имеют общий доступ к рабочему пространству содержащей функции.
Вложенная функция имеет следующий синтаксис:
пример
Перепишем функцию quadratic из предыдущего примера, однако на этот раз функция диска будет вложенной функцией.
Создайте файл функции quadratic2.m и введите в него следующий код –
Вы можете вызвать вышеуказанную функцию из командной строки как –
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Частные функции
Закрытая функция – это основная функция, которая видна только ограниченной группе других функций. Если вы не хотите показывать реализацию функции (й), вы можете создать их как частные функции.
Закрытые функции находятся в подпапках со специальным именем private .
Они видны только функциям в родительской папке.
пример
Перепишем квадратичную функцию. На этот раз, однако, функция диска, вычисляющая дискриминант, будет частной функцией.
Создайте подпапку с именем private в рабочем каталоге. Сохраните в нем следующий файл функции disc.m –
Создайте функцию quadratic3.m в вашем рабочем каталоге и введите в нее следующий код:
Вы можете вызвать вышеуказанную функцию из командной строки как –
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Глобальные переменные
Глобальные переменные могут совместно использоваться более чем одной функцией. Для этого вам нужно объявить переменную как глобальную во всех функциях.
Если вы хотите получить доступ к этой переменной из базовой рабочей области, объявите переменную в командной строке.
Глобальное объявление должно произойти до того, как переменная будет фактически использована в функции. Рекомендуется использовать заглавные буквы для имен глобальных переменных, чтобы отличать их от других переменных.
пример
Давайте создадим файл функции с именем medium.m и наберем в нем следующий код:
Functions in MATLAB
Functions in programming languages are self-contained modules of code that accomplish a specific task. They usually (but not always) take some data as input, process the input data, and return a result. Therefore, the definition of function in programming goes far beyond the mathematical definition of a function. For example, programming functions can have no input or output.
The main reason for writing functions is to reduce coding redundancy and increase code reuse. Once a function is written, it can be used over and over and over again. Whenever a function is needed, it can be called from the inside of the main program or from inside of other functions.
In MATLAB, like most other programming languages, function is a collection of programming statements that can be executed whenever and wherever requested. Both MATLAB scripts and functions allow you to reuse sequences of commands by storing them in program files. Scripts are the simplest type of program since they store commands exactly as you would type them at the command line. Functions provide more flexibility, primarily because you can pass input values and return output values. The general syntax for a MATLAB function is the following,
The above declares a function named myfunc that accepts inputs x1. xM and returns outputs y1. yN . This declaration statement must be the first executable line of the function. Just like MATLAB variables, valid function names begin with an alphabetic character and can contain letters, numbers, or underscores.
You can save your function in,
- a function file which contains only function definitions. The name of the file should match the name of the first function in the file.
- a script file which contains commands and function definitions. Functions must be at the end of the file. This may seem a bit odd to you, if you already know other programming languages, for example, Python. Script files cannot have the same name as a function in the file. Functions in scripts are supported only in MATLAB R2016b or later.
Files can include multiple local functions or nested functions. For readability, use the optional end keyword to indicate the end of each function in a file. The end keyword is required when,
- Any function in the file contains a nested function.
- The function is a local function within a function file, and any local function in the file uses the end keyword.
- The function is a local function within a script file.
In general, it is always good to add the end keyword to all functions, for better readability.
Example
Let’s write a MATLAB function that takes in a temperature value in Centigrade and converts it to Fahrenheit.
Answer
Functions with no input arguments
We can define functions that take no input argument, yet do something predefined for us. Consider the following function which outputs information about the field of Data Science when called.
Functions with no output (return value)
We can also modify the above function such that it does not return anything specifically.
This is almost equivalent to the word void in languages like Java, C, and C++. If you set a variable equal to this function, you will get an error message, because the function does not return anything as output.
Functions with multiple input arguments
Functions can take almost as many input arguments as we wish. Consider the following that takes two arguments,
Variable number of input arguments
The functions that we have written thus far have contained a fixed number of input arguments and a fixed number of output arguments. But you can also define a MATLAB function that accepts a variable number of inputs. In this case, you use MATLAB’s builtin input argument cell varargin in place of the arbitrary number of input arguments. The function nargin returns the number of input arguments that were passed to the function. For example, consider the following function that displays the values of each input to the function,
You can find more information about input/ouput function arguments here.
Optional arguments using inputParser
Unlike other languages such as Python, Fortran, and C++, there is no simple direct way of having optional arguments in MATLAB functions, other than the one described above, using varargin . However, MATLAB has a powerful set of built-in capabilities known as inputParser for parsing the input arguments of a given function. The usage and details of this method go beyond the scope of this class. However, you can learn more about it here.
Functions with multiple output (return values)
MATLAB functions can also return more than one output value. The output could be of any type: vector, matrix, cell, structure, etc. For example, consider a function that takes an input vector of double and calculates its mean and standard deviation.
Notice that if you don’t provide two output arguments, then basically only one is reported.
Exercise
Write a function that takes in three coefficients $(a,b,c)$ of a quadratic equation $ax^2+bx+c$ and finds the roots of this equation.
Answer
Variable number of output arguments
A variable number of output arguments can also be specified. For example, consider the following function typesize() which takes one input argument inputval . The function will always return a character specifying whether the input argument was a scalar (‘s’), vector (‘v’), or matrix (‘m’). This character is returned through the output argument arrtype . Additionally, if the input argument was a vector, the function also returns the length of the vector, and if the input argument was a matrix, the function returns the number of rows and the number of columns of the matrix. The MATLAB’s builtin output argument varargout is used, which is a cell array. So, for a vector, the length is returned through varargout and for a matrix, both the number of rows and columns are returned through varargout ,
Function handles in MATLAB
Function Handles are variables that allow you to invoke a function indirectly. A function handle is a data type that stores an association to a function. For example, you can use a function handle to construct anonymous functions or specify call-back functions. Also, you can use a function handle to pass a function to another function, or call local functions from outside the main function (see below).
Indirectly calling a function enables you to invoke the function regardless of where you call it from. Typical uses of function handles include:
- Pass a function to another function (often called function functions). For example, passing a function to integration or optimization functions as we will see later in this course, such as integral and fzero .
- Construct handles to functions defined inline instead of stored in a program file (anonymous functions).
- Call local functions from outside the main function.
You can see if a variable, say h , is a function handle using isa(h,’function_handle’) .
Creating function handle
The general method for creating a function handle is to precede the function name with an @ sign. For example, if you have a function called myfunc , you can create a handle named f for it as follows,
Then you can create a function handle on MATLAB command line like the following,
If the function does not require any inputs, then you can call the function with empty parentheses. For example,
If you don’t add () at the time of call, then simply another function handle will be created, now assigned to a ,
Function handles can be passed as variables to other functions. For example, to calculate the integral of $f(x)=x^2$, as implemented in getSq() above, on the range $[0,1]$ define,
Arrays of function handles
You can also create an array of function handles by collecting them into a cell or structure array. For example,
To get general information about a function handle on MATLAB command line, use,
Function types in MATLAB
There are several types of functions in MATLAB. These include,
- local functions,
- nested functions,
- private functions,
- function functions,
- anonymous functions
- …
Anonymous functions
Anonymous functions allow you to create a MATLAB file without the need to put the function in a separate .m file dedicated to the function. This function is associated with a variable whose data type is function_handle. Anonymous functions can accept inputs and return outputs, just as standard functions do. However, they can contain only a single executable statement. The concept of the anonymous function is similar to lambda functions in Python, if you are already familiar with this language. For example, consider the following handle to an anonymous function that finds the square of a number,
Variables in anonymous function expressions
Function handles can store not only an expression but also variables that the expression requires for evaluation. For example, you can create a function handle to an anonymous function that requires coefficients a , b , and c .
Since a , b , and c are available at the time you create parabola, the function handle includes those values. The values persist within the function handle even if you clear the variables,
But note that in order to supply different values for the coefficients, you must create a new (e.g., redefine the) function handle,
Multiple (nested) anonymous functions
The expression in an anonymous function can include another anonymous function. This is useful for passing different parameters to a function that you are evaluating over a range of values. For example, suppose you want to solve the following equation for varying values of the variable c ,
You can do so by combining two anonymous functions,
Here are the steps to derive the above nested anonymous functions,
-
Write the integrand as an anonymous function,
The final function allows you to solve the equation for any value of c . For example,
Anonymous functions with no input
If your function does not require any inputs, use empty parentheses when you define and call the anonymous function. Otherwise, as stated above in function handles, you will simply create a new function handle. For example,
and omitting the parentheses in the assignment statement creates another function handle, and does not execute the function,
Anonymous functions with multiple inputs or outputs
Anonymous functions require that you explicitly specify the input arguments, as many as it may be, just the way you would for a standard function, separating multiple inputs with commas. For example, the following function accepts two inputs, x and y ,
However, you do not explicitly define output arguments when you create an anonymous function. If the expression in the function returns multiple outputs, then you can request them when you call the function. In that case, you should enclose multiple output variables in square brackets [] . For example, MATLAB’s ndgrid function can return as many outputs as the number of input vectors. This anonymous function that calls ndgrid can also return multiple outputs,
You can use the output from mygrid to create a mesh or surface plot, like the following, as we will further discuss in the future notes on plotting in MATLAB,
Arrays of anonymous functions
As we did above for MATLAB function handles, you can also store multiple anonymous functions in a cell array or structure array. The most common approach is to use a cell array, like the following,
When you create the cell array, keep in mind that MATLAB interprets spaces as column separators for the cell array. Either omit spaces from expressions, as shown in the previous code or enclose expressions in parentheses such as,
Access the contents of a cell using curly braces. For example, f <1>returns the first function handle. To execute the function, pass input values in parentheses after the curly braces,
Local functions
MATLAB program files can contain code for more than one function. In a function file, the first function in the file is called the main function. This function is visible to functions in other files, or you can call it from the command line. Additional functions within the file are called local functions, and they can occur in any order after the main function. Local functions are only visible to other functions in the same file. They are equivalent to subroutines in other programming languages and are sometimes called subfunctions.
As of R2016b, you can also create local functions in a script file, as long as they all appear after the last line of script code. For more information, see here.
Exercise
Create a function file named mystats.m that takes as input a given vector of real numbers and outputs the mean and median of the vector. The .m file for this function should contain contains a main function mystats() , and two local functions, mymean and mymedian . Test your main function using an input vector-like,
Answer
Note that you cannot call the local functions, because local functions are not visible to any other place or function in MATLAB other than mystats() .
Collective function handle for all local functions
MATLAB has a built-in function localfunctions that returns a cell array of all local functions in the scope of the current function or script (i.e., in the current MATLAB file). This is very useful when you want to write a function that returns to the main program, a list of functions local to this function. For example,
Now, if you call computeEllipseVals on the command prompt, you will get a cell array to all functions local to computeEllipseVals ,
Function functions
Function-functions are functions that operate on other functions that are passed to it as input arguments. The function that is passed to the function-function is usually referred to as passed function. A simple example is MATLAB’s built-in function fplot(func,lim) , which plots the given input function func to it within the limit lim ,
Nested functions
Nested functions, as implicitly described by their names, are completely contained within a parent function. Any function in a program file can include a nested function. For example, consider the following simple function nestedfunc() inside of its parent function parent() ,
The primary difference between nested functions and other types of functions is that they can access and modify variables that are defined in their parent functions. Therefore, nested functions can use variables that are not explicitly passed as input arguments. In a parent function, you can create a handle to a nested function that contains the data necessary to run the nested function.
Requirements for Nested Functions
- Although MATLAB functions do not typically require an end statement, to nest any function in a program file, all functions in that file must use an end statement.
When the parent function does not use a given variable, the variable remains local to the nested function. This is rather subtle and complicated. So pay attention. For example, in this function named main, the two nested functions have their own versions of externFunc that cannot interact with each other and, calling main gives a syntax error in nestedfun2 , since myvar is undefined,
However, even the slightest mention of the variable myvar , like the following, makes it accessible in the scope of both main and nested functions.
However, if there is any other function in MATLAB path that has the same name as this variable myvar , then MATLAB by default will call the function, instead of invoking the value for this variable given by the nested functions. For example, if the following function is in the MATLAB path,
then calling the same function main as above would give,
The scope of variables in MATLAB functions, especially nested functions, can become a significant source of error and confusion in your MATLAB code if you are not careful. As a result, MATLAB’s code editor has special syntax-highlighting features for variables that are shared between nested functions and is very smart in automatically detecting syntax or semantic errors in your codes. So, I always recommend you to use MATLAB’s own editor and debugger. You can find more information about this issue here.
Private Functions
A typical modern MATLAB contains thousands of M-files on the user’s path, all accessible just by typing the name of the M-file. While this ease of accessing M-files is an advantage, it can lead to clutter and clashes of names, not least due to the presence of helper functions that are used by other functions but not intended to be called directly by the user. Private functions provide an elegant way to avoid these problems. Any functions residing in a directory called private are visible only to functions in the parent directory. They can, therefore, have the same names as functions in other directories. When MATLAB looks for a function it searches subfunctions, then private functions (relative to the directory in which the function making the call is located), then the current directory and the path. Hence if a private function has the same name as a nonprivate function (even a built-in function), the private function will be found first.
Recursive functions
In programming, a recursive function is a function that calls itself. Recursion is needed frequently in programming, although there might be better, more efficient ways of implementing many of the simple explanatory recursion examples that you find in programming books. A prominent and sometimes more efficient alternative to recursive programming is iterative methods. Nontrivial examples that require recursive programming are abundant but go beyond the scope of this course.
To begin, let’s write a simple function that takes in one positive integer $n$, and calculates its factorial,