Computation and Simulation MatLab Tutorial Ref. Page Issue Date : GE303-43-1 :1 :1 : 04-11-2003 MatLab is an abbreviation for Matrix Laboratory. It allows you do matrix calculations as if they were scalars. MatLab is also useful for visualising data (2D and 3D plots) and it is fully programmable. MatLab is the core software package which allows you to do general maths calculations. There are numerous (hundreds) MatLab “toolboxes” which extend the functionality of MatLab for specific tasks such as Simulink which is for simulating dynamic systems, the signal processing toolbox which is a collection of digital signal processing algorithms, financial toolbox which provides tools for the modelling and analysis of financial (stock market) data etc. 1 STARTING MATLAB When you start MatLab, several windows open. The command window, where you type commands, is the important one. After you start MatLab, you should navigate to a folder you want to work in (your working directory). Using Windows Explorer, create a folder on your X drive called “MatLab Tutorial”. Change to x:\MatLab Tutorial :» cd(‘x:\MatLab Tutorial’) Note the single quotes. In MatLab, a character string is enclosed in single quotes. If you are unsure of your working directory :» pwd ans = X:\MatLab Tutorial 2 GETTING HELP MatLab has two main sources of help. You can view the software manuals using the help menu. These are full electronic copies of the manuals for MatLab and all installed toolboxes. This is a good place to start to get an overview of a particular topic. The other form of help is the help command which is best when you know the name of the MatLab command (or function) but can’t remember exactly how it works. Typing help by itself gives a list of all the help topics. You can then get help on any of these topics by typing help topicName, e.g. to get help on the if statement :» help if IF IF statement condition. The general form of the IF statement is IF expression statements ELSEIF expression statements ELSE statements END The statements are executed if the real part of the expression has all non-zero elements. The ELSE and ELSEIF parts are optional. Zero or more ELSEIF parts can be used as well as nested IF's. The expression is usually of the form expr rop expr where rop is ==, <, >, <=, >=, or ~=. Example if I == J A(I,J) = 2; 533574510 Sean Doherty Computation and Simulation MatLab Tutorial Ref. Page Issue Date : GE303-43-1 :2 :1 : 04-11-2003 elseif abs(I-J) == 1 A(I,J) = -1; else A(I,J) = 0; end See also RELOP, ELSE, ELSEIF, END, FOR, WHILE, SWITCH. Note how it also gives you a list of related commands (and/or functions) … “See also” 3 VECTORS AND MATRICES 11 12 13 14 Suppose we want to create the matrix X 21 22 23 24 31 32 33 34 method 1 (use a new line (i.e. a <CR> at end of each row) » X = [11 12 13 14 21 22 23 24 31 32 33 34] X = 11 21 31 12 22 32 13 23 33 14 24 34 method 2 (separate each row with a semi-colon) » X = [11 12 13 14; 21 22 23 24; 31 32 33 34] X = 11 21 31 12 22 32 13 23 33 14 24 34 When creating a vector, we can form a row vector :» a = [-1 2 -3 4] a = -1 2 -3 4 or a column vector :» b = [-1; 2; -3; 4] b = -1 2 -3 4 Whenever you type a command, you can suppress MatLab displaying the result of the command by terminating the command with a semicolon :» b = [-1; 2; -3; 4]; b is formed in the same way, but the result is not displayed because of the semicolon at the end of the line. When you work in MatLab, the variables (scalars, vectors or matrices) you create, either directly or as a 533574510 Sean Doherty Computation and Simulation MatLab Tutorial Ref. Page Issue Date : GE303-43-1 :3 :1 : 04-11-2003 result of a calculation are stored in the workspace. To display a list of the workspace variables :» whos Name Size X a b 3x4 1x4 4x1 Bytes 96 32 32 Class double array double array double array Grand total is 20 elements using 160 bytes So, we have 3 variables, X which has 3 rows and 4 columns, a which has 1 row and 4 columns (a row vector) and b which has 4 rows and 1 column (a column vector). To display any workspace variable, just type its name (without terminating semicolon!) :» a a = -1 2 -3 4 3.1 Elements of a matrix Suppose we want to extract from the matrix X the element on the 2nd row and 3rd column and assign it to a new variable z :» z = X(2,3) z = 23 So, in general to refer to the element on the ith row and jth column of a matrix X, we use X(i,j). To refer to all of the ith row, we use X(i,:), or all of the j th column is X(:,j) :» r1 = X(1,:) r1 = 11 12 13 14 » c2 = X(:,2) c2 = 12 22 32 We can use the X(i,j) notation to refer to ANY sub matrix of X because i and j can be vectors :» X1 = X(:,[1 3 4]) X1 = 11 21 31 13 23 33 14 24 34 This assigns to X1 all (: by itself means all) rows of X and columns 1, 2 and 4. » X2 = X([2 3],:) X2 = 21 31 22 32 23 33 24 34 (rows 2 and 3, all columns) 533574510 Sean Doherty Computation and Simulation MatLab Tutorial Ref. Page Issue Date : GE303-43-1 :4 :1 : 04-11-2003 » X3 = X([2 3],[2 3]) X3 = 22 32 23 33 (rows 2 and 3, columns 2 and 3) We can extend the colon notation to specify a sequence, e.g. create a vector v which STARTs at 1, with INCREMENTs of 2 and STOPs at 10 :» v = 1:2:10 v = 1 3 5 7 9 If you omit the INCREMENT, it defaults to 1 :» v = 1:10 v = 1 2 3 4 5 6 7 8 9 10 We can use this vector notation when referring to a sub matrix :» x4 = X(1:2:3, 2:4) x4 = 12 32 13 33 14 34 (rows 1 and 3 (i.e. start at 1, increment by 2, stop at 3), columns 2,3,4 (i.e. start at 1, stop at 3 – default increment of 1 is used). 4 SAVING WORKSPACE VARIABLES Type whos now to display the different variables. »save fileName saves ALL workspace variables to fileName.mat »save fileName X1 saves the variable X1 to fileName.mat »save fileName X1 X2 X3 saves the variables X1 X2 and X3 to fileName.mat NB. If you use the same filename, the contents of the previous file will be overwritten without warning. The save command uses a special file format. If you want to save your variables in ASCII format (e.g. to subsequently import the data into Excel) :»save fileName X1 –ASCII – DOUBLE – TABS saves the variable X1 to fileName.mat in ASCII format as double precision numbers with tab spacing. type help save for other options). To load a previously saved file :»load fileName Sometimes you want to delete some of the variables in the workspace :clear clears ALL workspace variables 533574510 Sean Doherty Computation and Simulation MatLab Tutorial clear x1 x2 Ref. Page Issue Date : GE303-43-1 :5 :1 : 04-11-2003 clears variables x1 and x2 from the workspace. Exercise 1 1) Clear all variables from your workspace. 1.1 2.1 2) Create a matrix h 3.1 4.1 1.2 1.3 1.4 1.5 1.6 2.2 2.3 2.4 2.5 2.6 3.2 3.3 3.4 3.5 3.6 4.2 4.3 4.4 4.5 4.6 Can you spot how you can form this matrix without manually typing each element ? Hint [1.1:0.1:1.6] gives the first row. 3) What size is this matrix? Confirm the size using whos. To find the size of a variable, you can use the size command. Type s = size(h) 4) Form the following submatricies :1.1 1.2 h1 2.1 2.2 1 . 1 1 . 5 h2 2 . 2 1 . 5 h4 3.1 3.2 3.3 3.4 1.5 2.5 h5 3.5 4.5 1 . 12 . 14 . 6 h3 2 . 22 . 24 . 6 3 . 32 . 34 . 6 1 . 16 . 15 . 14 . 3 h4 2 . 26 , 25 . 24 . 3 3 . 36 . 35 . 34 . 3 1.1 2.2 h6 3.3 4.4 5) Confirm the size of your workspace variables using whos. 6) Save h h5 and h6 to a file called submatrix1 7) clear all variables from your workspace 8) load the file submatrix1 9) Confirm the size of your workspace variables using whos. 5 MATRIX CALCULATIONS Two useful MatLab functions for creating matrices are zeros (form matrix of zeros) and ones (form matrix of ones) :» a = zeros(2,4) a = 0 0 0 0 0 0 0 0 » b = ones(2,3) b = 1 1 1 1 1 1 Can we add a and b ? No! To add two matrices, they must have the same size and MatLab will tell you so if you try to add them :533574510 Sean Doherty Computation and Simulation MatLab Tutorial Ref. Page Issue Date : GE303-43-1 :6 :1 : 04-11-2003 » c = a+b ??? Error using ==> + Matrix dimensions must agree. Provided, the dimensions of the matrices are compatible, matrix algebra is easy in MatLab. Let’s illustrate through an exercise. Exercise 2. 1. Clear your workspace 2. Create a matrix of ones, called a, with 7 rows and 3 columns. 3. Multiply a by 2 to create a matrix of twos, called b, with 7 rows and 3 columns. 4. Form the sum c = a + b 5. Form the sum d = a - b 6. Form the product e = a * b. What’s wrong here? 7. Form the transpose of b using bt = b’ 8. Inspect the sizes of your workspace variables using whos. 9. Which matrices in your workspace are compatible for multiplication? 10. Form the products abt = a*bt and bta = bt*a 11. Form the vector v = (1 2 3 4) 12. Form the product v1 = vTv and v2 = vvT. NB. vv T n v(i) 2 i 1 6 GRAPHING Try the following :» t=0:0.25:7; » y = sin(t); » plot(t,y) sin is a MatLab function. You can copy and paste MatLab plots into MS Word. In the MatLab figure, use “Copy Figure”. In Word, you might find that using “Paste Special”, Paste “Picture” works better. Also, it is easier to position the plot in word if you insert a textbox (Insert/textbox) and paste (or paste special) into the textbox. To plot multiple curves :» » » » » t=0:0.25:7; y1=sin(t); y2=cos(t); y3=y1+y2; plot(t,y1,t,y2,t,y3) You can specify line types and colours :» plot(t,y1,’r-‘,t,y2,’g:’,t,y3,’k-.’) where r gives red, g green and k black and -, :, -. produce different line types. Type help plot for details You can adjust the properties/appearance of a plot using the Tools menu :Tools/ Axes Properties : set title, labels, axes limits etc. Tools/ Line Properties : adjust widths, colours and style of a selected line 533574510 Sean Doherty Computation and Simulation MatLab Tutorial Ref. Page Issue Date : GE303-43-1 :7 :1 : 04-11-2003 Tools Text Properties : -adjust Text Property of ANY selected text (e.g. the labels of the X axis) Other functions which you might find useful for graphing (use help for further information) figure :- you can have multiple figure windows, each one containing a plot :- you can have multiple plots on a single figure. Try subplot( 3,2,1) :- insert a legend :- normally, if you issue a plot command, it deletes any existing plot from the figure window before subplot legend hold plotting. Typing hold on prevents this (i.e. you can add a graph to an existing plot). hold off toggles hold 7 SCRIPTS AND M-FUNCTIONS You can automate Matlab by typing commands into a scriptfile. In the MatLab command window, select File/New/M-file. You can put any sequence of commands into a scriptfile and save it as, for example test (MatLab will automatically add the extension .m, saving the scriptfile as test.m). Now, if you type test at the command line, each of the commands in the scriptfile are executed in sequence - this will give exactly the same result as typing each command in the command window. Let’s illustrate by using the (simplified) script code from lecture 2 which is to graph :If not already open, open the MatLab Editor using File/New/Mfile We want to plot the mathematical function f(x) x 3 x 2 3x 3 0 over the range [–2, 1.8] Generate the x vector (I’m using a step size of 0.1 – you could use a smaller step size if you want) »x = -2:0.1:1.8; Calculate the values of y at x using the above equation »y = x.^3 + x.^2 - 3*x - 3; (^ means to the power of. x^3 is x*x*x x.^3 means raise each element of x to the power of 3) »plot(x,y) Define a vector which contains the roots of f(x) – you are given these values »r = [-3^0.5 3^0.5 -1]; Switch hold ON – otherwise plot will get rid of existing graph »hold on Plot these 3 points using black (i.e. k) circles (i.e. o) »plot(r,[0 0 0], ‘ok'); Now use Tools/ Axes/Line/text Properties to :1. Insert a x label ‘x’ 2. Insert a ylabel ‘y’ 3. Insert a plot title 'Sample function for root finding : f(x) = x^3 + x^2 - 3x – 3 4. Switch grid on 5. Change the axes limits to x [-3 3] and y [-6 2] When you execute a script file, it is exactly the same as typing each line at the command prompt. This means that all variables created in the scriptfile are in the workspace. Often, you don’t want this but you want to create a m-function which you pass a list of arguments and it returns one or more values – all calculations done in the m-function are local to the m-function – you cannot see these in the workspace. You 533574510 Sean Doherty Computation and Simulation MatLab Tutorial Ref. Page Issue Date : GE303-43-1 :8 :1 : 04-11-2003 can a list of the MatLab programming language constructs by typing help lang. Let’s create a m-function which when passed an x value, returns the value of f(x) x 3 x 2 3x 3 0 . In the MatLab editor, open a new page and type the following : function [y] = f1(x) y = x.^3 + x.^2 - 3*x - 3; Now save this as f1. Matlab will automatically add the .m extension To call this m-function at the command prompt, for example to find the value of f(9), and assign to a variable z, we type :» z=f1(9) z = 780 Note, that f1.m will also work for vectors :» z=f1(-1:.5:1) z = 0 -1.3750 -3.0000 -4.1250 -4.0000 Of course, MatLab m-functions can have multiple arguments and multiple return values, e.g. function [a,b,c] = nuim(x,y) defines a m-function with 2 arguments (referred to as x, y in the m-function) and returns 3 values (referred to as a,b,c in the m-function). The variables a,b,c,x,y and any other variables in the m-function are local to the m-function – they are not seen in the workspace. How do we call a m-function within another m-function? We have two options. Suppose we want to call f1.m within a new m-function called f2.m. Within f2.m we can simply type (1) z=f1(9); This is equivalent to (2) z = feval(‘f1’,9); feval is a MatLab function which, in the above case, calls the m-function called f1 (note the quotes ‘f1’ is a string) and passes f1 the argument 9. With (1), the name of the m-function being called in f2.m (i.e. f1) is hard coded in f2.m, so, if we want to change the name of the f1 m-function, we have to edit the f2.m file. With (2) we can pass the name of the m-function as an argument to f2.m i.e. function [a, b, c …] = f2(x,y,…,fun) % Note that fun is a string : z = feval(fun,9); 533574510 Sean Doherty Computation and Simulation MatLab Tutorial Ref. Page Issue Date : GE303-43-1 :9 :1 : 04-11-2003 : Then at the command prompt we can pass the name of the f1 m-function to f2.m :[f, g, h, ….] = f2(d, e, …, ‘f1’); 533574510 Sean Doherty