Some elements for Matlab programming Nathalie Thomas 2018 2019 Matlab, which stands for the abbreviation of MATrix LABoratory, is one of the most popular language for scientic computation. The classical applications of Matlab are : mathematical computation, algorithm development, model establishment and simulation, data analysis and virtualization, and user interface design. 1 Help commands There are some very useful instructions thereafter : lookfor keywords allows one to nd a command with the help of keywords. Example : lookfor filter. Matlab will return the list of functions whose tutorials contain this keyword. help command returns a tutorial on the required command. Contrary to lookfor, one should provide the exact command name. Example : help mean. help toolbox returns all the commands which belong to the required toolbox. Example : help signal; help stats; help optim; help nnet;. 1
2 Matrix 2.1 Construction Matlab mainly deals with matrix computations. Vectors or scalars are considered as a single row and/or a single column matrix. There are many dierent ways to dene a matrix : it can be dened by one list of elements, it can be generated dynamically using functions, or it can also be loaded from a le. The denition by a list of elements can be presented as follows : A = [1 2 3; 4 5 6; 7 8 9] This instruction will dene a 3 3 matrix and assign it to the variable A. The elements of the same row are separated by spaces or by commas, while dierent rows are separated by semicolons. Matlab can also deal with complex matrices : A = [1 2; 3 4] + i [5 6; 7 8] A = [1 + 5 i 2 + 6 i; 3 + 7 i 4 + 8 i] i or j can be used as the imaginary unit without any dierence. If they have been already used as variables, one can redene the imaginary unit : ii = sqrt( 1) The way that matrix elements are indexed can be resumed as follows : A(2, 3) is the element of the second row and third column of the matrix A. For a vector B, B(4) is the fourth element of the vector, whatever B is a row vector or a column vector. Be careful the index of element begins with 1 (not 0!!!). One can assign a scalar to one element of a matrix as follows : A(2, 4) = 8 This instruction will assign the value 8 to the element at the second row and the fourth column of the matrix A. 2
Some functions exist to create a matrix. The most commonly used are : zeros : matrix of zeros ones : matrix of ones eye : identity matrix linspace : arithmetic progressed vector logspace : logarithmic progressed vector diag : create or extract the diagonal of a matrix For example, zeros(m,n) create a m n matrix of zeros, and zeros(n) create a n n matrix of zeros. If x is a vector, diag(x) is a diagonal matrix whose diagonal elements are the elements of x (remaining elements are zeros). If A is a square matrix, diag(a) is a vector that contains the diagonal elements of A. A matrix can be also be dened by blocks. Given A a 3 3 matrix : will dene a 5 5 matrix. B = [A, zeros(3, 2); zeros(2, 3), eye(2)] Random number generator (use help stats to see the list) allows one to generate matrices whose elements follow a given distribution. For example, the command rand(n) creates a n n matrix whose elements follow the uniform distribution between 0 and 1. rand(m,n) creates a m n matrix whose elements follow the same uniform distribution. The command randn(n) creates a n n matrix whose elements follow a Gaussian distribution of mean 0 and variance 1. randn(m,n) creates a m n matrix whose elements follow the same Gaussian distribution. The notation : allows one to exploit the matrix structure of Matlab and to save loops compared with many other programming languages. For example 1:5 is the row vector [1 2 3 4 5]. Of course, the step of incrementation can be a non integer, the syntax is then start : step : (by default, the step is equal to 1). Example : 0.2:0.2:1.2 is the vector [0.2 0.4 0.6 0.8 1.0 1.2], and 5:-1:1 is [5 4 3 2 1]. 3
The notation : also allows to reach a submatrix of a given matrix. For example, A(1:4,3) is the vector composed of the rst 4 elements of the 3 rd column of the matrix A. A(:,3) is the 3 rd column of the matrix A and A(1:4,:) is composed of the rst 4 rows of A. It also permits to replace some parts of a matrix. For example, A(:,[2 4 5]) = B(:,1:3) replace the column 2, 4 and 5 of A by the rst 3 columns of B. The function reshape(a,m,n) reconstructs the matrix A with m rows et n columns. 2.2 Elementary operations Following operations are available in Matlab : + addition conj conjugate only subtraction. transpose only multiplication \ left division ˆ power / right division conjugate transpose These commands can be used on matrices but also with scalars. If the dimensions of matrices are not compatible, one error message will appear, except when one operation between a scalar and a matrix is computed (the operation will be achieved between the scalar and each element of the matrix). Warning : The matrix division is particular. Given A a matrix and b a row or column vector, x=a/b is the solution of xa=b. The left and right division are related by b/a = (A'\b')'. In order to solve this, Matlab calculates the inverse of A when A is invertible (its pseudo-inverse when A is singular) without any warnings. 2.3 Element by element operations Classical operations, like, ^, \, / can also be used element by element on a matrix or a vector by adding a dot before the operation symbol. For example : [1 2 3 4].*[1 2 3 4] or [1 2 3 4].^2 give [1 4 9 16]. 4
2.4 Elementary functions In Matlab, the common elementary functions used on matrices and vectors are : sin, cos, tan,asin, acos, atan sinh, cosh, tanh, asinh, acosh, atanh exp, log, log10 rem, abs, angle, real, imag, conj, sqrt, sign round, floor, ceil, fix Other functions give a scalar output when they take vectors as input. When we apply them on matrices, they operate on each column indepently. Therefore, the operation result is a vector. They are : max, min, sort, sum, prod, median, mean, std any, all For example, the maximal element of a matrix A is given by max(max(a)) (not by max(a) which returns a vector). 2.5 Matrix functions The most used functions are : eig eigenvalue poly det inv expm sqrtm size characteristic polynomial determinant inverse exponential matrix matrix square root size of array 3 Workspace management The following functions allow to have a global view of the workspace : who lists current variables whos what lists current variables, their dimensions and their types lists.m and.mat les The variables can be deleted using the command clear variable_name. Pay attention to the command clear which deletes all the variables within the 5
workspace. When leaving Matlab, all the variables are lost. It is possible to save them by using the command save file_name name_of_variables_to_save. The le format is then.mat. To reload variables, use load file_name. Some classical DOS or Unix commands also exist in Matlab : pwd shows the current working directory cd ls or dir what path changes the working directory lists all the les in a working directory lists the.m,.mat and.mex les in a working directory gets/sets search path The other DOS or Unix commands can be executed if they are preceded with!. Example :!del file_name. 4 Loops, tests and relations In Matlab, this type of functions operates similarly as those in C or Pascal language. But pay attention : Replace a loop by a matrix operation when it is possible, because this will reduce signicantly the computational time. 4.1 Loops The repeated execution of series of instructions can be achieved using for or while. The for loop syntax is as follows : for condition instructions For example, given n : x = [ ] for k = 1 : n %creates an empty vector x = [x k 2 ]; 6
The while loop syntax is as follows : while expression processing Processing will be repeated while the expression is true. The series of instructions to be executed can be constrained by conditions using the instructions case and otherwise. 4.2 Test : if instruction This instruction allows to execute series of conditional instructions. Its syntax is as follows : if condition instructions The processing will be executed only if the condition is true. Multiple cases are possible : if condition1 instructions1 elseif condition2 instructions else instructions 4.3 Relations The main relational operators are as follows : < smaller >= bigger or equal > bigger == equal ( = is an aectation) <= smaller or equal = dierent 7
They can be combined with the following logical operators : & and, or, not When a relation is applied to scalars, the result is then equal to 1 or 0 deping on whether it is true or false. When a relation is applied to matrices or to vectors with the same dimension, the result is a matrix whose elements are 1 or 0. A relation between matrices is interpreted by while and if as true if the condition is satised by all the elements of the matrix. Therefore, if you want to execute a processing when the matrices A and B are equal, you may do : if A = = B processing whereas if you want to execute a processing when they are not equal, if A = B processing will not return the expected result, because the processing will be executed only if all the elements of A et B are dierent. So you may write : or if any(any(a = B)) if A = = B else processing processing The functions any and all allow to solve the relations between matrices into vectors or scalars. The function find is also an interesting function : it returns the index of elements satisfying a condition. For example, given y as a vector, then find(y > 2) will return a row vector containing the index of the elements of y which are strictly bigger than 2. 8
4.4 Pause and break During the execution of a program, it is possible to susp its execution using the command pause. The execution will then continue by pressing any key. The command break stops the execution of a loop while or for. 5.m les Matlab can execute a set of instructions within a program. These programs are with the extension.m. There are two types of.m les : scripts and functions. % allows to insert comments. If the last character of an instruction is a semicolon, the output is not displayed. 5.1 Scripts A script le contains a set of Matlab instructions. If the name of a given le is prog.m, the command prog will execute it. The variables of a script le are global. The execution will change their values in the workspace. 5.2 Functions The variables of a function are local (but can be declared as global variables). The rst line of a function script should always be function [result1, result2,...] = file_name(argument1, argument2,...) Consider, for example, the function function y = mean(x) y = sum(x)/length(x); This function (saved as mean.m) computes the mean value of the elements in 9
vector x. It can be called from a.m le, for example like this : X = [1 2 3 4]; Average = mean(x); 5.3 Texts, inputs, error messages Texts should be in quotes : s = 'texte'. They can be displayed on the Matlab command window : disp( show ). Error messages can be displayed using the command error, which also stops the program at the same time : error( sorry! ). 5.4 Vectorization and pre-allocation To reduce the computational time of a program, it is important to vectorize algorithms in the.m le. In fact, Matlab can deal with matrix and vector operations instead of using loops as in other programming languages. Consider the following example : f0 = 0.2; for t = 1 : N y(t) = sin(2 pi f0 t) By vectorizing the program, it can be rewritten as : f0 = 0.2; t = 1 : N; y = sin(2 pi f0 t); When it is not possible to vectorize, it is necessary to pre-allocate the vectors or the matrices in which the results will be saved to make the loops faster. For example : y = zeros(1, 100); for (i = 1 : 100) y(i) = det(xˆi); 10
If you do not pre-allocate the vector, Matlab will refresh its dimension every loop, which is very time consuming. 6 Plots Matlab allows to display 2-D and 3-D plots. In order to have an idea of the graphical capability of Matlab, you can use the command demo but, for the signal (and also later for the telecommunication) practical work, we will essentially use 2-D plots. Given two vectors with same dimension, x and y. The command plot(x,y) will plot y as a function of x. If you want to plot a second graph in a new gure, insert the command figure or figure(i + 1) if the current gure is indexed by i. To plot several curves within the same gure, type hold on. This command can be canceled by hold off. The texts and/or labels on the axis or gures can be done using the following commands : title gure title xlabel X-axis label ylabel Y-axis label gtext places text with mouse text text annotation The command grid adds a grid on a gure. All the above commands should be typed after the command plot. By default, the curves are plotted in continuous lines, but there are other options :- -, :, -.,., +, *, o and x. Similarly, one can precise the colors using : y, m, c, r, g, b, w and k. For example, plot(x,y,'r*') will plot y as a function of x in red stars * or plot(x,y,'r-*') will plot y as a function of x with red stars * linked points. The command subplot allows one to divide one gure into several subgures : subplot(m, n, p) divides the gure window into a m n matrix of small subgures and select the p th sub-gure for the current gure. The commands semilogx and semilogy, instead of plot, allow to obtain semi-logarithmic axis. 11