What is MATLAB? MATLAB PROGRAMMING Stands for MATrix LABoratory A software built around vectors and matrices A great tool for numerical computation of mathematical problems, such as Calculus Has powerful graphic tools; pictures in 2D/3D Is a programming language Close to scripting language, has structures such as looping, function calls 1 2 What is MATLAB? A programming environment Many toolboxes (signal processing, image processing, ) and simulation tools (Simulink) An application development tool MATLAB programs can be exported to become an application Graphical user interfaces can be developed under MATLAB to allow interaction with Programming Environment Directory, workspace, etc. Command History Window Command Window user 3 4
Using MATLAB as a calculator Built-in operators and functions Command Window Giving commands to MATLAB E.g., evaluate mathematical expressions using the MATLAB programming syntax Compute 5sin(2.5 3- )+1/75 Type Command prompt Constants Operators Function 5 Operation, function or constant MATLAB command Operation, function or constant MATLAB command + (addition) + sin x sin(x) -(subtraction) - cos x cos(x) (multiplication) * tan x tan(x) / (division) / cot x cot(x) x (absolute value of abs(x) arcsin x asin(x) x) square root of x sqrt(x) arccos x acos(x) e x exp(x) arctan x atan(x) ln x (natural log) log(x) arccot x acot(x) log 10 x (base 10 log) log10(x) n! (n factorial) gamma(n+1) p (3.14159265...) pi e (2.71828...) exp(1) i (imaginary unit, i sqrt(-1)) 6 Built-in operators and functions Vectors and Matrices Type help to find out information of MATLAB functions MATLAB is tailor-designed for vector and matrix operations To define a vector: x = [ 1 2 3 4 5 6 7 8 9 10]; 7 A variable with name x A vector with 10 elements. The number is the value of each element We often use a ; at the end of each statement. Without it, MATLAB will echo your statement when you hit return 8
Matrix Form (1) 2x+3y=9 x-2y=-13 (3) 6x+y=9-5x-3y=7 3x-10y=-4 2 3 x 9 1 2 y 13 22 21 21 6 1 9 x 5 3 7 y 3 10 4 21 32 31 9 A Matrix Multiplication 4 10 3 4 B 3 8 Check the size first A: 1 x 3 B: 3 x 1 AB 1x1 (a scalar) AB = 4(-4) + (-10)(3) + 3(8) = -22 BA: 3 x 3 4 16 40 12 BA 3 4 10 3 12 30 9 8 32 80 24 10 Matrix Multiplication Matrix Multiplication 8 5 3 1 3 0 4 3 10 2 A C 2 5 8 9 2 0 4 1 7 5 AC=? A: 2 x 4, C: 4x3 AC: 2 x 3 8 5 3 1 3 0 4 3 10 2 13 53 17 AC 2 5 8 9 2 0 4 56 23 81 1 7 5 AB in general not equal to BA 3 1 7 1 4 9 A 10 1 8 B 6 2 1 5 2 4 7 4 47 40 38 77 8 23 3 AB 60 10 33 BA 43 6 22 45 0 19 26 11 45 11 12
Vectors Matrices x = [ 1 2 3 4 5 6 7 8 9 10]; Can also be written as x = 1:10; or x = 1:1:10; Examples: x2 = 1:0.1:1.5; Means a vector starts with a number 1 Means the next element will add 1 to the previous element x2 = [1 1.1 1.2 1.3 1.4 1.5]; To access the first element: x2(1) give 1 Means a vector ends with a number 10 To access the third element: x2(3) give 1.2 13 Get the element of the 1 st and 2 nd column, of A i.e. 2 Get all the elements in the 1 st row of A i.e. 1,2,3 Get all the elements in the 2 nd column of A i.e. 2,5,8 14 Vector and matrix operations Multiplication of vectors and matrices Arithmetic operations can be applied to vectors and matrix x=[1 2 3]; x + y [-1 3 6]; y=[-2 1 3]; x - y [3 1 0]; a=2; a*x [2 4 6]; x(1)*y(3) 3; a: 2 x 3, b: 3 x 2 a*b 2x2 matrix x*y??? Error using ==> mtimes Inner matrix dimensions must agree. 15 16
Element-based operation of matrices If we want to multiply two matrices element by element, we can use. operator Matrix operations Functions Operation carried out det(a) Determinant of matrix A inv(a) Matrix inverse \ Left division (solving linear system) rank(a) or rank([a b]) Number of linearly independent rows or columns expm Matrix exponential lu LU factorization (Gaussian elimination) qr QR factorization chol Cholesky factorization eig Eigenvalue decomposition svd Singular value decomposition 17 18 Plotting graphs Plotting graphs plot: creates linear plots of vectors and matrices t = 0:0.001:0.1; y = 3*cos(2*pi*50*t); plot(t,y, --b ) xlabel( t ) ylabel( y(t) ) title( Cosine wave ) Define a vector t with value from 0 to 0.1 and a step size of 0.001 For each element of t, compute y based on the formulation Plot y against t with option: dash blue line 19 20
Other options of plot Obtain sufficient data for plotting plot(x,y,option) Symbol Color Symbol Style k black. Point b blue o Circle c cyan x x-mark g green + Plus m magenta * Star r red - Solid w white : Dotted y yellow -. Dashdot -- Dashed 21 t = 0:0.001:0.1; y = 3*cos(2*pi*50*t); plot(t,y, --b ) xlabel( t ) ylabel( y(t) ) title( Cosine wave ) Why 0.001? With step size = 0.01 22 Obtain sufficient data for plotting User-defined functions t = 0:0.001:0.1; y = 3*cos(2*pi*50*t); plot(t,y, --b ) xlabel( t ) ylabel( y(t) ) title( Cosine wave ) The cosine wave has a frequency of 50 hertz, i.e. 50 cycle per second Each cycle will last 1/50 = 0.02 second Setting step size = 0.001 ensures for each cycle there are 0.02/0.001 = 20 data to plot on the graph We can define our own functions MATLAB programming Better planning of the logical flow of the commands Facilitate the access of some frequently used routines M-file: plain text file containing MATLAB commands and saved with extension.m There are two types: scripts and functions 23 24
M-file Function M-file Script M-file Contains only the MATLAB commands Similar to a batch file : putting together a number of commands in a batch and run sequentially Function M-file Develop user-defined functions Contains some special program constructs in addition to the commands 25 The function M file should start with the following statement: function y=<function_name>(argument list) A keyword of MATLAB that indicates this M-file stores a function A list of output parameters The function name. Better to be the same as the file name A list of input parameters of the function 26 Example Comments Define a function called funcx that will compute the following equation Input parameters: x1, x2 Output parameter: y Comments are indicated by a percent sign % Any text on the same line after a percent sign is ignored Good practice to add comment Purpose of the function Information about input parameters Information about output parameters 27 28
function y = funcx(x1,x2) % This is a function for computing the % equation y = x1^2+(1-e^x2)^2-4 % Input parameters: % x1, x2: the two input numbers % Output parameter: % y: The result of the computation y = x1.^2 + (1 - exp(x2)).^2 4; 29 30 Conditionals: if if isinf(x) ~isreal(x) % Is x infinite or imag? disp( Bad input! )% If yes, show error mess y = NaN;% and set y as Not A Number (NaN) elseif (x < 1000) && (x > 0) % Else if disp( x is between 0 to 1000 ); y = x; else % If the above two conditions are not y = 0; % fulfilled, set y = 0 end 31 Relational and logical operators Logical operator: (isinf): return T or F Relational operators: == equal to ~= not equal to < less than > greater than <= less than or equal to >= greater than or equal to Logical operators: && short-circuited scalar logical AND & bitwise logical AND short-circuited scalar logical OR bitwise logical OR ~ logical NOT 32
Example && can only be applied to scalar The first condition is fulfilled, hence will not evaluate the second one The first condition is not fulfilled, hence continue Conditional: switch switch units % Test the variable units, % which is a string case length % If equal to length disp( meters ) % then case volume % If equal to volume disp( liters ) % then case time disp( seconds ) otherwise % If all of the above is false disp( I give up ) % Display I give up end evaluate the second one 33 34 Loops: for Loops: while nmin = 3; nmax = 10; f = zeros(1,nmax); % Clearly define the f(1:2) = 1; % total memory needed for n = nmin:nmax f(n) = f(n-1) + f(n-2); % This statement will be executed % 8 times, from n = 3 to 10 end n = 0; while x > 1 % While x > 1, do the x = x/2; % following iteratively n = n+1; if n > 50, break, end % If n>50, out end % out from the % loop 35 36
Matlab is not good at handling loops Better to replace loops with vector operations Exercise 1 Give the MATLAB commands that evaluate the following equation and plot the result: For loop Vector operation generates the same set of results 37 38 set of results Solution 1 >> x = >> y = >> plot(x,y,'--r') >> xlabel('x') >> ylabel('y') >> title('gaussian function') 39 Exercise 2 Consider: Using the for loop, develop a MATLAB function to implement the above equation Syntax: y = natural_log(x,n) Remember to check if the absolute value of x and n that the user input are smaller than 1 and greater than 0, respectively Error message is generated if not Add comments 40
Solution function y = natural_log(x,n) % This function computes % % Input parameters: % % % % Output parameter: % if Solution % Check if n is greater than 0 % and abs(x) is smaller than 1 % If yes, implement the equation elseif % show a warning message and quit disp('warning: n is smaller than 0') else % If abs(x) >= 1, % show a warning message and quit 41 end 42 Exercise 3 For the function natural_log(x,n) in Exercise 2 Convert that to using vector operations Hint: the function sum(v) can take the sum of all elements in the vector v Summary Introduction to MATLAB programming Basic arithmetic operations x*y x.* y Looping: for, while Prefer to use vector calculations rather than looping Functions 43 44
References M.J. Roberts, Fundamentals of Signals & Systems, McGraw-Hill, 2008. James H. McClellan, Ronald W. Schafer and Mark A. Yoder, Signal Processing First, Prentice-Hall, 2003. T.A. Driscoll, Learning Matlab, Philadelphia, PA: Society for Industrial and Applied Mathematics, c2009. Using Matlab, The Math Works Inc. 45