12
Matlab (Mat rix laboratory) is an interactive software system for numerical computations and graphics. Starting MATLAB - On a PC, double click the MATLAB icon - On a LINUX/UNIX machine, enter the command: matlab Exiting MATLAB - To exit MATLAB, enter the command: quit or exit Getting Help - The command: help xxx will get help on topic xxx - The command: lookfor xxx will look for functions whose first line of the help text contains the keyword xxx. - Use the command: lookfor -all xxx to search all help text lines for each function. - The command: helpdesk gives more detailed information on a function etc., including some examples. Capturing MATLAB Commands/Output Sometimes a record of commands and output entered in a MATLAB session needs to be recorded. To do this, enter the command: diary xxx where xxx is a filename. Output saved is only text based and no graphics will be included. To shut off the diary, enter the command:

Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

Matlab (Matrix laboratory) is an interactive software system for numerical computations and graphics. Starting MATLAB - On a PC, double click the MATLAB icon - On a LINUX/UNIX machine, enter the command: matlab Exiting MATLAB - To exit MATLAB, enter the command: quit or exit Getting Help - The command: help xxx will get help on topic xxx - The command: lookfor xxx will look for functions whose first line of the help text contains the keyword xxx. - Use the command: lookfor -all xxx to search all help text lines for each function. - The command: helpdesk gives more detailed information on a function etc., including some examples. Capturing MATLAB Commands/Output Sometimes a record of commands and output entered in a MATLAB session needs to be recorded. To do this, enter the command: diary xxx where xxx is a filename. Output saved is only text based and no graphics will be included. To shut off the diary, enter the command:

Page 2: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

diary off Variables - To see the contents of a variable, enter the variable name and press the enter key. - To erase a variable from memory, enter the command: clear xxx where xxx is the variable to remove. - The command: clear will remove all variables. Types of variables - MATLAB's primary type is a matrix. - 1 x 1 matrices are interpreted as scalars - 1 x n matrices are interpreted as row vectors - n x 1 matrices are interpreted as column vectors The MATLAB workspace The workspace is the area of memory accessible from the MATLAB command line. Variables are stored in the workspace. The command: whos Is used to see what is currently in the workspace. Creating Statements, Expressions and Variables in the Workspace MATLAB statements are usually of the form: variable = expression or expression Several statements can be placed on one line as long as each statement is separated by a comma or semi-colon.

Page 3: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

MATLAB does not require any type declarations or dimension statements. Scalars Try entering the following statements: a = 5, b = 6.327e3 c = 7 d = 5.5 + 7i whos MATLAB can handle integers, reals, scientific notation and complex numbers. If complex numbers are used, there can be no space between the i and the number in the imaginary part. To suppress the output of a variable, put a semi-colon at the end of each statement. Row vectors To create a row vector, enclose the values with square brackets [ ]. Each value within the brackets must be separated by either a comma or blanks. Try: a = [1 2 3 4 5.5] b = [3 4e5] c = [1 2 3 4 5 6 7 8 9 ... 10 11 12 13 14 15] Column Vectors To create a column vector, enclose the values with square brackets [ ]. Each value within the brackets must be separated by semi-colon. The semi-colon starts a new row. Try: c = [2;4;5;6] d = [1;1;2;2;3;3]

Page 4: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

Matrices Creating a matrix is the combination of a row and column vector. Enclose the values in the square brackets and use the semi-colon to start a new row in the matrix. Try: ff = [1 2 3; 234 34 3; 3 4 5] gg = [4 5 6; 2 3 4] Saving a MATLAB workspace Sometimes the workspace contains several variables and it would be a pain to re-enter all of them. To save the current workspace enter the command: save xxx This will create a file called xxx.mat To load a workspace back into MATLAB, enter the command: load xxx This will load the file xxx.mat into the workspace. Try: whos save first clear whos load first whos Expressions

Page 5: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

Expressions can be composed of operators, numbers, functions or variables. All operations are evaluated as a matrix. Here are some matrix operators and functions: + addition - subtraction * multiplication / right division ' transpose ^ power .* array multiplication (A.*B is the element-by-element product of

the arrays A and B) eig(A) compute the eigenvalues of the matrix A \ solve the system of equations A\b chol(A) compute the Cholesky factorization of a symmetric PD matrix norm compute various matrix or vector norms Vectors and Matrices Vectors and matrices have to follow the matrix operator rules. Try the following and examine the results: clear a = [1;2] b = 3 c = a + b b * a d = b * a row = [1 2 3 4 5 6 7 8 9] row = row' col = [1 2 3 4 5]' r = [1 2 3 4 5] c = [6 7 8 9 0]' r*c c*r b2 = [1 2 3; 4 5 6] b3 = [3 3 3; 4 4 4] 5*b2

Page 6: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

b2+b3 b3-b2 b2*b3' Building Matrices So far the elements in the matrices have been numbers. MATLAB allows expressions and even other matrices as elements to create larger matrices. Try the following and examine the results: a = 5 b = [5*a a] c = [b;b] d = [c c; c c] a=[1 2; 3 4] b=[5 6; 7 8] [a+b a-b; 2*a 3*b; b a] Functions MATLAB has several functions, here are some that will create matrices. zeros(m,n) creates an (m,n) matrix of zeros; ones(m,n) creates an (m,n) matrix of ones; eye(n) creates the (m,n) identity matrix; diag(v) (v is an n-vector) creates an (n,n) diagonal matrix with v on the

diagonal. Try the following clear z = zeros(5,5) o = ones(3,3) ident = eye(7) five = 5*ones(4,4) mix = rand(2,5) normdist = randn(3,4)

Page 7: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

p = [zeros(5,6) ones(5,3)] Accessing Elements in a Matrix For row and column vectors a single subscript can be used. For example: k=3 a= [1 2 3; 4 5 6] b= [4 5 6]' a(2,2) a(2,k) a(4) b(3) Colon Operator (:) This is one of MATLAB's most important operators. Proper use of this operator will improve efficiency. The form of the colon operator is start : inc : end where start is the initial starting value, inc is an increment value and end is the ending value. If the inc expression is left out, an increment of 1 is used. Either form creates a row vector. Try the following: 1:3 1:0.5:4.7 55:-3:22 1:-1:3 x= 3, y=2, z=9 x:y:z x = 1:10 y = [1:5;6:10]

Page 8: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

The colon operator can also be used to access parts of a matrix. If the colon is used by itself in a row or column subscript, it accesses the whole row or column. For example: a(:,3) - the third column a(1,:) - the first row a(1:4,3) - the first 4 rows of the third column a(1:3,:) - the first 3 rows Try the following out: a=[1:4;5:8;9:12;13:16] a(:,3) a(1,:) a(2:4,2:3) a(2,:) = [1 1 1 1] a(:,2) = [2 2 2 2]' Comparing Efficiency Two ways in MATLAB to compare the efficiency of algorithms is by count the number of floating point operations (flops) or elapsed time. flops(0) - Reset floating point operations to zero flops - Display current number of floating point operations tic - Starts clock (in seconds) toc - Stops clock Examples: a = rand(100,100); b = rand(100,200); tic, x=a*b; toc flops(0), x=a*b; flops Saving space

Page 9: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

If a matrix is very large, but the majority of the matrix is zero, then using the sparse command will save some space and possibly computational time. To convert a sparse matrix to a full matrix, use the full command. Try the following: a= floor(10*rand(1000)/9); b = sparse(a); whos tic, a*a; toc tic, b*b; toc Scripts and Functions Scripts (sometimes called M-files) in MATLAB are text files which contain MATLAB commands. When a script is invoked, MATLAB reads in the file and executes each command in it. If several commands need to be executed repeatedly, then creating a script would save time. Any variables created by the script remain in the workspace. The name of the script can be any valid filename with a .m extension (e.g. start.m). To invoke a script, enter the name of the file without the extension. Using an editor, create the following script and name it plotsin.m : % Identify your script % Author: Your name x = 0:2*pi/N:2*pi; y = sin(w*x); plot(x,y) At the command line prompt in MATLAB, enter the commands: N=100;w=5; plotsin This should run the script.

Page 10: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

Much more powerful than scripts are functions, which allow the user to create new Matlab commands. A function is defined in an m-file that begins with a line of the following form: function [output1,output2,...] = cmd_name(input1,input2,...) The rest of the m-file consists of ordinary Matlab commands. When a function is invoked, Matlab creates a local workspace. The commands in the function cannot refer to variables from the global workspace unless they are passed as inputs. By the same token, variables created as the function executes are erased when the execution of the function ends, unless they are passed back as outputs. Here is a simple example of a function; it computes f(x)=sin(x^2). The following commands should be stored in the file fcn.m (the name of the function within Matlab is the name of the m-file, without the extension): function y = fcn(x) y = sin(x.^2); (Note that the vectorized operator .^ is used, so that the function fcn is also vectorized.) With this function defined, we can use fcn as any built-in function. Enter at the command prompt: x = (-pi:2*pi/100:pi)'; y = sin(x); z = fcn(x); plot(x,y,x,z) grid Programming in Matlab The general form of the if statement is if expr1 statements elseif expr2 statements .

Page 11: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

. else statements end Matlab provides two types of loops: a for-loop and a while-loop. A for-loop repeats the statements in the loop as the loop index takes on the values in a given row vector. Try: for i=1:4 disp(i^2) end The while-loop repeats as long as the given expr is true (nonzero). Try: x=1; while 1+x > 1 x = x/2; end

Structures

A structure is a data type which contains several values, possibly of different types, referenced by name. The simplest way to create a structure is by simple assignment. For example, consider the function

f(x)=(x1-1)^2+x1*x2

The following m-file computes the value, gradient, and Hessian of f at a point x, and returns them in a structure:

function fx = f(x) fx.Value = (x(1)-1)^2+x(1)*x(2); fx.Gradient = [2*(x(1)-1)+x(2);x(1)]; fx.Hessian = [2 1;1 0];

Page 12: Matrix laboratory) is an interactive software system for ...cs4te3/tutorials/matlabtutorial.pdfMatrices Creating a matrix is the combination of a row and column vector. Enclose the

Solving optimization problems in Matlab fminbnd Find a minimum of a function of one variable on a fixed

interval fminsearch Unconstrained nonlinear minimization (minimize a function of

several variables using Nelder-Mead Simplex Method) fzero Find zero of a function of one variable fminunc Find a minimum of an unconstrained multivariable function

(Quasi-Newton method) fmincon Find a minimum of a constrained nonlinear multivariable

function linprog Linear programming