1 CHAPTER 1. INTRODUCTION TO MATLAB Written by: Sophia Hassiotis, January, 2003 Last revision: January, 2015 “I THINK EVERYBODY IN THIS COUNTRY SHOULD LEARN HOW TO PROGRAM A COMPUTER BECAUSE IT TEACHES YOU HOW TO THINK.” — STEVE JOBS, THE LOST INTERVIEW For some inspiration, visit: http://www.code.org/ ________________________________________________________________________ We will use MATLAB as our programming language. You can download and install MATLAB from the Stevens domain: “public on storage01” You can find the Activation Key in the word file “License Key.rtf” Please see the following document for an introduction and help from the mathworks website: http://www.mathworks.com/help/pdf_doc/matlab/getstart.pdf. MATLAB Windows a command window (enter commands and data) edit window (create modify files) a graphics window (display graphics) 2 Basic commands for the Command Window clc clf clear who whos clears command window clears current figure removes variables from memory, does not affect window lists all variables defined same as who with more information on matrix size and variable type Control c aborts an operations (for example, use to abort an infinite loop) Use the Editor to create SCRIPTS In what follows, MATLAB is introduced as a series of workshops. You may Copy-Paste everything pink into the MATLAB command window and see what happens, or you can create and run scripts. Note that sometimes the editors cannot translate the symbols between word and MATLAB correctly and you may get errors. In those cases, type the information directly into the command window and do not copy-paste from this word file. Please note that all MATLAB functions will appear in this report in blue color/bold font 3 DATA STRUCTURES ARRAYS: SCALARS, VECTORS, MATRICES How to input: Use a bracket to input an element in the array Input a comment statement: Use the % sign to input a comment. MATLAB does not try to execute anything found after it. Input the value of a scalar: a=5 %here, MATLAB will echo this input on the command window. >>a = 5 If you do not want to echo the input back, place a semicolon after the command as: a=5; Use brackets to create a vector array: b=[1 2 3] Input matrix arrays: A=[1 2 3; 4 5 6; 7 8 9]; % values separated by spaces, rows separated by semicolon or A=[1,2,3;4,5,6;7,8,9]; % values separated by commas, rows separated by semicolon or A=[1 2 3 % rows separated by the ENTER 456 7 8 9] Input Large Matrices using the line-continuation: A=[1 2,... % the three periods mean that the command is continued in the 3;4 5,... % line below 6;7 8 9] Use already defined matrices to define new ones: B=[A A] or B=[0 0 0;A] or say B=[A A; A A] 4 How to retrieve your input: Use a parenthesis to pick elements in the array Retrieve a column of a matrix: D=B(:,3) % retrieves all the rows of the 3rd column of B Retrieve a Sub-matrix C=B(:,3:5) %where C is made up of columns 3-5 of B (in effect, it reads as [all rows, columns 3 to 5]) C=B(1:3,3:5) % where C is made up of rows 1 to 3 and columns 3 to 5 of B Indexing with logical arrays—using rand and logical* %MATLAB example for indexing with logical arrays M=rand(4,5) %generates a 4x5 array of random numbers M= 0.6557 0.0357 0.8491 0.9340 0.6787 0.7577 0.7431 0.3922 0.6555 0.1712 0.7060 0.0318 0.2769 0.0462 0.0971 0.8235 0.6948 0.3171 0.9502 0.0344 Rindex=logical([1 0 0 1]) % pick Rows 1 and 5 of matrix M Rindex = 1 0 0 1 Cindex=logical([0 0 1 1 1 ]) % pick Columns 3,4,and 5 Cindex = 0 0 1 1 1 M(Rindex,Cindex) % create a new matrix M using rows 1 and 5 and columns 3,4,5. ans = 0.6555 0.2769 0.6948 0.0318 0.8235 0.0344 *Please note that all MATLAB commands will appear in this report in blue color, bold font 5 How to manipulate or create input Erase a row of a matrix A(:,3)=[ ] Generate a vector H=1:5 T=0:0.1:2 V=10:-1:0 Generate a column matrix—Note that C(:) places each column one after the other. Try this: C =[1 2 3; 4 5 6; 7 8 9]; C(:) Transpose a Matrix A=B’ Special Values and functions ones, eye,zeros,size There are some names that MATLAB recognizes as its own functions. We cannot re-define or use such function names. For example, pi (3,14); i,j (sqrt of –1); Inf (infinity); NaN (no number, exp: 0/0); eps (floating point precision); ans (computed value not stored in variable name) The ones function creates a matrix of ones A=ones(6) The eye function creates the identity matrix A=eye(6) For example, type in: C=[2 4;5 6] D=[C ones(size(C));eye(size (C)) zeros(size(C ))] Zero matrices A=zeros(6) B=zeros(4,3) C=[1 2 3; 4 5 6] 6 D=zeros(size(C )) Example of Math Functions: cos(pi) or cos(angleindegrees*pi/180) Format and Printing format and fprint Several formats are available. Please type these commands into the command window to gain an insight into formatting Format Printing Text or or A format such as: a=300.444444466666777778888888 format short format long format short e format long e format bank temp=78 fprintf(‘the temperature is %f degrees F \n’,temp) (decimal) %e (exponential) %g (shorter of decimal/exponential) %4.1f prints 4 positions, one of which is a decimal position The command \n is needed to guarantee a change in line. Lay-out in memory Theentries of the matrix are stored together in memory in a specific order. For example, take the matrix A A=[1 2 3;21 22 23;31 32 33] A= 1 2 3 21 22 23 31 32 33 Somewhere in memory, MATLAB has the following information Name= 'A' Size = [3 3]; Data= 1 21 31 2 7 22 32 3 23 33 The fifth entry of A is 22 and it can be referenced directly as >> A(5) ans = 22 Character Arrays Use quotes to input a character array The character arrays are marked as such in the workspace. For example, A='my name is SH'; whos A 1x13 26 char % the char stands for "character" array %MATLAB example for stacking character arrays---using size str1='modsim is fun,'; str2='you must be kidding'; size(str1) ans = 1 14 size(str2) ans = 1 19 str3=[str1 str2] % note that to create a row vector the two string can have different sizes str3 = modsim is fun,you must be kidding str4=[' ' str1;str2] % note that Strings 1 and 2 must be the same size to stack. One needs t to place {19-14=5} spaces before str1 to make it the same size as str2. str4 = modsim is fun, you must be kidding 8 DATA STRUCTURES: CELL ARRAYS What they are: Cell arrays are like the matrix arrays, but the elements do not have to be the same type nor the same size. How to input: Use of curly brackets to input an element in the array Create a single row container with A=[{[1 2 3]} {'SH'} {pi} {[1 2 3;4 5 6;7 8 9]}] %Equivalent to: A={[1 2 3] 'SH' pi [1 2 3;4 5 6;7 8 9]} A= [1x3 double] 'SH' [3.1416] [3x3 double] Create a 2x2 container with B={[1 2 3] 'SH';pi [1 2 3;4 5 6;7 8 9]} B= [1x3 double] 'SH' [ 3.1416] [3x3 double] How to retrieve your input: Use a curly brackets to retrieve the contents of the cell Retrieve the contents of the [3x3] matrix inside the A cell A(4) % Note that the parentheses refer to the container ans = [3x3 double] A{4} % Note the curly brackets refer to the contents ans = 1 4 7 2 5 8 3 6 9 Here is another example that will help in organizing your matrices into one container. K={[1 2;3 4] [5 6;7 8] [9 10;11 12]} K= 9 [2x2 double] [2x2 double] [2x2 double] K2=K{2} K2 = 5 6 7 8 You can add another matrix into the K container. For example K{1,4}=[13 14;15 16] or K3=[13 14;15 16]; K{1,4}=K3 Structures: struct—They can put together values and characters into one structure. These are advanced data structures and we will not cover here. 10 PERFORMING SIMPLE TASKS IN MATHEMATICS WITH MATLAB Simple arithmetic Addition, subtraction, division, exponential: Define scalars a, b, and c and try these simple operations in the command window. x=a+b y=a/b z=c^b Element-by-element Operations: Define matrices A and B and try these operations C=A*B % note that this is the multiplication of two matrices D=A.*B % note the addition of a period after A forces an element-by-element operation E=A./B F=A.^B %MATLAB example-1 in using Element-by-Element Operations Let’s define a vector x and a function f(x) x=0:1:3 x= 0 1 2 3 f=x.^2 f= 0 1 4 9 This is the same operation as (note the dot): ff=x.*x ff = 0 1 4 9 But it is not the same as the square of the vector (note absence of dot): magnitude=x*x' magnitude = 14 Scalar base-to-vector exponent A=[2 2 3] C=2.^A D=A.^2 11 %MATLAB example-2 in using Element-by-Element Operations M=rand(2,2) %generates a 2x2 matrix of random numbers between 0 and 1. M= 0.4387 0.7655 0.3816 0.7952 cos(M) % finds the cosine of all elements in matrix M ans = 0.9053 0.7210 0.9281 0.7001 Nestle functions using parenthesis: example: log(sin(x)) Complex Functions x=1+0.5*i Polynomials plot, polyval, conv, deconv, roots,poly Define a polynomial function f(x) and plot it as a function of its independent variable x. x=0:1:20; f=x.^3-2*x.^2+0.5*x-6.5; plot(x,f) OR, you may, instead, define the coefficients of polynomial f(x), and then evaluate f(x) at points x by using polyval: f=[1 -2 0.5 -6.5] h =polyval(f,x) plot(x,h) Add two polynomials by adding the coefficients Multiply two polynomials using conv(a,b) a=[2 3] %(2x + 3) b=[4 0 1 0] %(4x^3+0x^2+1x+0) conv(a,b) The answer will be: [8 12 2 3 0] which translates to: (8x^4+12x^3+2x^2+3x+0) Divide two polynomials b/a using deconv [q,r]=deconv(b,a) ; % vector q contains coefficients of quotient; vector r contains coefficients of remainder 12 Find the roots of polynomials y=b(x) (i.e. what are the values of x that make y zero) using roots. b=[4 0 1 0] roots(b) % OR you may use: r = roots ( [4 0 1 0] ) The answer will be: ans = 0 0 + 0.5000i 0 - 0.5000i Calculate the polynomial if we know the roots r using poly(r ) r =[ 0 0 + 0.5000i 0 - 0.5000i] poly(r) ans =[1.0000 0 0.2500 0] Statistics and Data Analysis Data Analysis Functions x=[1 2 3;3 2 1;0 0 0] max(x) ans = [ 3 2 3] %max value in each column [y,k]=max(x) %vector y gives max values, vector k gives the indices associated with the maximum values. You will find this answer: y =[ 3 2 3] (max value); k =[ 2 1 1] (indices) sum(x) gives sum of each column prod(x) product of each column cumsum(x) cumulative sums as you go down the column mean(x) gives average of each column median(x) median in each column (ie the number in the middle) sort(x) sorts numbers in each column 13 PLOTING WITH MATLAB Function of one variable using: plot To evaluate a function of one variable y(t), we create a vector of values for t and then compute the function y at every point t. t=0:0.01:1; y=sin(2*pi*t); plot(t,y),xlabel('t'),ylabel('y') To evaluate and plot the polynomial F(x)=5x^2-2x-3, use ELEMENT operations x=0:1:3 >>x = 0 1 2 3 f=5*x.^2-2*x-3 >>f = -3 0 13 36 plot(x,f),xlabel('x'),ylabel('f(x)') ) 14 Function of one variable. surf 1 ytran*y 0.5 t=0:0.01:1; y=sin(2*pi*t); w=y'*y; surf(w),xlabel('t'),ylabel('y'),… zlabel('ytran*y') 0 -0.5 -1 150 150 100 100 50 y 50 0 0 t This subroutine Plots w at: x=1 to size(w); and y=1 to size(w). Try these exercises %MATLAB example on how to use pause time=0:1:10; vel=[2 4 6 7 8 9 5 3 5 7 1]; plot (time,vel) pause(10) plot(time,vel),title('example1'),xlabel('time (sec)'),ylabel('velocity (mph)'),grid The pause(10) will pause the program for 10 seconds so you can study the graph. Then, the graphics window will disappear and the rest of the program will resume Log and Semilog %MATLAB example on semi-log graphs % Try this plot from Dr. Brunnel’s class time=[0.5 1 2 3 4 5 7 10 20 30 50 100 200 500 1000]; D=[0.16 .18 .24 .27 .47 .5 .57 .68 .84 .96 1.06 1.29... 1.46 1.68 1.86]; semilogx(time,D),title('Drawdown Curve'),xlabel('Time'),ylabel('Drawdown'),grid 15 Note that: semilogx(x,y) semilogy(x,y) loglog(x,y) x in log scale vs y in linear x in linear vs y in log x in log scale vs y in log scale Place multiple plots on same graph. For example, try ploting on the same graph the pairs (x,y) and (w,z). Note that the pairs are not of the same size. x=[1 2 3 4 5];y=[50 60 70 80 90];w=[10 11 12];z=[30 40 50]; plot(x,y,w,z) Multiple functions of x. x=0:1:5; %(row vector) f(:,1)=10*x' %(the first column of f is 10*each elem) f(:,2)=x'.^2 %(the 2od column of f is each element squared) plot(x,f),title('two plots'),xlabel('x'),grid Line and mark styles Subplots plot(x,f,'o'),title('two plots'),xlabel('x'),grid Plots only the points with mark “o” Can use o, *, +,x and a period . to indicate points plot(x,f,'-.'),title('two plots'),xlabel('x'),grid Plots dash-dot lines Can use –(solid), _(dashed),: (dotted), -.(dash-dot) subplot(m,n,p): mxn grid of smaller windows, p=pth window for current plot Plots numbered left to right, top to bottom subplot (2,2,1), plot(x,f) means: 4 plots on a page (2x2 grid) the x,f vectors is plot #1 (top left) subplot(2,1,2), plot(x,f) means: 2 plots on a page (2x1 grid) one on top of other the x,f vector is plot #2 subplot(1,2,2), plot(x,f) means: 2 plots on a page (1x2) Polar Plots polar(theta,r) generates polar plot of angles theta(rad) vs r 16 Function of two variables meshgrid, surf, mesh, contour,meshc To evaluate a function of two variables, F(x,y) we define a grid in the x-y plane and we evaluate the function at the grid points. In MATLAB two matrices define a 2-D grid. One matrix contains the x-coordinates at all points in the grid. The other matrix contains the ycoordinates of all points in the grid. Example1: Let’s create a grid of xy pairs where 5 points are created for x that is defined between 2 and 10 and 3 points are created for y that is defined between 2 and 6. Use the command meshgrid to arrive at a 3x5 matrix that contains the pairs xy where the function is evaluated. Evaluate the function z= -1/(1+x^2+y^2) at the grid points and plot. %MATLAB example using meshgrid x=2:2:10; y=2:2:6; [xgrid ygrid]=meshgrid(x,y) 0 -0.02 xgrid = -0.04 4 6 8 10 2 4 6 8 10 -0.08 2 4 6 8 10 -0.1 z 2 -0.06 -0.12 2 ygrid = 2 2 2 2 2 4 4 4 4 4 6 6 6 6 6 2,6 4,6 6,6 2,4 8,6 10,6 4,4 2,2 6,4 4,2 4 6 6 8,4 5 10,4 4 6,2 8,2 8 10,2 2 10 3 y x %Now, the function will be evaluated at the grid points (x,y)= (2,2), (4,2)…(10,2)…(10,6) z=-1./(1+xgrid.^2 +ygrid.^2) surf(xgrid,ygrid,z),xlabel('x'),ylabel('y'),zlabel('z') 17 0 -0.02 z -0.04 -0.06 -0.08 -0.1 -0.12 6 5 10 8 4 6 3 4 2 y 2 x Example 2--Try on your own: Create a grid of xy pairs where m points are created for x that is defined between 0 and 2 and n points are created for y that is defined between 0 and 3. Evaluate the function F(x,y)=-xy^2 at the grid points, and plot. %Class exercise on using grid points x=0:0.5:2 x= 0 0.5 1 1.5 2 y=0:1:3 y= 0 1 2 3 [xgrid,ygrid]=meshgrid(x,y) xgrid = 0 0 0 0 ygrid = 0.5 0.5 0.5 0.5 1 1 1 1 1.5 1.5 1.5 1.5 2 2 2 2 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 % Now the function is evaluated at points (0,0), (0.5,0), (1,0), (1.5,0), (2,0), (0,1)…(2,3). For example, lets evaluate the function F(x,y)=-xy^2 at the grid points and plot using surf. Pay attention at the period after the variables. fxy= -1*xgrid.*ygrid.^2 fxy = 0 0 0 0 0 18 0 -0.5 -1.0 -1.5 -2.0 0 -2.0 -4.0 -6.0 -8.0 0 -4.5 -9.0 -13.5 -18. surf(xgrid,ygrid,fxy),xlabel('x'),ylabel('y'),zlabel('F(xy)') 0 F(xy) -5 -10 -15 -20 3 2 2 1.5 1 1 0.5 y 0 0 x We used the command surf to create the surface plot. You may use other commands to create mesh or contour plots. Plot the equations of these two examples again using the following: Mesh Plot: » mesh(xgrid,ygrid,z) Surface Plot: » surf(xgrid,ygrid,z) Contour Map » contour(xgrid,ygrid,z) » contour(xgrid,ygrid,z,20) where we are asking for 20 contours Mesh and contour » meshc(xgrid,ygrid,z) Using the PLOT catalog You may use PLOT to select variables to plot. In the previous example, create the xgrid, ygrid and fxy. Then plot by choosing x, y, z and pressing surf 19 HOMEWORK 1. 1. Go through all commands given in Chapter 1 (do not hand this part of HWK in.) 2. Write a simple function to define f(x)=x^2-cos x –x and plot the graph of the function in the range of 0 to 2. 3. Use the functions meshgrid and mesh to obtain a 3-D plot of the function Z=2xy/(x^2+y^2) for x=1 to 3 and y=1 to 5. Redraw with surf and contour. 4. Plot the Lemniscate of Bernoulli (x2+y2)2= 2(x2-y2) 5. Plot y=x2; y= sin(x2), and y= sin(x) on the same graph. Label them with arrows pointing to the respective curve (for example, have an arrow from the label 'y=x2' to the curve y=x2). annotation command can be used. HOMEWORK 2 6. Fit the following data with 4 different polynomials. Plot your results. Can you fit a higher-order polynomial? Would you need to? What is a possible material with this stress-strain curve? Write down the simplest form of an equation that describes your data. Strain 0 0.0002 0.0004 0.0006 0.0008 0.0010 0.0012 0.0014 0.0016 0.0018 0.0020 0.0022 0.0024 0.0026 0.0028 0.0030 0.0032 0.0034 0.0036 Stress (psi) 0 900 1,800 2,000 2,500 3,000 3,300 3,500 3,700 3,850 4,000 3,800 3,600 3,500 3,400 3,300 3,200 3,000 2,800 20 PROGRAMMING WITH MATLAB The basic steps in programming are common in all languages. First you will need to identify what is your input, what is your expected output and what are the basic steps that relate the two. It is advisable that you create a flowchart to help you summarize this preliminary work before you start programming. Input/Output in MATLAB save, load, .MAT,.DAT 1) User Input during program execution (NOT recommended in this class.) Example: Let’s say that MATLAB encounters the statement z=input('Enter Matrix Z ') At that point the program will stop execution until you type (in the command window) the matrix Z in brackets as: >> [1 2 3] 2) Input matrices right on the screen Example: >>a=[1 2 3;4 5 6;0 0 3]; 3) Load workspace—you may save information that you input in the screen. This information can be re-loaded on the workspace at a later time. MAT files type in the data (say time, vel) on the screen. Type save filename1 time vel. The time and velocity vectors have been saved in a file called filename1.mat. Matlab has added the .mat ending. This file most probably is saved at your “work” directory. You cannot read or write in filename1. %MATLAB example on how to save and reload workspace vel=[1 2 3]; time=[0.1 0.2 0.3]; save tempinput vel time %Note: the Mat file tempinput.mat appears in your work directory clear %empties memory of all information whos %you will find no variables in the workspace load tempinput %reload your work space whos %you will find the workspace is now loaded Name Size Bytes Class time 1x3 24 double array vel 1x3 24 double array Grand total is 6 elements using 48 bytes 21 4) Import Data (using the menu commands File/Import data) DAT files A command such as: save time.dat will save the time vector in ascii format at your work directory to be used at a later date. You may import this data by using the File/Import data commands %MATLAB Example on how to save a DAT file clear time=[0.1 0.2 0.3 0.4]; save time.dat You may use WORD FILES to tabulate your data and save as text or in excel. Such data can also be loaded into your workspace by using the File import data commands. MATLAB will save the file in the workspace by the name data. Try this example. Type the time-temperature-velocity data given below and save as a text or an excel file. Let’s call this file: MyExample. Use import to load MyExample into your work space. Import the MATRIX time(hr) temp(F) vel(ft/s) 1 70 100 2 75 140 3 85 30 4 90 0 5 83 20 6 77 60 7 64 100 8 60 150 9 59 200 10 55 210 22 You may plot time vs temperature using the command: plot(MyExample(:,1),MyExample(:,3)),xlabel('time'),ylabel('Temperature') Logical Operators You can write large programs with MATLAB by using a combination of basic structures. Relational Operators: <= >= == ~= Logical Operators ~ & | less than or equal greater than or equal equal not equal not and or %MATLAB Example using logical operators. a=1; b=2; c=3; if (a~=b) & c==3 d=200 end % check your answer LOOPS: if, else, elseif Here we will list several logical expression used to check and execute commands. if STATEMENT: if the logical expression is true, execute the commands between if and end. If the logical expression is not true, skip to the end. %MATLAB example using the if statement x=10;g=20; if g<0 x=0 end x %MATLAB Example of nested if statements 23 x=10;y=20;z=30; if z > 29 %(if this statement is not true, it skips to second end) x=0 if x<1 y=-200 end end x y check: x = 0 ; y = -200 else STATEMENT: if the logical expression is true, execute command after the if and go to the end of the operation. If the logical expression is not true, execute command after the else. %MATLAB example using the else statement x=10; g=20; if g<0 x=0 else x=-3 y=-3 end Check your answer. You will find: x = -3; y = -3 elseif STATEMENT: used for nested else statements. %MATLAB example using the else if statement g=20; if g<0 x=0 elseif g>22 x=10 else x=200. end x Check your answer. You will find x=200. LOOPS, for, while For repetitive operations you must use a loop. The most common loop in MATLAB is the for-loop. It can be summarized as follows: 24 for loop_variable = startvalue:endvalue <Commands> end %MATLAB example using the for-loop for i=1:4 x(i)=2*i+1; y(i)=2*x(i); end x y Check your answer. You will find x =[ 3 5 7 9]; y =[ 6 10 14 18] A nested loop will have two or more loops within each other. %MATLAB example on using nested for-loops for i=1:4 for j=1:3 A(i,j)=2*i+j; end end A You will find that A = 3 4 5 5 6 7 7 8 9 9 10 11 The following example demonstrates a basic structure for performing a summation using loops. % MATLAB Example on using loops to sum. sum=0; for i=1:3 x(i)=2*i; sum=sum+x(i); end sum Check your answer. You will find: sum=12 25 The next examples demonstrate how we can input the indices. Please make sure you start your indices from a positive number. %MATLAB example-1 on using indices n=5; for j=n+5:-1:1 a(j)=5*j; end a Check your answer. You will find: a= 5 10 15 20 25 30 35 40 45 50 %MATLAB example-2 on using indices clear for j=[2 5 1] a(j)=3*j; b=3*j; end a b Check your answers. You will find: a= [ 3 6 0 0 15] and b= [ 3]. Please note that b takes the values of 6, 15, and 3 in that order. If you want to save your answers in a vector, see how vector a is treated. The while statement can also be used to create a repetitive operation. It is used to perform an operation while a condition is satisfied. %MATLAB example-1using the while statement clear i=1; while i<3 x(i)=3*i; i=i+1; end x Check your answer. You will find that x=[ 3 6] %MATLAB example-2using the while statement clear x=[0 1 3]; y=[2 3 11]; while sum(x)<max(y) x=x.^2; end x Check your answer. You will find x= [ 0 1 81] 26 User-Defined Functions Your can create your own function and give it a name. MATLAB will recognize your functions as its own {ex. sqrt(x) or sin(x)}. The specific form of the user-defined function must be typed into a New m-file in the following format: function outputparameter=function_name(inputparameter) or if you have more than one output/input parameter: function[output parameter1, out2, out3] = function_name (input parameter1, input2) % function_name: Use the first line to input your definition of the function, as you would like it to appear in a “help fuction_name” command. ----body of function i.e. statements defining user’s function. These statements should include statements assigning values to the output parameters Once the function is defined, save in an M-file as: function_name.m To call the function in Matlab type: [output parameter1, param2, param3] = function_name (input parameter1, input param2) EXAMPLE 1. Let’s create a function that will calculate 1/(x^2). We will name the function fun1. Bring up the MATLAB editor and type (or copy-paste) the following in the editor (not the command window). Save it it in your work directory as fun1. Matlab adds .m to indicate M-file function p=fun1(x) %This is a MATLAB example on creating a Function. %Note that the word function appears above this comment statement. %The new function has the name fun1. % fun1 is a simple function that calculates 1/x^2 p=1/(x^2); Now you can call it in the MATLAB command window as follows: y=fun1(2) 27 MATLAB calculates y=0.25. Note that I chose to call the output parameter y not p during implementation. The input parameter x is equal to 2 You may choose to give the value of the input differently as shown below x=2; y=fun1(x) ans = 0.25 OR, call the function as an input to another function. For example, cos(fun1(x)) ans = 0.9689 EXAMPLE2. Let’s create a function that will calculate the roots of ax^2+bx+c=0. We will name the function rootquad. Bring up the MATLAB editor and type (or copypaste) the following in the editor (not the command window). Save it it in your work directory as rootquad. Matlab adds .m to indicate M-file function [x1,x2]=rootquad(a,b,c) % rootquad solves ax^2+bx+c=0 given the coefficients a,b,c. %The output (roots) are assigned to x1 and x2 % d=b*b-4*a*c; x1=(-b+sqrt(d))/(2*a); x2=(-b-sqrt(d))/(2*a); Now, let’s call it in the MATLAB command window to evaluate the polynomial 4x^2+9x+3=0 a=4;b=9;c=3; [r1,r2]=rootquad(a,b,c) The answer is: r1 = -0.4069 r2 = -1.8431 You can also operate in the input as: x=20;y=-40;z=3; [p,q]=rootquad(x+2*y,x-y,2*z) The answer is: p = -0.0916 28 q = 1.0916 OR, you can use the function feval (ie. Evaluate function) [r1,r2]=feval('rootquad',4,9,3) The answer is: r1 = -0.4069 r2 = -1.8431 Function Functions This example shows how to use the output of one MATLAB function (sin) as an input to another (fplot). Note that @sin is the handle of MATLAB function sin fplot(@sin,[0,3*pi]) % output from the function sin is used in the function fplot Nested Functions Use nested functions to share data. Let’s create a function nested_a and save it as nested_a.m function [p,q]=nested_a(a,x,y) %this is used by my introduction manual---working w/nested functions p=a*x+y; q=a*x; when we call this function in MATLAB we get: >> [pp,qq]=nested_a(5,2,1) pp = 11 qq = 10 29 This data can be shared by a different function nested_b without being passed as parameters. For example, create a new function and save it as nestExample.m. Within this script, nest a new function nested_b that does not need to be saved separately. Note that this new function has access to all the inputs and outputs of the main function nestExample. Do not forget the end statements. function [p,q]=nestExample(a,x,y) %this is used by my introduction manual---working w/nested functions p=a*x+y q=a*x function [alpha,beta]=nested_b alpha=p^2 beta=a+x+y end end Call it in the MATLAB command as: >> [i,j]=nestExample(1,2,3) p= 5 q= 2 i= 5 j= 2 where you renamed the parameter alpha as i and the parameter beta as j. Anonymous Functions With anonymous functions you can make a function without an M-file. Anonymous functions can use the variables in the workspace as parameters. The function is defined at the command line! Example 1: Consider the function f(x,y)= a x^2 - b y^2 Create a function handle f to this function where the constants a and b are defined. a=2;b=5; f=@(x,y)a*x.^2-b*y.^2; %(or you can type f=@(x,y)a*x^2-b*y^2; w/t the dots) f(3,4) ans = -62 30 Example 2: Define functions at the command line. Consider the function f(x) = sin (alpha * x ) Create a function handle f to this function where alpha = 0.5. %Creating a function handle alpha=0.5; f=@(x) sin(alpha*x); x=0:0.001:3*pi; area(x,f(x)) %plot and shade the area under the plot Integrating a Function, using quad We can use quad to calculate the area under the function between a range of values, here between 0 and pi quad(f,0,pi) ans = 2.0000 Minimizing a Function, ezplot, hold on, hold off, fminbnd Consider the function: f(x) = a x^2 + b x + c where a=1, b=-2, and c=1 31 %Create a function handle for it. a=1;b=-2;c=1; f=@(x)(a*x.^2+b*x+c); ezplot(f); % Plot the function title('f(x)=ax^2+bx+c, a=1,b=-2,c=1'); hold on; % Find and plot the minimum minimum=fminbnd(f,-2,2); % We can pass the function handle directly % to the minimization routine plot(minimum,f(minimum),'d'); % We can evaluate the function without % using feval grid; hold off; >> minimum minimum = 1.0000 32 HOMEWORK 3—PROGRAMMING WITH MATLAB 3.1 Write an m-file (script) that will read a given vector and output the numbers in order. For example: Input: [6 3 0 9 22 8 5 8 2 1 4 78] Output: [0 1 2 3 4 5 6 8 8 9 22 78] Please do NOT use internal matlab subroutines (for example: sort(x)) to accomplish this task. 3.2 Write an m-file (script) to compute for i = 1,3,5,7. 3.3 Write a function that will calculate for any input f. 3.4 Write a function whose input is a string and whose output is the string in the reverse order. Please do NOT use internal matlab subroutines (for example: fliplr(x)) to accomplish this task. 3.5 Write a function function s=sumsquares(n) which will have an input of integer number n and computes using the for loop. This is just for the sake of exercise since sum( (1:n).^ 2) achieves the same result 3.6 Handout HWK on USE NESTED AND ANONYMOUS FUNCTIONS 33 SYMBOLIC MATH WITH MATLAB Solve algebraic equations using command solve. First define variables as symbolic and solve the equation. >> syms a b c x >> S=a*x^2 + b*x + c; >> solve(S) ans = -(b + (b^2 - 4*a*c)^(1/2))/(2*a) -(b - (b^2 - 4*a*c)^(1/2))/(2*a) Or solve for a specific variable, for example, to solve the equation for variable b, type >> b=solve(S,b) b= -(a*x^2 + c)/x So far we assumed f(x)=0. To solve f(x)=q(x) use the operator = =. For example >> syms x >> s=solve(cos(2*x)+sin(x)= =1) s= 0 pi/6 (5*pi)/6 Solve a system of algebraic equations x2 y2 = 0 x-y/2 = a >> syms x y alpha >> [solx,soly]=solve(x^2*y*2== 0, x-y/2 == alpha) solx = alpha 0 soly = 0 -2*alpha 34 Solve ordinary differential equations using command dsolve Let’s solve y’(t)=t*y >> syms y(t) >> y(t)=dsolve(diff(y) == t*y) y(t) = C2*exp(t^2/2) solve the same ODE with initial condition y(0)=2 >> syms y(t) >> y(t)=dsolve(diff(y) == t*y, y(0) == 2) y(t) = 2*exp(t^2/2) Solve a system of differential equations dDf/dt= 3 f(t)+4g(t) dDg/d= - 4 f(t)+3g(t) >> syms f(t) g(t) >> S=dsolve(diff(f) == 3*f + 4*g, diff(g) == -4*f + 3*g) S= g: [1x1 sym] f: [1x1 sym] >> f(t)=S.f %you must type this in to recover your solution from matrix S f(t) = C7*cos(4*t)*exp(3*t) + C6*sin(4*t)*exp(3*t) >> g(t)=S.g g(t) = C6*cos(4*t)*exp(3*t) - C7*sin(4*t)*exp(3*t) 35 APPENDIX A—DEBUGGING IN MATLAB To place your program in debugging mode, click the line next to a statement. The algorithm will run up to that statement and all values will be available to you. 36 APPENDIX B—CURVE FITTING Using the Curve Fitting Tool Find relevant information at the MATLAB HELP, data fitting (Interactive Curve Fitting) >> x=[1 2 3 4 5 6 7 8 9 10]; >> y=[5 8 6 0 2 6 8 1 5 3]; >> plot(x,y) MATLAB allows you to fit 1) a polynomial, 2) exponential, 3) Fourier, 4) Gausian, 5) Power, 6) Sum of Sine Functions and 7) Weibull. It also allows you to input your own function. Example 1. Fit a Polynomial >> cftool %opens the Curve Fitting Tool Choose Data Choose the x and y data vectors 37 Create data set and Close Choose Fitting and then, New Fit, Type of fit polynomial, 5th Degree Polynomial, Apply 38 Example 2. Fit Sum of Sin Functions Choose Fitting and then, New Fit, Type of fit polynomial, 5th Degree Polynomial, Apply 39 In-class work Fit the data e=[0 0.01 0.02 0.03 0.04 0.05] s=[0 500 900 1200 950 600 ]