MBI REU Matlab Tutorial Lecturer: Reginald L. McGee II, Ph.D. June 8, 2017
MATLAB MATrix LABoratory MATLAB is a tool for numerical computation and visualization which allows Real & Complex Arithmetics Matrix Manipulations Implementations of algorithms Visualisation of data and many other things... It is language with its own grammar called SYNTAX!! It has a BIG library of built in functions! Common Math functions are listed in Tables 2.1 & 2.2 of your textbook.
MATLAB Window contains: Current Folder Workspace Command History Command Window The writing area that you will see when you start MATLAB. What do we write in Command Window? ANS: MATLAB statements, commands A MATLAB statement is the smallest piece of code which can be executed in a program.(i.e. a sentence in a natural language).
Command Window Command Window runs MATLAB interpreter. Command prompt >>: Type your statements immediately after this prompt. to execute your statement, press enter. to interupt a statement that MATLAB is running, type ctrl + c. The simplest kind of statement is a mathematical expression, which is made up of numbers, the operators + - * /ˆand functions. Ex: >> 3*(5+4) Ex: >> 3 ˆ 4
More Examples Type the following statements in command window >> 2*10 ˆ-20 >> factorial(5) >> 1/3 To learn more about MATLAB built-in functions we use help command. type >> help factorial Now, type >> format long g >> 1/3 To learn more about formatting type help format.
More Examples... Compute the values of 12, 3 40, 3 1 sine of 180, cosine of 180 radians. ln(10), log 10 (100). log 5 (6) Note: MATLAB only computes log(x) and log10(x). log(x) computes natural logarithm in MATLAB. To find any log β α you need to use the formula. log β α = log α log β
Variables A named value is called a variable. Some predefined variables in MATLAB: ans: Default variable name, when one has not been spesified pi: π, i,j: 1, Inf: Question: What is e : euler s number in MATLAB? You can also create your variables, give them names. Variable names can consist of letters, numbers, and the underscore characther. But no spaces! must begin with a letter. are case sensitive.
Examples >> my first variable=1000 >> num samples=1e5 >> err abs=abs(4-(1.91)^2) >> err rel=abs(4-(1.91)^2 )/ 4 >> ComplexExample=exp(-5i)
Examples >> my first variable=1000 >> num samples=1e5 >> err abs=abs(4-(1.91)^2) >> err rel=abs(4-(1.91)^2 )/ 4 >> ComplexExample=exp(-5i) Warning: DO NOT USE reserved matlab words when you name your variables. Ex: pi=1. Good Job... YOU LOST pi! How do we recover it? To recover pi: type clear pi To learn more about clear command, type help clear Remark: To print out the value of a variable, you can enter it alone on a line use disp()
Quick comment on numerical accuracy In MATLAB, numbers are stored to 15-16 digits of accuracy. Ex: What is the value of sin(π) analytically? Find sin(π) in MATLAB.
Useful Commands/symbols help disp(x): Display text or numeric expressions without printing the variable name. display(): Display text or numeric expressions clear: Clears variables from memory diary: Creates a diary of commands % used to indicate nonexecutable text within the body of a program ; used to allow multiple statements to be executed without printing the intermediate results input: requests user input by displaying the prompt string on the screen. who: lists all variables in the workspace
Variable Data Types Numeric types: Integers, floating-point data. By default, all numeric values are stored as double. This is the highest precision available to store a real number. Ex: Remember pi is a floating-point representation of the real number π in MATLAB. Characters and Strings: Texts are stores as char. Single quotes are the constructor symbol for MATLAB character arrays. Ex: mystring= Hello World Logicals: i.e. true/ false states Tables: arrays in tabular form. Function Handles Structures, cells, etc...
Arrays: Vectors, Matrices single number: scalars set of numbers: arrays Notation R m (C m ) denotes all real(complex) column vectors with m elements. R m n (C m n ) denotes all real(complex) m n matrices. Notation If v R m, v = (v i ), 1 i m, where v i R is called i th element(value) of v, i is called subscript/index/location/position of the element v i. Similarly, If A R m n A = (a i,j ) for 1 i m, 1 j n where a ij is the element in the ith row, jth column.
Creating Vectors & Matrices row vectors >> x=[2 3-6]; % or [2,3,-6] each element separated by spaces or commas column vectors >> w=[2;3;-6] each element separated by semicolon or >> w=[2 3-6]. = x. x. means transpose of x in MATLAB; while x is complex conjugate transpose of x. Matrices >> A=[1 2 3; 4 5 6; 7 8 9]; % or A=[1,2,3; 4,5,6; 7,8,9];
Creating Vectors & Matrices Vectors &Matrices continued You can also enter A by >> A=[1 2 3 4 5 6 7 8 9]; Here, each row is separated by ENTER. But this is in efficient. indices The i th index of x is accessed by >> x(i) The i th row j th columns of A is accessed by >> A(i,j) We can also assign values to the ith element. Ex:>> x(i)=100 Indices start at i = 1 in MATLAB (not i = 0) See arrayscript.m
Vector-Matrix Operations We can add vectors( matrices ) of the same size: R m n + R m n = R m n multipy a vector(matrix) by a constant cr m n = R m n carry out matrix-vector multiplication.(be careful: inner dimensions must agree) R m p R p n = R m n
Linear spacing Colon (:) Operator j:k is the same as [j,j+1,j+2,, j+m] with m=fix(k-j) (Returns empty if j k) j:h:k is the same as [j,j+h,j+2h,, j+mh] with m=fix((k-j)/h) Also, use colon to create a vector of indices to select rows, columns, or elements of arrays. Note: linspace(a,b,n) is also used to create arithmetic progression where a is the first, b is the last element n is the # of terms in the series
Colon operator continued Recall that A(i,:) gives you the i th row and that A(:,j) gives you the j th column. Create a random matrix A and try the operation A(:).
Vectors as indices Create a vector of length fifteen called x. >> x(4:10) %elements 4th through 10th. (1st way) >> indx=4:10; x(indx) %elements 4th through 10th. (2nd way) >> n=length(x);x(n-3:n) %last 4 elements (1st way) >> x(end-3:end) %last 4 elements (2nd way) >> x([2 7 10 11]) %2,7,10 11th elemenths
Some data manipulation functions Apply these to your original vector x. sum prod mean std var sort
Random vectors/matrices rand(), randn(),randi(), randperm() to generate uniform random numbers in the interval (a, b): >>a+(b-a)*rand(m,n); % or a+(b-a)*rand([m n])
Some common matrix tasks Extracting information from a matrix A. det trace rref lu inv eig Solving Ax = b. >> x=a\b % Gausian Elimination method >> x=inv(a)*b % Matrix inversion method. NEVER use this way because of computational cost and possible inaccuracies.
Exercises!!!
Exercise 1: Leslie Matrices Matrix algebra can be used to study the dynamics of a population of individuals in different stages. p t, a vector counting individuals of each stage class at time t The i th component, p t (i), are the counts at stage i L is the population projection matrix L ij, is the fraction of individuals that moves from stage j to stage i and so in matrix notation p t+1 = Lp t p t = L t p 0.
Exercise: Leslie Matrices 10 a. Create the initial population vector p 0 = 10 and Leslie 20 0 0.75 0.95 matrix L = 0.3 0.5 0. 0 0.7 0.65 b. Use L and p 0 to find the population vector at year 100. 59 c. If the population vector at year 11 is p 11 = 29, find the 45 population vector at year 10. Also, use L and p 0 to find the population at year 10. d. Find the total number of individuals at year 20. (Hint: Use the sum() function) e. Determine how many stages have more than 25 individuals at year 3. (Hint: Use a logical statement)
Example: Fitzhugh-Nagumo Equations This system of ordinary differential equations can be used to study population neurons and other oscillating cells. dx 1 dt = C + x 1 (x 1 α) (1 x 1 ) x 2 dx 2 dt = ɛ (x 1 γ x 2 ) See FN limitcyle.m