Sapienza University of Rome Department of economics and law Advanced Monetary Theory and Policy EPOS 2013/14 Getting started with MATLAB Giovanni Di Bartolomeo giovanni.dibartolomeo@uniroma1.it
Outline What is MATLAB? MATLAB screen Operators (arithmetic, relational, logical ) Variables, array, matrix, indexing Display facilities Using of m-file (scripts) Flow control Writing user defined functions Basic statistics with MATLAB
What is MATLAB? MATrix LABoratory: MATLAB is a program for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices. It s name is derived from MATrix LABoratory. MATLAB has since been expanded and now has built-in functions for solving problems requiring data analysis, signal processing, optimization, and several other types of scientific computations.
Command Window MATLAB Desktop type commands clc: clear command window Workspace view program variables clear to clear (clear all: removes all variables, globals, functions and MEX links) double click on a variable to see it in the Array Editor Command History view past commands Launch Pad access help, tools, demos and documentation
MATLAB Desktop Launch Pad Current Directory Command Window Workspace History
Command window The MATLAB environment is command oriented. A prompt (>>) appears on the screen and a MATLAB statement can be entered. <ENTER> key is pressed the statement is executed, and another prompt appears. If a statement is terminated with a semicolon ( ; ), no results will be displayed. Otherwise results will appear before the next prompt. assign operator Matlab prompt» a=5;» b=a/2 b = 2.5000» suppress command output
MATLAB Desktop Launch Pad Workspace Current DIrectory Command Window History
How to resume default Desktop 8
MATLAB Help Different ways to find information help help general, help mean, sqrt... helpdesk - an html document with links to further information
MATLAB Help
MATLAB Help
Some useful MATLAB commands who List known variables whos List known variables plus their size help >> help sqrt Help on using sqrt lookfor >> lookfor sqrt Search for keyword sqrt in on MATLABPATH. what >> what ('directory') List MATLAB files in directory clear Clear all variables from work space clear x y Clear variables x and y from work space clc Clear the command window
Some useful MATLAB commands dir List all files in current directory ls Same as dir type test Display the content of test.m in command window delete test Delete test.m cd a: Change directory to a: chdir a: Same as cd pwd Show current directory which test Display directory path to closest test.m
MATLAB Help Different ways to find information help help general, help mean, sqrt... helpdesk - an html document with links to further information
MATLAB variable names Variable names ARE case sensitive Variable names can contain up to 63 characters Variable names must start with a letter followed by letters, digits, and underscores.
MATLAB special variables ans Default variable name for results pi Value of inf Infinity NaN Not a number e.g. 0/0 i and j i=j=square root of minus one: (-1) (imaginary number) e.g. sqrt(-1) ans= 0 + 1.0000i realmin The smallest usable positive real number realmax The largest usable positive real number
Reserved words MATLAB has some special (reserved) words that you may not use, for example, for end if while function return elseif case otherwise switch continue else try catch global persistent break
Operators Power ^ or.^ a^b or a.^b Multiplication * (matrix multiply) or.* (array multiply) a*b or a.*b Division / or./ a/b or a./b \ or.\ b\a or b.\a Note that: 56/8 = 8\56 Addition + a + b Subtraction - a b Assignment = a = b (assign b to a)
Operators (Element by Element) E.g., A.*B, A./B, A.^B.* element-by-element multiplication./ element-by-element division.^ element-by-element power And element-by-element for + and -?
MATLAB operators MATLAB supports six relational operators. Less Than < Less Than or Equal <= Greater Than > Greater Than or Equal >= Equal To == Not Equal To ~= MATLAB supports three logical operators. not ~ % highest precedence and & % equal precedence with or or % equal precedence with and
MATLAB matrices MATLAB works with essentially only one kind of object, a rectangular numerical matrix MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, that is how it is stored. Vectors are special forms of matrices and contain only one row OR one column. Scalars are matrices with only one row AND one column
Matrices Don t need to initialise type, or dimensions >>A = [3 2 1; 5 1 0; 2 1 7] A = >> 3 2 1 5 1 0 2 1 7 square brackets to define matrices semicolon for next row in matrix
Manipulating matrices >> A ' % transpose >> B*A % matrix multiplication >> B.*A % element by element multiplication >> B/A % matrix division >> B./A % element by element division >> [B A] % Join matrices (horizontally) >> [B; A] % Join matrices (vertically) Input two matrices and try the above expression [be careful at the matrix conformability] Note: % is the neglect sign for MATLAB. Anything after it on the same line is neglected by MATLAB compiler. Sometimes slowing down the execution is done deliberately for observation purposes. You can use the command pause for this purpose
MATLAB matrices A matrix with only one row AND one column is a scalar. A scalar can be created in MATLAB as follows:» a_value=23 a_value = 23
MATLAB matrices A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas):» rowvec = [12, 14, 63] or rowvec = [12 14 63] rowvec = 12 14 63
MATLAB matrices A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons):» colvec = [13 ; 45 ; -2] colvec = 13 45-2
MATLAB matrices A matrix can be created in MATLAB as follows (note the commas AND semicolons):» matrix = [1, 2, 3 ; 4, 5,6 ; 7, 8, 9] matrix = 1 2 3 4 5 6 7 8 9
Extracting a sub-matrix A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of both matrices, the rows and columns. The syntax is: sub_matrix = matrix( r1 : r2, c1 : c2 ); where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and ending columns to be extracted to make the new matrix.
A vector» x = [1 2 5 1] x = Matrices transpose 1 2 5 1 Transpose» y = x y = 1 2 5 1
[ ] concatenation Other operators» x = [ zeros(1,3) ones(1,2) ] x = 0 0 0 1 1 ( ) subscription» x = [ 1 3 5 7 9] x = 1 3 5 7 9» y = x(2) y = 3» y = x(2:4) y = 3 5 7
Long array» t =1:10 t = 10 1 2 3 4 5 6 7 8 9» k =2:-0.5:-1 k = 2 1.5 1 0.5 0-0.5-1» B = [1:4; 5:8] x = 1 2 3 4 5 6 7 8
Generating vectors from functions zeros(m,n) MxN matrix of zeros x = zeros(1,3) x = 0 0 0 ones(m,n) MxN matrix of ones x = ones(1,3) x = 1 1 1 rand(m,n) MxN matrix of uniformly distributed random numbers on (0,1) x = rand(1,3) x = 0.9501 0.2311 0.6068
Scalar Matrix addition» a=3;» b=[1, 2, 3;4, 5, 6] b = 1 2 3 4 5 6» c= b+a % Add a to each element of b c = 4 5 6 7 8 9 The same can be done for -, *, /
Graph functions plot linear plot stem discrete plot grid add grid lines xlabel add X-axis label ylabel add Y-axis label title add graph title subplot divide figure window figure create new figure window pause wait for user response
MATLAB graphics x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x = 0:2\pi') ylabel('sine of x') title('plot of the Sine Function')
Multiple graphs t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2) grid on
Multiple plots t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); subplot(2,2,1) plot(t,y1) subplot(2,2,2) plot(t,y2)
MATLAB editor Scripts (m-files) Use scripts to execute a series of MATLAB commands Matlab Desktop Press to create new m-file in the matlab editor
Use of m-file If you include ; at the end of each statement, result will not be shown immediately
Control and flow Control flow capability enables MATLAB to function beyond the level of a simple desk calculator With control flow statements, MATLAB can be used as a complete high-level matrix language Flow control in MATLAB is performed with condition statements and loops Flow controls if for while break.
Flow control It is often necessary to only perform MATLAB operations when certain conditions are met Relational and Logical operators are used to define specific conditions Simple flow control in MATLAB is performed with the If, Else, Elseif and Switch statements
If, Else, and Elseif An if statement evaluates a logical expression and evaluates a group of commands when the logical expression is true The list of conditional commands are terminated by the end statement If the logical expression is false, all the conditional commands are skipped Execution of the script resumes after the end statement Basic form: if logical_expression commands end
A = 6 B = 0 if A > 3 D = [1 2 6] A = A + 1 elseif A > 2 D = D + 1 A = A + 2 end Example
Switch The switch statement can act as many elseif statements Only the one case statement who s value satisfies the original expression is evaluated Basic form: switch expression (scalar or string) end case value 1 case value 2 case value n commands 1 commands 2 commands n
A = 6 B = 0 switch A case 4 D = [ 0 0 0] A = A - 1 case 5 B = 1 case 6 D = [1 2 6] A = A + 1 end Example
Loops Loops are an important component of flow control that enables MATLAB to repeat multiple statements in specific and controllable ways Simple repetition in MATLAB is controlled by two types of loops: For loops While loops
For Loops The for loop executes a statement or group of statements a predetermined number of times Basic Form: for index = start:increment:end end Example: statements for i = 1:1:100 end x(i) = 0 Assigns 0 to the first 100 elements of vector x If x does not exist or has fewer than 100 elements, additional space will be automatically allocated
Loops can be nested in other loops We can create an m by n matrix A whose elements are the sum of their matrix position A = [ ] for i = 1:m for j = 1:n A(i,j) = i + j end end
While Loops The while loop executes a statement or group of statements repeatedly as long as the controlling expression is true Examples: Basic Form: while expression end A = 6 B = 15 while A > 0 & B < 10 end A = A + 1 B = B 2 statements Iteratively increase A and decrease B until the two conditions of the while loop are met Be very careful to ensure that your while loop will eventually reach its termination condition to prevent an infinite loop
Breaking out of loops!!! The break command terminates a for and while loop. When a break is encountered by MATLAB, execution of the script continues outside and after the loop A = 6 B = 15 count = 1 while A > 0 & B < 10 A = A + 1 B = B + 2 count = count + 1 if count > 100 break end end In the example: Break out of the loop after 100 repetitions if the while condition has not been met
Programming in MATLAB: Functions Users can write functions which can be called from the command line. Functions can accept input variables/matrices and will output variables/matrices. Functions will not manipulate variables/matrices in the MATLAB Workspace. In MATLAB functions closely resemble scripts and can be written in the MATLAB editor. MATLAB functions have the function (protected) keyword. Remember that the filename of a function will be its calling function name. Don t overload any built-in functions by using the same filename for your functions or scripts!
Writing user defined functions Functions are m-files which can be executed by specifying some inputs and supply some desired outputs. The code telling the MATLAB that an m-file is actually a function is function out1=functionname(in1) function out1=functionname(in1,in2,in3) function [out1,out2]=functionname(in1,in2) You should write this command at the beginning of the m-file and you should save the m-file with a file name same as the function name input Function output
Writing user defined functions: Example Write a function: out=squarer (A, ind) Which takes the square of the input matrix if the input indicator is equal to 1 And takes the element by element square of the input matrix if the input indicator is equal to 2 Same Name
Writing user defined functions: Examples Another function which takes an input array and returns the sum and product of its elements as outputs The function sumprod(.) can be called from command window or an m-file as
Writing user defined functions: Example Try the function!!! >> I=iterate(5) I = 1 4 9 16 25 output function name input function keyword help lines for function for statement block Access the comments of your MATLAB functions >> help iterate Make sure you save changes to the m-file before you call the function!
Useful commands The two commands used most by MATLAB users are >>help functionname >>lookfor keyword
Writing user defined functions: Example >> [i j]=sort2(2,4) i = 4 j = 2 >> Functions can have many outputs contained in a matrix if statement block
Statistics The MATLAB installation contains basic statistical tools. Including, mean, median, standard deviation, error variance, and correlations More advanced statistics are available from the statistics toolbox and include parametric and non-parametric comparisons, analysis of variance and curve fitting tools Here we will concentrate on some of the most commonly used statistics for research Parametric and non-parametric comparisons Curve Fitting
Mean and median Mean: Average or mean value of a distribution Median: Middle value of a sorted distribution M = mean(a), M = median(a) M = mean(a,dim), M = median(a,dim) M = mean(a), M = median(a): Returns the mean or median value of vector A. If A is a multidimensional mean/median returns an array of mean values.
Example A = [ 0 2 5 7 20] B = [ 1 2 3 3 3 6 4 6 8 4 7 7]; mean(a) = 6.8 mean(b) = 3.0000 4.5000 6.0000 (column-wise mean) mean(b,2) = 2.0000 4.0000 6.0000 6.0000 (row-wise mean)
Standard deviation and variance Standard deviation is calculated using the std() function std(x) : Calcuate the standard deviation of vector x If x is a matrix, std() will return the standard deviation of each column Variance (defined as the square of the standard deviation) is calculated using the var() function var(x) : Calcuate the variance of vector x If x is a matrix, var() will return the standard deviation of each column
Correlation MATLAB can calculate statistical correlations using the corrcoef() function [R,P] = corrcoef(a,b) Calculates a matrix of R correlation coefficiencts and P significance values (95% confidence intervals) for variables A and B A B R = A AcorA BcorA B AcorB BcorB
Comparison of means A wide variety of mathematical methods exist for determining whether the means of different groups are statistically different Methods for comparing means can be either parametric (assumes data is normally distributed) or non-parametric (does not assume normal distribution)
[H,P] = ttest2(x,y) Parametric tests TTEST Determines whether the means from matrices X and Y are statistically different. H return a 0 or 1 indicating accept or reject nul hypothesis (that the means are the same) P will return the significance level
Parametric Tests TTEST [H,P] = ttest2(x,y) Determines whether the means from matrices X and Y are statistically different. H return a 0 or 1 indicating accept or reject nul hypothesis (that the means are the same) P will return the significance level Example >>[H,P] = ttest2(var1,var2) H =1 P = 0.00000000000014877 5 4 3 2 1 0-1 -2-3 -4-3 -2-1 0 1 2 3
Curve fitting Plotting a line of best fit in MATLAB can be performed using either a traditional least squares fit or a robust fitting method. 12 10 8 6 4 2 Least squares Robust A least squares linear fit minimizes the square of the distance between every data point and the line of best fit P = robustfit(x,y) returns the vector B of the y intercept and slope, obtained by performing robust linear fit 0-2 1 2 3 4 5 6 7 8 9 10