MATLAB Lesson I Chiara Lelli Politecnico di Milano October 2, 2012
MATLAB MATLAB (MATrix LABoratory) is an interactive software system for: scientific computing statistical analysis vector and matrix computations graphics symbolic computation
Default interface The default view (Desktop > Default) shows the following windows: Command Window where you type the commands (the arrow keys on the keyboard allow to recover previous commands); Workspace that shows the variables currently used; Current Directory is the folder containing the scripts and functions currently saved; Command history that shows the command list of the session.
MATLAB 2006b
MATLAB 2009b
Variables allocation A variable is defined by assigning a name and a value: 1 >> a=5 2 a =5.0000 3 >> b =3; Due to the ; the value assigned to b is not shown. If you type a value or a computation without assigning a variable, the variable ans is created (and eventually overwritten): 1 >> 2*1 2 ans =2 3 >> 2+1; 4 >> ans 5 ans =3
Names of the variables The names attributed to the variables must fulfill the following criteria: Upper and lower case letters are considered different from each other (Matlab is case sensitive); The variable names must contain no more than 31 alphanumeric characters, and the first character can not be a number; The variable names can not include blanks or special characters as computation symbols (-, =, +, *), apostrophe, punctuation marks, slash or backslash.
Elementary operations By considering the previous values assigned to the variables a e b, we can compute: 1 >> a+b addition 2 ans =8 3 >> a- b subtraction 4 ans =2 5 >> a/ b division 6 ans =1.667 7 >> a* b multiplication 8 ans =15 9 >> a^b exponentiation 10 ans =125 We can compute more complicated expressions (by paying attention to the correct use of the brackets): 1 >> (((2*a-b) ^2-3) *(b^3) )/2 2 ans =621
Default variables Some real constants are already allocated: 1 >> pi 2 ans =3.1416 3 >> i 4 ans =0+1 i 5 >> inf 6 ans = Inf Default mathematical functions Function Meaning sin, cos, tan sine, cosine, tangent asin, acos, atan arcsine, arccosine, arctangent exp exponential log, log2, log10 natural logarithm, base 2, base 10 sqrt square root abs absolute value
Documentation 1 >> ver 2 --------------------- 3 MATLAB Version 7.8.0.347 (R2009a) 4 MATLAB License Number: 161051 5... ver shows the Matlab version we are working on. 1 >> help sqrt 2 SQRT Square root. 3... 4 >> doc sqrt 1 >> pwd 2 C:\ Programmi \ MATLAB \ R2006b \ work help shows how to use a function and doc displays online documentation about a command. pwd returns the name of the current directory (in this example is the default directory) ls returns the list of the files in the current directory.
Save the current data 1 >> save variables 2 >> clear all 3 >> clc 4 >> load variables The command save stores all variables from the current workspace in the MAT-file variables, clear removes the variables from the workspace, and load retrieves the data. clear all removes all the current variables; clear x removes the only variable x; clc clear the screen.
Number representation Not all real numbers are representable on a digital computer. In particular a real number is represented with finitely many terms. 1 >> 1-3*(4/3-1) 2 ans = 2.2204 e -016 Why?The number 4 3 = 1.333333... cannot be exactly represented by a binary number with finitely many terms. Some consequences are: there exists an upper limit for the modulus of the machine numbers: realmax there exists a lower limit for the modulus of the machine numbers: realmin the truncation of a real number leads to an error eps= ε M, that returns the distance from 1.0 to the next largest floating-point number. x fl(x) 1 x 2 ε M
Vectors and matrices A vector is defined as follows 1 >> v =[1 2 3] 2 v= 1 2 3 row vector A matrix is defined as follows 1 >> M=[ 1 2 ; 3 4] 2 M= 1 2 3 3 4 4 >> v1 =[10; 20] 5 v1 =10 6 20 2 2 matrix (the ; is used to start a new line) column vector Transposition, denoted by a prime after the vector variable, transforms a row vector into the corresponding column vector and viceversa: 1 >> v2=v 2 v2 =1 3 2 4 3
When we define a matrix, the dimensions of rows and columns must agree: 1 >> M1 =[1 2; 3] 2??? Error using == > vertcat 3 CAT arguments dimensions are not consistent. Some default matrices are: zeros(m, n): m n matrix with null elements ones(m, n): m n matrix with all elements equal to 1 eye(m, n): m n matrix with 1 s on the diagonal and 0 s elsewhere rand(m, n): m n matrix of random numbers 1 >> eye (3,3) 2 ans = 1 0 0 3 0 1 0 4 0 0 1
The command size returns the dimensions of a matrix or vector: 1 >> a =1; 2 >> size (a) 3 ans =1 1 a scalar is composed by 1 row and 1 column 1 >> size (v) 2 ans =1 3 In this case we can use the command length 1 >> length ( v) 2 ans =3 the vector v is composed by 1 row and 3 columns 1 >> size (M) 2 ans =2 2 matrix M is composed by 2 rows and 2 columns
Through the : we select a whole row or column of a matrix: 1 >> M (2,:) 2 ans =3 4 indicates the second row of M ( : selects all the columns) To select one element of a matrix, we must indicate the position of such an element: M(i,j) = element located in the i-th row and j-th column. 1 >> M (2,1) 2 ans =3 3 >> v1 (2) 4 ans =20 1 >> A =[1 3;5 7;9 11]; 2 >> A (2) 3 ans =5 4 >> A (3) 5 ans =9 A(i): element located in the first column and in the i-th row.
1 >> A (2:3,2) 2 ans = 7 3 11 A(i:j,k): selects the elements in the k-th column from row i to row j 1 >> A (:,2) =[1; 1; 1] 2 ans = 1 1 3 5 1 4 9 1 A(i,:)=[..] assigns new values to row i A(:,j)=[..] assigns new values to column j 1 >> A (3,:) =[] 2 ans = 1 1 3 5 1 A(i,:)=[] deletes the i-th row
Operations with matrices and vectors Product of a vector/matrix with a scalar k k x: multiplies entries of x by k Sum of vectors/matrices x + y: sums vectors/matrices componentwise Difference of vectors/matrices x y: subtracts vectors/matrices componentwise Products of vectors/matrices x. y: multiplies vectors/matrices componentwise Division of vectors/matrices x./y: divides vectors/matrices componentwise Products of a matrix with a vector A x: performs the rows by columns product (the dimensions of the factors must agree)
if and for loops if loop 1 if logical statement 2 instruction #1 3 else 4 instruction #2 5 end The first instruction is executed if the logical statement is true, otherwise the second instruction is performed. for loop 1 for variable = start : step : finish 2 instructions 3 end The for loop repeats the instructions while the variable (counter) runs its values. start and finish represent the first and the last values assumed by the counter, step is the increment on the counter value at each repetition of the loop.
Examples 1 >> A =[1 2 3;4 5 10;7 8 9]; 2 >> if (A (2,3) ~=6) 3 A (2,3) =6; 4 end 5 >> A (2,3) 6 ans =6 1 >> for i =1:2 2 for j =1:2 3 B(i,j)=i*j; 4 end 5 end 6 >> B 7 ans =1 2 8 2 4 Matlab logical operators < less than > greater than <= less or equal than >= grater or equal than == equal = different from on italian keyboards Activate BlocNum, then Alt+123.
Script When long sequences of commands must be executed many times, it is more convenient to use script and function, which are text files named with extension.m. An m-file must be saved in the same directory in which it has to be executed, or in a directory whose path is included in the list of paths automatically accessed by MATLAB. A script contains a sequence of commands that will be executed as if they were typed from the command line: x = cos(pi/4) y = sin(pi/4) quad = x x + y y diff = x y example.m A script can be created with a MATLAB editor, by typing and it runs by typing the file name on the Command Window 1 >> edit 1 >> example
Function The function is a more interactive tool since it requires the specification of a number of input arguments and produces a number of output variables. It has a more complex syntax: 1 function [ output values ]= function_name ( input values ) 2 % comments The file name where the function is saved must be equal to that of the function: function name.m. The function comments are displayed whenever typing 1 >> help function_name 2 comments While all the variables defined within a script are still defined after the script execution is over (global variables), variables defined internally to a function are deleted after the function execution is over (local variables) and only the output variables are still defined.
Example 1 function [sum,prod,diff, div ]= operations (x,y) 2 % function [sum, prod, diff, div ]= operations (x,y) 3 4 % describe the operation +,*, -,/ between 5 % two scalars x and y 6 sum =x+y; 7 prod =x*y; 8 diff =x-y; 9 div =x/y; The function runs by typing, for example: 1 >> [a,b,c, d]= operations (5,3) ; 2 >> c 3 c=2
Graphics: cartesian axes The cartesian axes are generated by defining a sequence of points x and the sequence y of the values of the function at each point x. A sequence of real numbers can be generated through 2 ways: 1 >> x=x1: step : xn; produces values between x1 and xn with the increment given by step (same syntax as the for loop); 1 >> y= linspace (x1,xn,n) produces N uniform intervals between x1 and xn. Examples: 1 >> x =(1:0.1:4) 2 x = 1.0000 3 1.1000 4 1.2000 5... 1 >> y= linspace (1,4,400) 2 x = 1.0000 3 1.0075 4 1.0150 5...
Example: plot the function x sin(x) construct the x-axis 1 >> x= linspace (0, pi,100) ; compute the function at each point and plot the pairs (x,y) 1 >> y=x.* sin (x); 2 >> plot (x, y) Main graphics options: Line color b g r... Line type - :... Marker type. x... Marker size Line width Example: 1 >> plot (x,y, --go, Markersize,3, Linewidth,2)