MatLab for biologists Lecture 1 May 11, 2010 1 1 Start MatLab , environment, history To start MatLab type ‘matlab’, or click on its icon. 1.1 MatLab environment The following elements are the typical components of a MatLab environment: 1. Command window – interprets and executes commands 2. Command history – list of earlier commands 3. Workspace and variable editor – list and edit current variables 4. Current Directory – file/folder browser 5. Editor – create/edit/execute scripts and functions. Figure 1: Typical MatLab environment. 1.2 History MatLab stands for ”MAtrix LABoratory”1 and is a numerical computing environment. Developed by The MathWorks, MatLab allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces. MatLab was created in the late 1970s by Cleve Moler at the University of New Mexico. He designed it to give his students access to LINPACK and EISPACK without having to learn Fortran. It soon spread to other universities and found a strong audience within the applied mathematics community. Jack Little, an engineer rewrote MatLab in C and founded The MathWorks in 1984 to continue its development. 2 MatLab as a calculator MatLab can be used as a calculator with the basic arithmetic operators + * / and brackets ( ). An extra symbol, ^ can be used to compute powers; e.g. 3^3 = 27. >>4+1/2*3 ans= 5.5000 From the result we can see that the evaluation of the arithmetic operations is not directly from left to right, but some of them has higher priority. In MatLab the order of the evaluation of the most important operators is the following: 1. expressions in brackets, 2. powers, 3. * /, working left to right, 4. + -, working left to right. Therefore, the expression is evaluated as 4+3 1/1 2*2 3. What is the result of the following expressions? • 1+2^3*4/5 • 5+(4*3)^2-1 • (1+2)^3*4/4 1 Source: Wikipedia Exercise • 3*4/(4-2^2) We can separate operations/expressions using ‘,’ or ‘;’ signs. Using ‘,’ the result will be printed after the calculation, while expressions with ‘;’ will be evaluated but not written to the display, this plays important role in more difficult computations, where we can determine which results we want to visualize e.g. >>3+3, 3*10+23; 9*3.5, 23; ans= 6 ans= 31.5000 The last ‘,’ and ‘;’ can be left, the result will than be displayed. 3 Remark Data types Different data types are available in MatLab . These are: • logical • char • NUMERIC – INTEGER ∗ ∗ ∗ ∗ int8, uint8 int16, uint16 int32, uint32 int64, uint64 – REAL ∗ single ∗ double • cell The e (exponent) notation is used for very large or very small numbers e.g. -1.3412e+03 = -1.3412 ×103 = -1341.2 1.3412e-01 = 1.3412 ×101 = 0.13412 The who command shows the stored variables and the whos prints the type of them. Remark Remark 4 Variables Type the following to the command window! >>16 * 7 ans= 112 >>ans / 4 ans= 28 Here we used the output (ans) (answer) of the first calculation as a variable in the second one. To store our data and make our work much flexible we can store the numbers in variables. These variables can have different data types. Compute the size of a cell population after a given hour if the rate of growth/hour and the current size is known. >>CellNumber = 1500; GrowthRate = 5; Hours = 10; >>NewPopulation = CellNumber*(1+GrowthRate/100)^Hours NewPopulation = 2.4433e+003 Exercise The variables can be used in subsequent calculations. Assignment statements: values are assigned to variables, each variable must be assigned a value before it may be used on the right of an assignment statement. 4.1 Naming variables Variable names must begin with a letter, which may be followed by any combination of letters, digits, and underscores. MatLab distinguishes between upper and lowercase characters. Variable names can be of any length, MatLab uses only the first 63 characters of the name and ignores the rest. One can use isvarname to make sure the name is valid. The answer is 1 if the name is valid, 0 otherwise. Are the following names valid variable names in MatLab ? 21st century var.name pi hello^world is this valid Exercise 4.2 Special (reserved) names in MatLab Several names are reserved for special values. These are: ans, eps, realmax, realmin, pi, i, j, inf, NaN, computer, version. With help command we can see the corresponding description of MatLab Important Remark functions. Try: help NaN. 5 MatLab functions MatLab has many built-in functions which can be used in the following general form: function [out1 out2 ... outn ] = function name(in1 in2 ... inn ). The list of the built-in functions is huge, here we give a short and far not complete overview on them. To see the detailed description use the help function. For detailed description of MatLab functions see the following: Remark 1. help command 2. MatLab graphical help pages 3. Online help pages: http://www.mathworks.com 4. MatLab Central – open (file) exchange for the user community 5.1 Elementary mathematical functions sin, cos, tan, asin, ... trigonometric functions (radian) sqrt, mod, rem elementary mathematical functions logarithmic functions log, log10, exp Type help sind, cosd. 5.2 System functions These functions are: clear, tic, toc, format, who whos ... What is the date function for? What is the command to display the current time? 5.3 Vector and matrix functions This category manipulates vectors and matrices, detailed description see later. Some examples: inv, permute, det, min, max, mean, std,... Exercise 5.4 Special functions Special functions are built-in into MatLab or in toolboxes e.g. to manipulate images, fitting curves, solving PDE-s. 5.5 Exercises 1. We know that the longest side of a right-angle triangle is 8 cm and one angle is 33◦ . How long are the other two sides? 2. I have 20.000 CHF and I go for shopping, in the first hour I spend the half of my money, in the second hour the half of the remaining. How much money I have after 9 hours of shopping? After how many hours is my money less than 1 CHF? 6 Vectors We distinguish between row (list of numbers) and column vectors. Row vectors are lists of numbers separated by either commas or spaces. The number of entries is known as the length of the vector and the entries are often referred to as elements or components of the vector. The entries must be enclosed in square brackets. >>v1 = [5 9 log(3)], v2 = [sqrt(3) 1 0] v1 = 5.0000 9.0000 1.0986 v2 = 1.7321 1.0000 0 We can do certain arithmetic operations with vectors of the same length e.g. >>v1 + v2 ans = 6.7321 10.0000 1.0986 >>v3 = v1 + 3*v2 v3 = 10.1962 12.0000 1.0986 >>length(v3) ans = 3 Try to make arithmetic operation with vectors not in the same size. Try to multiply two vectors. We can build row vectors from existing one. >>v4 = [v1 + 3, v2] v4 = 8.0000 12.0000 4.0986 1.7321 1.0000 0 Exercise >>sort(v4) ans = 0 1.0000 1.7321 4.0986 8.0000 12.0000 Remark We can see or modify the elements of the vectors. >>v3(2) = 23 v3 = 10.1962 23.0000 1.0986 Important >>v3(3) ans = 1.0986 6.1 Creating row vectors with ‘:’ In MatLab ‘:’ is a shortcut producing row vectors. >>1:5 ans = 1 2 3 4 5 >>3:6 ans = 3 4 5 6 The general form is start : inc : stop where the vector start from start value, increases with inc and stops before left stop. inc can be negative value. >>0.32:0.1:0.6 ans = 0.3200 0.4200 0.5200 >>6:-.5:4 ans = 6.0000 5.5000 5.0000 4.5000 4.0000 6.2 Pointing parts of vectors To get the 2nd to 5th elements of v4 we can use the following: >>v4(2:5) ans = 12.0000 4.0986 1.7321 1.0000 To list every second element >>v4(1:2:6) ans = 8.0000 4.0986 1.0000 How to list the elements in a decreasing order? 6.3 Exercise Column vectors There are two ways to create column vectors. Fist we can make a similar list as in the previous case but separate the elements with ‘;’, or we can transpose row vectors with the ‘’’ command e.g. >>v5 = [2; 3; 8] v5 = 2 3 8 >>v2’ ans = 1.7321 1.0000 0 Also row vectors can be created from columns by transposing them using ‘’’. Remark 6.4 Exercises The plot command plots vectors to a graphical window. Try: >>plot(v4); >>scale= 0:0.01:2*pi; plot(sin(scale)); Compute the average cell number in a well from radius 0.5-2.5 mm in 100 µm steps if we know that the cell density in ideal case is 50 cells/mm2 but depending on the radius it is less with well radius3 * 40. Plot the values. 7 Matrices Matrix is a rectangular array of numbers. MatLab is a matrix based programming language. The row and column vectors are special cases of matrices. An m × n matrix is a set of numbers organized into a rectangular array. e.g. a matrix with m = 2 rows and n = 3 columns 2 3 −2 7 9 8 can be defined in MatLab as: >>A = [ 2 3 -2 7 9 8] A = 2 3 -2 7 9 8 An alternative way to define them is using ‘;’ rather than new lines, as: >>B = [ 4 5; 1 -7; 4 8] B = 4 5 1 -7 4 8 >>C = [ 7:13; 14:-2:2; 1:7] C = 7 8 9 10 11 12 13 14 12 10 8 6 4 2 1 2 3 4 5 6 7 7.1 Matrix functions Most of the functions work on matrices, and we should try to write our programs being compatible with this concept. We can query the size of the matrices using the size command. e.g. >>size(A), size(C) ans = 2 3 ans = 3 7 Transposing matrices works similar way as we mentioned in case of vectors. Using ‘’’, the rows becomes columns and vice versa. e.g. >>A’ ans = 2 7 3 9 -2 8 There are built-in functions in MatLab which creates special matrices. Using zeros(n, m) and ones(n, m) functions we can create n by m matrices of 0s and 1s respectively. Try what is the difference between zeros(n, 1) and zeros(n). Check in the help. Create a 10 × 10 diagonal matrix and fill the elements with the square of the numbers from 1 to 10. Use the eye and diag functions. 7.2 Exercise Exercise Building and accessing parts of matrices We can build large matrices from smaller ones. To concatenate matrices horizontally, similar to the vectors we put the matrices into ‘[]’, tabulating them with spaces or ‘,’; vertical concatenation can be done separating the elements with enter or ‘;’. The matrices have to be in the same dimension along the concatenation. e.g. >>D = [A’ C] D = 2 7 7 8 9 10 11 12 13 3 9 14 12 10 8 6 4 2 -2 8 1 2 3 4 5 6 7 >>E = [D; C A’] E = 2 7 7 8 9 10 11 12 13 3 9 14 12 10 8 6 4 2 -2 8 1 2 3 4 5 6 7 7 8 9 10 11 12 13 2 7 14 12 10 8 6 4 2 3 9 1 2 3 4 5 6 7 -2 8 To access an element of a matrix we need to give its row and column index. In MatLab the element in the ith row and jth column on matrix A can be accessed as: A(i, j). e.g. >>E(2, 3), E(5, 6) ans = 14 ans = Important 4 >>E(7, 2) ??? Index exceeds matrix dimensions. To modify the elements: >>A(2, 3) = 3 A = 2 3 -2 7 9 3 >>A(1, 1) = A(2, 3) + 5 A = 8 3 -2 7 9 3 It is possible to access not only individual elements of matrices but arbitrary sub-matrices using vectors or intervals instead of single indices. For example the list of every second elements of the 3rd line of E. >>E(3, 1:2:9) ans = -2 1 3 5 7 The stand alone ‘:’ operator substitutes a vector going from the first index to the last. e.g. >>E(:, 4) ans = 8 12 2 10 8 4 The end statement during indexing refers the last row/column of the matrix. Create the following 10 × 10 matrix and try the spy command! Remark Exercise 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 7.3 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 Arithmetic operations To calculate the dot product of matrices use ‘.*’. To element-wise add or subtract matrices we can use ‘+’/‘-’. The matrices have to be in the same size! e.g. >>A + A, A .* A To multiply matrices with vectors or other matrices we use ‘*’. e.g. >>v1=[1; 3; 6]; >>A*v1 ans = 5 52 >>A’*A ans = 113 87 5 87 90 21 5 21 13 >>A * E(2:4, 5:7) ans = 67 52 37 130 128 126 8 Script files and functions To run more commands after each other or organize computations what we use frequently in MatLab we have alternative ways. 8.1 Script files Sometimes we want to collect sequence of commands, for this MatLab offers the script files (.m). We can edit and run them on the MatLab Editor. It is also possible to run them, typing the name of the script file. Create a script which computes the body mass index (weight [kg] * height2 [m]). 8.2 MatLab functions In many cases there are sequence of operations we want to run more than once, possibly with different parameters. For this we can write our own MatLab functions. The standard definition of a function is: function [out1 out2 ... outn ] = function name(in1 in2 ... inn ), where outi and ini are the output and input variables respectively. The functions are stored in .m files, and in most of the cases the filename is the same as the function name. The input arguments can be used by referring their names, and the output variables should be created in the function. An example function which computes the body mass index: function bmi = BodyMassIndex(h, w); bmi = w / h^2; Write a function, which has one input number n, and no output. The function creates an n × n matrix, with a chessboard shape (1-white, 0-black) and plots in a graphical window! Hint: imagesc. 9 Exercise Exercise Input, output I. In the previous section we learned how to run a sequence of commands. Sometimes it is convenient or essential to read or write variables either from/to standard input or files. The input command displays a question and reads a variable from the command line. To display values or text we can use the disp command. The result of disp command and leaving the ‘;’ from the end of the commands is similar but disp does not visualizes the variable names. Remark To save and open our variables MatLab offers the save and load commands. See the help of them! 9.1 Exercises • Save the workspace to the lesson 2.mat file! • Save A, C, and E variables to matrices.mat file. Clear the workspace and load the matrices. • Write a script file, which asks the user’s height and weight and computes the body mass index, than displays the result and writes all the variables into a file. 10 Used material • An Introduction to MatLab – David F. Griffiths – University of Dundee • Using MatLab – The MathWorks, Inc. c ‘primer’ – Ernesto Di Iorio – ETH Zurich • A MatLab