MATLAB Programming/Arrays
Introduction to Arrays [ edit | edit source ]
An array is the most fundamental data type in MATLAB. In MATLAB, as in many traditional languages, arrays are a collection of several values of the same type. The string and number data type formerly presented are particular cases of arrays.
A matrix is an array with two dimensions. Most arrays have the same data type; however, a cell array is an array with varying data types. If no data type is specified for numbers, then the default data type is the equivalent to the double precision floating point in the C programming language on the same architecture. For example on x86 and PowerPC a double has 64 bits.
Declaring Arrays [ edit | edit source ]
Row and Column Arrays [ edit | edit source ]
A row array is created using comma separated values inside brackets:
Sometimes commas are omitted for simple row arrays. Omitting commas is not recommended because in larger more complex arrays white-spaces can be ambiguous. Commas almost always indicate an array is horizontal.
A column array is created using semicolons to separate values:
Declaring multi-dimensional arrays [ edit | edit source ]
A two dimensional array (or a matrix) is declared with commas separating columns, and semicolons separating rows:
Simple matrix manipulation is the basis of many linear algebra computations. To use arrays of more than two dimensions, a matrix has to be extended using indexing.
When declaring arrays in MATLAB all rows and all columns need have same size. If not an error message will be generated:
Indexing Arrays [ edit | edit source ]
Arrays are indexed using integers. To return a single element in a simple array, use a single integer.
To return a single element in a two dimensional array one number as a row index and the second as a column index.
To return multiple elements in an array an array can be used as an index.
To return the last element of an array use (end).
A range of indexes can be returned using a colon(:)
Properties of MATLAB arrays and matrices [ edit | edit source ]
Contrary to low level languages such as C, an array in MATLAB is a more high level type of data: it contains various information about its size, its data type, and so on.
The number of rows and columns of the matrix can be known through the built-in size function. Following the standard mathematical convention, the first number is the number of rows and the second is the number of columns:
The goal of MATLAB arrays is to have a type similar to mathematical vectors and matrices. As such, row and column arrays are not equivalent. Mono-dimensional arrays are actually a special case of multi-dimensional arrays, and the ‘size’ function can be used for them as well.
Row and column do not have the same size, so they are not equivalent:
Why Use Arrays? [ edit | edit source ]
A major advantage of using arrays and matrices is that it lets you avoid using loops to perform the same operation on multiple elements of the array. For example, suppose you wanted to add 3 to each element of the array [1,2,3]. If MATLAB didn’t use arrays you would have to do this using a FOR loop:
Doing this is not efficient in MATLAB, and it will make your programs run very slowly. Instead, you can create another array of 3s and add the two arrays directly. MATLAB automatically separates the elements:
If all you are doing is adding a constant, you can also omit the declaration of ‘arrayofthrees’, as MATLAB will assume that the constant will be added to all elements of the array. This is very useful, for example if you use an array with variable size:
The same rule applies to scalar multiplication.
See Introduction to array operations for more information on the operations MATLAB can perform on arrays.
Arrays are a fundamental principle of MATLAB, and almost everything in MATLAB is done through a massive use of arrays. To have a deeper explanation of arrays and their operations, see Arrays and matrices.
MATLAB – Массивы
Все переменные всех типов данных в MATLAB являются многомерными массивами. Вектор – это одномерный массив, а матрица – это двумерный массив.
Мы уже обсуждали векторы и матрицы. В этой главе мы обсудим многомерные массивы. Однако перед этим давайте обсудим некоторые специальные типы массивов.
Специальные массивы в MATLAB
В этом разделе мы обсудим некоторые функции, которые создают специальные массивы. Для всех этих функций один аргумент создает квадратный массив, двойные аргументы создают прямоугольный массив.
Функция нулей () создает массив всех нулей –
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Функция ones () создает массив всех единиц –
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Функция eye () создает единичную матрицу.
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Функция rand () создает массив равномерно распределенных случайных чисел по (0,1) –
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Магический Квадрат
Магический квадрат – это квадрат, который дает одинаковую сумму, когда его элементы добавляются построчно, по столбцам или по диагонали.
Функция magic () создает массив магических квадратов. Требуется исключительный аргумент, который дает размер квадрата. Аргумент должен быть скаляром, большим или равным 3.
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Многомерные массивы
В MATLAB массив, имеющий более двух измерений, называется многомерным массивом. Многомерные массивы в MATLAB являются расширением нормальной двумерной матрицы.
Обычно для создания многомерного массива мы сначала создаем двумерный массив и расширяем его.
Например, давайте создадим двумерный массив a.
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Массив a является массивом 3 на 3; мы можем добавить третье измерение к, предоставив такие значения, как –
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Мы также можем создавать многомерные массивы, используя функции ones (), zeros () или rand ().
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Мы также можем использовать функцию cat () для построения многомерных массивов. Он объединяет список массивов по указанному измерению –
Синтаксис для функции cat () –
B – новый созданный массив
A1 , A2 , … массивы, которые будут объединены
dim – это размер, по которому объединяются массивы.
B – новый созданный массив
A1 , A2 , … массивы, которые будут объединены
dim – это размер, по которому объединяются массивы.
пример
Создайте файл сценария и введите в него следующий код –
Когда вы запускаете файл, он отображает –
Функции массива
MATLAB предоставляет следующие функции для сортировки, вращения, перестановки, изменения формы или смещения содержимого массива.
| функция | Цель |
|---|---|
| длина | Длина вектора или наибольшее измерение массива |
| ndims | Количество размеров массива |
| numel | Количество элементов массива |
| размер | Размеры массива |
| iscolumn | Определяет, является ли ввод вектором столбца |
| пустой | Определяет, является ли массив пустым |
| ismatrix | Определяет, является ли ввод матричным |
| isrow | Определяет, является ли ввод вектором строки |
| isscalar | Определяет, является ли вход скалярным |
| isvector | Определяет, является ли входной вектор |
| blkdiag | Создает блочную диагональную матрицу из входных аргументов. |
| circshift | Смещает массив по кругу |
| ctranspose | Комплексное сопряженное транспонирование |
| диаг | Диагональные матрицы и диагонали матрицы |
| flipdim | Переворачивает массив по указанному измерению |
| fliplr | Отразить матрицу слева направо |
| flipud | Переворачивает матрицу вверх-вниз |
| ipermute | Инвертирует перестановочные размеры массива ND |
| переставлять | Переставляет размеры массива ND |
| repmat | Реплики и массив плиток |
| перекроить | Перекраивает массив |
| rot90 | Поворот матрицы на 90 градусов |
| shiftdim | Смещает размеры |
| issorted | Определяет, находятся ли заданные элементы в отсортированном порядке |
| Сортировать | Сортирует элементы массива в порядке возрастания или убывания |
| sortrows | Сортирует строки в порядке возрастания |
| выжимать | Удаляет одиночные размеры |
| транспонировать | транспонировать |
| векторизовать | Векторизованное выражение |
Примеры
Следующие примеры иллюстрируют некоторые из функций, упомянутых выше.
Длина, Размер и Количество элементов –
Создайте файл сценария и введите в него следующий код –
Когда вы запускаете файл, он показывает следующий результат –
Круговое смещение элементов массива –
Создайте файл сценария и введите в него следующий код –
Когда вы запускаете файл, он показывает следующий результат –
Сортировка массивов
Создайте файл сценария и введите в него следующий код –
Когда вы запускаете файл, он показывает следующий результат –
Cell Array
Массивы ячеек – это массивы индексированных ячеек, где каждая ячейка может хранить массив разных измерений и типов данных.
Функция cell используется для создания массива cell. Синтаксис для функции ячейки –
С – массив ячеек;
dim – скалярное целое число или вектор целых чисел, который определяет размеры массива ячеек C;
dim1, …, dimN – скалярные целые числа, которые определяют размеры C;
obj является одним из следующих –
- Массив или объект Java
- .NET массив типа System.String или System.Object
С – массив ячеек;
dim – скалярное целое число или вектор целых чисел, который определяет размеры массива ячеек C;
dim1, …, dimN – скалярные целые числа, которые определяют размеры C;
obj является одним из следующих –
пример
Создайте файл сценария и введите в него следующий код –
Когда вы запускаете файл, он показывает следующий результат –
Доступ к данным в массивах ячеек
Существует два способа обращения к элементам массива ячеек:
- Заключение индексов в первую скобку () для ссылки на наборы ячеек
- Заключение индексов в фигурные скобки <> для ссылки на данные в отдельных ячейках
Когда вы заключаете индексы в первую скобку, это относится к набору ячеек.
Индексы массива ячеек в гладких скобках относятся к наборам ячеек.
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
Вы также можете получить доступ к содержимому ячеек путем индексации с помощью фигурных скобок.
MATLAB выполнит приведенный выше оператор и вернет следующий результат –
# Getting started with MATLAB Language
MATLAB allows for several methods to index (access) elements of matrices and arrays:
- Subscript indexing — where you specify the position of the elements you want in each dimension of the matrix separately.
- Linear indexing — where the matrix is treated as a vector, no matter its dimensions. That means, you specify each position in the matrix with a single number.
- Logical indexing — where you use a logical matrix (and matrix of true and false values) with the identical dimensions of the matrix you are trying to index as a mask to specify which value to return.
These three methods are now explained in more detail using the following 3-by-3 matrix M as an example:
# Subscript indexing
The most straight-forward method for accessing an element, is to specify its row-column index. For example, accessing the element on the second row and third column:
The number of subscripts provided exactly matches the number of dimensions M has (two in this example).
Note that the order of subscripts is the same as the mathematical convention: row index is the first. Moreover, MATLAB indices starts with 1 and not 0 like most programming languages.
You can index multiple elements at once by passing a vector for each coordinate instead of a single number. For example to get the entire second row, we can specify that we want the first, second and third columns:
In MATLAB, the vector [1,2,3] is more easily created using the colon operator, i.e. 1:3 . You can use this in indexing as well. To select an entire row (or column), MATLAB provides a shortcut by allowing you just specify : . For example, the following code will also return the entire second row
MATLAB also provides a shortcut for specifying the last element of a dimension in the form of the end
(opens new window) keyword. The end keyword will work exactly as if it was the number of the last element in that dimension. So if you want all the columns from column 2 to the last column, you can use write the following:
Subscript indexing can be restrictive as it will not allow to extract single values from different columns and rows; it will extract the combination of all rows and columns.
For example subscript indexing cannot extract only the elements M(2,1) or M(3,3) . To do this we must consider linear indexing.
# Linear indexing
MATLAB allows you to treat n-dimensional arrays as one-dimensional arrays when you index using only one dimension. You can directly access the first element:
Note that arrays are stored in column-major order
(opens new window) in MATLAB which means that you access the elements by first going down the columns. So M(2) is the second element of the first column which is 3 and M(4) will be the first element of the second column i.e.
There exist built-in functions in MATLAB to convert subscript indices to linear indices, and vice versa: sub2ind
(opens new window) respectively. You can manually convert the subscripts ( r , c ) to a linear index by
To understand this, if we are in the first column then the linear index will simply be the row index. The formula above holds true for this because for c == 1 , (c-1) == 0 . In the next columns, the linear index is the row number plus all the rows of the previous columns.
Note that the end keyword still applies and now refers to the very last element of the array i.e. M(end) == M(end, end) == 2 .
You can also index multiple elements using linear indexing. Note that if you do that, the returned matrix will have the same shape as the matrix of index vectors.
M(2:4) returns a row vector because 2:4 represents the row vector [2,3,4] :
As an other example, M([1,2;3,4]) returns a 2-by-2 matrix because [1,2;3,4] is a 2-by-2 matrix as well. See the below code to convince yourself:
Note that indexing with : alone will always return a column vector:
This example also illustrates the order in which MATLAB returns elements when using linear indexing.
# Logical indexing
The third method of indexing is to use a logical matrix, i.e. a matrix containing only true or false values, as a mask to filter out the elements you don’t want. For example, if we want to find all the elements of M that are greater than 5 we can use the logical matrix
to index M and return only the values that are greater than 5 as follows:
If you wanted these number to stay in place (i.e. keep the shape of the matrix), then you could assign to the logic compliment
We can reduce complicated code blocks containing if and for statements by using logical indexing.
Take the non-vectorized (already shortened to a single loop by using linear indexing):
This can be shortened to the following code using logical indexing:
Or even shorter:
# More on indexing
Higher dimension matrices
All the methods mentioned above generalize into n-dimensions. If we use the three-dimensional matrix M3 = rand(3,3,3) as an example, then you can access all the rows and columns of the second slice of the third dimension by writing
You can access the first element of the second slice using linear indexing. Linear indexing will only move on to the second slice after all the rows and all the columns of the first slice. So the linear index for that element is
In fact, in MATLAB, every matrix is n-dimensional: it just happens to be that the size of most of the other n-dimensions are one. So, if a = 2 then a(1) == 2 (as one would expect), but also a(1, 1) == 2 , as does a(1, 1, 1) == 2 , a(1, 1, 1, . 1) == 2 and so on. These "extra" dimensions (of size 1 ), are referred to as singleton dimensions. The command squeeze will remove them, and one can use permute to swap the order of dimensions around (and introduce singleton dimensions if required).
An n-dimensional matrix can also be indexed using an m subscripts (where m<=n). The rule is that the first m-1 subscripts behave ordinarily, while the last (m’th) subscript references the remaining (n-m+1) dimensions, just as a linear index would reference an (n-m+1) dimensional array. Here is an example:
Returning ranges of elements
With subscript indexing, if you specify more than one element in more than one dimension, MATLAB returns each possible pair of coordinates. For example, if you try M([1,2],[1,3]) MATLAB will return M(1,1) and M(2,3) but it will also return M(1,3) and M(2,1) . This can seem unintuitive when you are looking for the elements for a list of coordinate pairs but consider the example of a larger matrix, A = rand(20) (note A is now 20 -by- 20 ), where you want to get the top right hand quadrant. In this case instead of having to specify every coordinate pair in that quadrant (and this this case that would be 100 pairs), you just specify the 10 rows and the 10 columns you want so A(1:10, 11:end) . Slicing a matrix like this is far more common than requiring a list of coordinate pairs.
In the event that you do want to get a list of coordinate pairs, the simplest solution is to convert to linear indexing. Consider the problem where you have a vector of column indices you want returned, where each row of the vector contains the column number you want returned for the corresponding row of the matrix. For example
So in this case you actually want to get back the elements at (1,3) , (2,2) and (3,1) . So using linear indexing:
Returning an element multiple times
With subscript and linear indexing you can also return an element multiple times by repeating it’s index so
You can use this to duplicate entire rows and column for example to repeat the first row and last column
For more information, see here
# Anonymous functions and function handles
# Basics
Anonymous functions are a powerful tool of the MATLAB language. They are functions that exist locally, that is: in the current workspace. However, they do not exist on the MATLAB path like a regular function would, e.g. in an m-file. That is why they are called anonymous, although they can have a name like a variable in the workspace.
# The @ operator
Use the @ operator to create anonymous functions and function handles. For example, to create a handle to the sin function (sine) and use it as f :
Now f is a handle to the sin function. Just like (in real life) a door handle is a way to use a door, a function handle is a way to use a function. To use f , arguments are passed to it as if it were the sin function:
f accepts any input arguments the sin function accepts. If sin would be a function that accepts zero input arguments (which it does not, but others do, e.g. the peaks function), f() would be used to call it without input arguments.
# Custom anonymous functions
# Anonymous functions of one variable
It is not obviously useful to create a handle to an existing function, like sin in the example above. It is kind of redundant in that example. However, it is useful to create anonymous functions that do custom things that otherwise would need to be repeated multiple times or created a separate function for. As an example of a custom anonymous function that accepts one variable as its input, sum the sine and cosine squared of a signal:
Now f accepts one input argument called x . This was specified using parentheses (. ) directly after the @ operator. f now is an anonymous function of x : f(x) . It is used by passing a value of x to f :
A vector of values or a variable can also be passed to f , as long as they are used in a valid way within f :
# Anonymous functions of more than one variable
In the same fashion anonymous functions can be created to accept more than one variable. An example of an anonymous function that accepts three variables:
# Parameterizing anonymous functions
Variables in the workspace can be used within the definition of anonymous functions. This is called parameterizing. For example, to use a constant c = 2 in an anonymous function:
f(3) used the variable c as a parameter to multiply with the provided x . Note that if the value of c is set to something different at this point, then f(3) is called, the result would not be different. The value of c is the value at the time of creation of the anonymous function:
# Input arguments to an anonymous function do not refer to workspace variables
Note that using the name of variables in the workspace as one of the input arguments of an anonymous function (i.e., using @(. ) ) will not use those variables’ values. Instead, they are treated as different variables within the scope of the anonymous function, that is: the anonymous function has its private workspace where the input variables never refer to the variables from the main workspace. The main workspace and the anonymous function’s workspace do not know about each other’s contents. An example to illustrate this:
The value of x from the main workspace is not used within f . Also, in the main workspace x was left untouched. Within the scope of f , the variable names between parentheses after the @ operator are independent from the main workspace variables.
# Anonymous functions are stored in variables
An anonymous function (or, more precisely, the function handle pointing at an anonymous function) is stored like any other value in the current workspace: In a variable (as we did above), in a cell array ( <@(x)x.^2,@(x)x+1>), or even in a property (like h.ButtonDownFcn for interactive graphics). This means the anonymous function can be treated like any other value. When storing it in a variable, it has a name in the current workspace and can be changed and cleared just like variables holding numbers.
Put differently: A function handle (whether in the @sin form or for an anonymous function) is simply a value that can be stored in a variable, just like a numerical matrix can be.
# Advanced use
# Passing function handles to other functions
Since function handles are treated like variables, they can be passed to functions that accept function handles as input arguments.
An example: A function is created in an m-file that accepts a function handle and a scalar number. It then calls the function handle by passing 3 to it and then adds the scalar number to the result. The result is returned.
Contents of funHandleDemo.m :
Save it somewhere on the path, e.g. in MATLAB’s current folder. Now funHandleDemo can be used as follows, for example:
The handle of another existing function can be passed to funHandleDemo :
Notice how @sin was a quick way to access the sin function without first storing it in a variable using f = @sin .
# Using bsxfun , cellfun and similar functions with anonymous functions
MATLAB has some built-in functions that accept anonymous functions as an input. This is a way to perform many calculations with a minimal number of lines of code. For example bsxfun , which performs element-by-element binary operations, that is: it applies a function on two vectors or matrices in an element-by-element fashion. Normally, this would require use of for -loops, which often requires preallocation for speed. Using bsxfun this process is sped up. The following example illustrates this using tic and toc , two functions that can be used to time how long code takes. It calculates the difference of every matrix element from the matrix column mean.
Running the example above results in two outputs:
These lines come from the toc functions, which print the elapsed time since the last call to the tic function.
The bsxfun call applies the function in the first input argument to the other two input arguments. @minus is a long name for the same operation as the minus sign would do. A different anonymous function or handle ( @ ) to any other function could have been specified, as long as it accepts A and mean(A) as inputs to generate a meaningful result.
Especially for large amounts of data in large matrices, bsxfun can speed up things a lot. It also makes code look cleaner, although it might be more difficult to interpret for people who don’t know MATLAB or bsxfun . (Note that in MATLAB R2016a and later, many operations that previously used bsxfun no longer need them; A-mean(A) works directly and can in some cases be even faster.)
# Matrices and Arrays
In MATLAB, the most basic data type is the numeric array. It can be a scalar, a 1-D vector, a 2-D matrix, or an N-D multidimensional array.
To create a row vector, enter the elements inside brackets, separated by spaces or commas:
To create a column vector, separate the elements with semicolons:
To create a matrix, we enter the rows as before separated by semicolons:
Notice you cannot create a matrix with unequal row / column size. All rows must be the same length, and all columns must be the same length:
To transpose a vector or a matrix, we use the .’ -operator, or the ‘ operator to take its Hermitian conjugate, which is the complex conjugate of its transpose. For real matrices, these two are the same:
For arrays of more than two-dimensions, there is no direct language syntax to enter them literally. Instead we must use functions to construct them (such as ones , zeros , rand ) or by manipulating other arrays (using functions such as cat , reshape , permute ). Some examples:
# Cell arrays
Elements of the same class can often be concatenated into arrays (with a few rare exceptions, e.g. function handles). Numeric scalars, by default of class double , can be stored in a matrix.
Characters, which are of class char in MATLAB, can also be stored in array using similar syntax. Such an array is similar to a string in many other programming languages.
Note that despite both of them are using brackets [ and ] , the result classes are different. Therefore the operations that can be done on them are also different.
In fact, the array s is not an array of the strings ‘MATLAB ‘ , ‘is ‘ , and ‘fun’ , it is just one string — an array of 13 characters. You would get the same results if it were defined by any of the following:
A regular MATLAB vector does not let you store a mix of variables of different classes, or a few different strings. This is where the cell array comes in handy. This is an array of cells that each can contain some MATLAB object, whose class can be different in every cell if needed. Use curly braces < and >around the elements to store in a cell array.
Standard MATLAB objects of any classes can be stored together in a cell array. Note that cell arrays require more memory to store their contents.
Accessing the contents of a cell is done using curly braces < and >.
Note that C(1) is different from C <1>. Whereas the latter returns the cell’s content (and has class double in out example), the former returns a cell array which is a sub-array of C . Similarly, if D were an 10 by 5 cell array, then D(4:8,1:3) would return a sub-array of D whose size is 5 by 3 and whose class is cell . And the syntax C <1:2>does not have a single returned object, but rater it returns 2 different objects (similar to a MATLAB function with multiple return values):
# Hello World
Open a new blank document in the MATLAB Editor (in recent versions of MATLAB, do this by selecting the Home tab of the toolstrip, and clicking on New Script). The default keyboard shortcut to create a new script is Ctrl-n .
Alternatively, typing edit myscriptname.m will open the file myscriptname.m for editing, or offer to create the file if it does not exist on the MATLAB path.
In the editor, type the following:
Select the Editor tab of the toolstrip, and click Save As. Save the document to a file in the current directory called helloworld.m . Saving an untitled file will bring up a dialog box to name the file.
In the MATLAB Command Window, type the following:
You should see the following response in the MATLAB Command Window:
We see that in the Command Window, we are able to type the names of functions or script files that we have written, or that are shipped with MATLAB, to run them.
Here, we have run the ‘helloworld’ script. Notice that typing the extension ( .m ) is unnecessary. The instructions held in the script file are executed by MATLAB, here printing ‘Hello, World!’ using the disp function.
Script files can be written in this way to save a series of commands for later (re)use.
# Helping yourself
MATLAB comes with many built-in scripts and functions which range from simple multiplication to image recognition toolboxes. In order to get information about a function you want to use type: help functionname in the command line. Lets take the help function as an example.
Information on how to use it can be obtained by typing:
in the command window. This will return information of the usage of function help . If the information you are looking for is still unclear you can try the documentation page of the function. Simply type:
in the command window. This will open the browsable documentation on the page for function help providing all the information you need to understand how the ‘help’ works.
This procedure works for all built-in functions and symbols.
When developing your own functions you can let them have their own help section by adding comments at the top of the function file or just after the function declaration.
Example for a simple function multiplyby2 saved in file multiplyby2.m
This is very useful when you pick up your code weeks/months/years after having written it.
The help and doc function provide a lot of information, learning how to use those features will help you progress rapidly and use MATLAB efficiently.
# Scripts and Functions
MATLAB code can be saved in m-files to be reused. m-files have the .m extension which is automatically associated with MATLAB. An m-file can contain either a script or functions.
Scripts
Scripts are simply program files that execute a series of MATLAB commands in a predefined order.
Scripts do not accept input, nor do scripts return output. Functionally, scripts are equivalent to typing commands directly into the MATLAB command window and being able to replay them.
An example of a script:
This script will define length , width , and area in the current workspace with the value 10 , 3 , and 30 respectively.
As stated before, the above script is functionally equivalent to typing the same commands directly into the command window.
Functions
Functions, when compared to scripts, are much more flexible and extensible. Unlike scripts, functions can accept input and return output to the caller. A function has its own workspace, this means that internal operations of the functions will not change the variables from the caller.
All functions are defined with the same header format:
The function keyword begins every function header. The list of outputs follows. The list of outputs can also be a comma separated list of variables to return.
Next is the name of the function that will be used for calling. This is generally the same name as the filename. For example, we would save this function as myFunctionName.m .
Following the function name is the list of inputs. Like the outputs, this can also be a comma separated list.
We can rewrite the example script from before as a reusable function like the following:
We can call functions from other functions, or even from script files. Here is an example of our above function being used in a script file.
As before, we create l , w , and a in the workspace with the values of 100 , 20 , and 2000 respectively.
# Reading Input & Writing Output
Just like all programming language, Matlab is designed to read and write in a large variety of formats. The native library supports a large number of Text,Image,Video,Audio,Data formats with more formats included in each version update — check here
(opens new window) to see the full list of supported file formats and what function to use to import them.
Before you attempt to load in your file, you must ask yourself what do you want the data to become and how you expect the computer to organize the data for you. Say you have a txt/csv file in the following format:
We can see that the first column is in the format of Strings, while the second, third are Numeric, the last column is in the form of Currency. Let’s say we want to find how much revenue we made today using Matlab and first we want to load in this txt/csv file. After checking the link, we can see that String and Numeric type of txt files are handled by textscan . So we could try:
where %s suggest that the element is a String type, %f suggest that the element is a Float type, and that the file is Delimited by ",". The HeaderLines option asks Matlab to skip the First N lines while the 1 immediately after it means to skip the first line (the header line).
Now C is the data we have loaded which is in the form of a Cell Array of 4 cells, each containing the column of data in the txt/csv file.
So first we want to calculate how many fruits we sold today by subtracting the third column from the second column, this can be done by:
Now we want to multiply this vector by the Price per unit, so first we need to convert that column of Strings into a column of Numbers, then convert it into a Numeric Matrix using Matlab’s cell2mat the first thing we need to do is to strip-off the "$" sign, there are many ways to do this. The most direct way is using a simple regex:
Or you can use a loop:
The str2num function turns the string which had "$" signs stripped into numeric types and cell2mat turns the cell of numeric elements into a matrix of numbers
Now we we can multiply the units sold by the cost per unit:
# Data Types
(opens new window) , or classes, in MATLAB. Each of these classes is in the form of a matrix or array. With the exception of function handles, this matrix or array is a minimum of 0-by-0 in size and can grow to an n-dimensional array of any size. A function handle is always scalar (1-by-1).
Important moment in MATLAB is that you don’t need to use any type declaration or dimension statements by default. When you define new variable MATLAB creates it automatically and allocates appropriate memory space.
If the variable already exists, MATLAB replaces the original data with new one and allocates new storage space if necessary.
Fundamental data types
Fundamental data types are: numeric, logical , char , cell , struct , table and function_handle .
To store data as an integer, you need to convert from double to the desired integer type. If the number being converted to an integer has a fractional part, MATLAB rounds to the nearest integer. If the fractional part is exactly 0.5 , then from the two equally nearby integers, MATLAB chooses the one for which the absolute value is larger in magnitude.
In order to access value1, each of the following syntax are equivalent
We can explicitly access a field we know will exist with the first method, or either pass a string or create a string to access the field in the second example. The third example is demostrating that the dot parenthases notation takes a string, which is the same one stored in the field1 variable.
There are a lot of instruments to work with each data type and also built-in data type conversion functions
Additional data types
There are several additional data types which are useful in some specific cases. They are:
Date and time: arrays to represent dates, time, and duration. `datetime(‘now’)` returns `21-Jul-2016 16:30:16`.
Arrays¶
To create a row vector, type the elements with a space or a comma between the elements inside the square brackets:
In the above example, we have created two vectors:
has size 1 by 4 and
has size 1 by 2.
The following example shows us how to create a column vector. We enter the elements with a semicolon between them and type the square brackets on the left and right:
Using whos command followed by a name of variable, will give us only the information of that variable. Here the vector z is 4 by 1.
Creating a vector with constant spacing¶
A vector in which the first element is x0, the last element is xn and the number of elements is n is created by typing the linspace command:
Another way to create a vector with a constant spacing is to type the first element, follow by a colon (:), the specified stepsize, colon, and then the last element. This way, the number of elements vary upon the chosen stepsize:
Note that the linspace and the above example return a row vector.
Creating matrices¶
A matrix is created by typing the elements, row by row, inside square brackets []. For example, we assign a matrix to variable x:
Command
Refer to
For a matrix
| Command | Refer to |
|---|---|
| A(:,n) | the elements in all the rows of column n |
| A(n,:) | the elements in all the columns of row n |
| A(:,m:n) | the elements in all the rows between columns m and n |
| A(m,n,:) | the elements in all the columns between rows m and n |
| A(m:n,p:q) | the elements in rows m through n and columns p through q |
| A(:) | vectorize the matrix A into a vector |
Using the matrix A from the previous example, we can demonstrate the use of colon as follows:
It is possible to select only specific elements of a vector by typing the selected elements inside brackets:
In the above example, we wanted to select only the 5th, the second and the last elements of x, and arrange them into a new vector u.
Similarly, to select specific rows and columns of a matrix, we type the selected rows and columns inside brackets, as shown below:
The above example shows how to create a matrix D as a stack of 4 row vectors. The matrix F is created from the 1st and 3rd rows, and the 1st, 3rd, and 5th through 7th columns of D.
Deleting and Adding Elements¶
A single element of a vector, or a range of elements of a matrix, can be deleted by assigning a null value ( [ ] ). The resulting vector, or matrix will have smaller size. Examples are:
In the first example, a vector y of size 1 by 6 was created. Then we removed the 4th element and y becomes a vector of size 1 by 5. The last expression was to remove the 2nd through the 4th elements of y. The next example shows how to delete elements in a matrix:
Similarly, we created a matrix of size 3 by 4. First we removed all rows corresponding to the 1st and 4th columns of Z. Then we deleted all columns corresponding to the 3rd row of Z.
A vector can be made longer by assigning values to the new elements. For example, a vector has 4 elements and we add elements 5,6. 10:
If a vector has n elements and a new value is assigned to an element with address of n+2, or larger, MATLAB assigns zeros to the elements that are between the last original element and the new element:
Rows and columns can be added to an existing matrix by assigning new values or by appending existing variables. For example, we add a new row to the matrix E:
Now we define a new matrix with the same number of rows as E, and concate it to E:
S becomes a matrix of size 3 by 5 now. If a matrix of size m by n is assigned a new element with an address beyond its size, MATLAB increase the size to include the new element. Zeros are assigned to the other elements that are added. For example:
Built-in functions for matrices¶
length(A) returns the number of elements in the vector A:
size(A) returns a row vector [m,n] , where m and n are the size of the matrix A:
reshape(A,m,n) rearrange a matrix A that has r rows and s columns to have m rows and n columns, where r times s must be equal to m times n :
diag(a) when a is a vector, creates a square matrix with the elements of a in the diagonal:
diag(A) when A is a square matrix, creats a vector from the diagonal elements of A :
sum(a) when a is a vector, returns the summation of all elements in a :
For an m by n matrix A, sum(A,1) returns a row vector whose elements are the summation of all entries in each column. Likewise, sum(A,2) returns a column vector whose elements are the summation of all entries in each row:
More built-in functions can be explored by typing help elmat .
Examples¶
| Function | Description |
|---|---|
| mean(a) | the mean value of the elements of a |
| var(a) | the variance of the elements of a |
| max(a) | the largest element of a |
| min(a) | the smallest element of a |
| sort(a) | arranges the elements of the vector in ascending order |
| dot(a,b) | the scalar product (dot) product of two vectors |
| prod(a) | the product of elements in a |
| diff(a) | the difference between subsequent elements of a |
Array operations¶
Addition, subtraction, and multiplication operations in matrices and vectors can be performed by using + - * commands respectively. However, we should keep in mind that the dimension of arrays must agree in any operations:
Transpose operator¶
The matrix transpose operator can be performed by using the single quote (‘) command:
Array division¶
The division operation can be explained through the concept of the inverse of a matrix. We say the matrix B is the inverse of the matrix A if

The inverse of a (square) matrix A is typically written as
for each element.
Left division ¶
The left division is used to solve the matrix equation
. In this equation, x and b are columns vectors and A is a square matrix. If A is invertible, the solution is given by
. In this equation
are row vectors. The solution of this equation is given by
(magnitude) of a vector
of the vectors. Verify the answer with the command dot (for instruction type help dot ).
- Use MATLAB to show that the sum of the infinite series
.