matlabs

Information about matlabs

Published on July 24, 2014

Author: ashishgupta288

Source: authorstream.com

Content

MATLAB: MATLAB Times Institute of Management & Technical Studies TABLE OF CONTENTS: TABLE OF CONTENTS What is MATLAB? Why MATLAB? MATLAB Environment MATLAB Basics Matrices and Arrays Programming in MATLAB: Scripts and Functions Curve Fitting MATLAB Integral Plotting (2D & 3D) Graphics Printing Computer Algebra MuPAD Debugging Graphical User Interface WHAT IS MATLAB?: WHAT IS MATLAB? Matlab is basically a high level language which has many specialized toolboxes for making things easier for us How high? Assembly High Level Languages such as C, Pascal etc. Matlab WHAT ARE WE INTERESTED IN?: WHAT ARE WE INTERESTED IN? Matlab is too broad for our purposes in this course. The features we are going to require is Matlab Command Line m-files functions mat-files Command execution like DOS command window Series of Matlab commands Input Output capability Data storage/ loading WHY MATLAB?: WHY MATLAB? Common Uses for Matlab in Research Data Acquisition Multi-platform, Multi Format data importing Analysis Tools (Existing , Custom ) Statistics Graphing Modeling PowerPoint Presentation: Multi-platform, Multi Format data importing Data can be loaded into Matlab from almost any format and platform Binary data files ( eg . REX, PLEXON etc.) Ascii Text ( eg . Eyelink I, II) Analog/Digital Data files PC UNIX 100101010 Subject 1 143 Subject 2 982 Subject 3 87 … WHY MATLAB? PowerPoint Presentation: Analysis Tools A Considerable library of analysis tools exist for data analysis Provides a framework for the design, creation, and implementation of any custom analysis tool imaginable WHY MATLAB? PowerPoint Presentation: Graphing A Comprehensive array of plotting options available from 2 to 4 dimensions Full control of formatting, axes, and other visual representational elements WHY MATLAB? PowerPoint Presentation: Modeling Models of complex dynamic system interactions can be designed to test experimental data WHY MATLAB? MATLAB ENVIRONMENT: MATLAB ENVIRONMENT Matlab construction Core functionality as compiled C-code, m-files Additional functionality in toolboxes (m-files) Today: Matlab programming (construct own m-files) Core m-files C-kernel Sig. Proc Contr. Syst . User defined THE PROGRAMMING ENVIRONMENT: THE PROGRAMMING ENVIRONMENT The working directory is controlled by >> dir >> cd catalogue >> pwd The path variable defines where matlab searches for m-files >> path >> addpath >> pathtool >> which function PowerPoint Presentation: Matlab can’t tell if identifier is variable or function >> z=theta; Matlab searches for identifier in the following order variable in current workspace built-in variable built-in m-file m-file in current directory m-file on search path Note: m-files can be located in current directory, or in path THE PROGRAMMING ENVIRONMENT USING MATLAB: Solving equations using variables Matlab is an expression language Expressions typed by the user are interpreted and evaluated by the Matlab system Variables are names used to store values Variable names allow stored values to be retrieved for calculations or permanently saved Variable = Expression Or Expression **Variable Names are Case Sensitive! USING MATLAB >> x = 6 x = 6 >> y = 2 y = 2 >> x + y Ans = 8 >> x * y Ans = 12 >> x / y Ans = 3 >> x ^ y Ans = 36 PowerPoint Presentation: Working with Matrices Matlab works with essentially only one kind of object, a rectangular numerical matrix A matrix is a collection of numerical values that are organized into a specific configuration of rows and columns. The number of rows and columns can be any number Example 3 rows and 4 columns define a 3 x 4 matrix having 12 elements A scalar is a single number and is represented by a 1 x 1 matrix in matlab . A vector is a one dimensional array of numbers and is represented by an n x 1 column vector or a 1 x n row vector of n elements USING MATLAB BASIC MATLAB INTERFACE: BASIC MATLAB INTERFACE Command window: Type your instructions here and press ENTER to execute them. PowerPoint Presentation: Command history: a list of instructions executed by MATLAB is shown here. BASIC MATLAB INTERFACE PowerPoint Presentation: SIMPLE CALCULATIONS PowerPoint Presentation: ans Most recent answer. eps Floating point relative accuracy. pi π inf ∞ NaN Not a number. SOME SPECIAL VARIABLES AND CONSTANTS PowerPoint Presentation: abs(x) Absolute value sqrt(x) Square root sin(x) Sine asin(x) Inverse sine cos(x) Cosine acos(x) Inverse cosine tan(x) Tangent atan(x) Inverse tangent log(x) Natural logarithm exp(x) Exponential log10(x) Base 10 logarithm sign(x) Signum function SOME COMMON MATHEMATICAL FUNCTION PowerPoint Presentation: TO GET HELP If you want to see help, you can type help at the command window. Or click ? PowerPoint Presentation: Click here TO GET HELP PowerPoint Presentation: Example: search for function mean TO GET HELP PowerPoint Presentation: To create an m-file, 1) type edit at the command window , or 2) Press this button. CREATE AN M-FILE PowerPoint Presentation: The previous command will display the editor window. The editor creates an m-file that can be used to write your MATLAB programs. CREATE AN M-FILE PowerPoint Presentation: A lines starting with % --- is a comments CREATE AN M-FILE PowerPoint Presentation: SAVE AN M-FILE To save the file press Note the file name will be changed … PowerPoint Presentation: RUN AN M-FILE To execute a program, press the RUN button. PowerPoint Presentation: This window will appear. Press the Change Directory button. RUN AN M-FILE PowerPoint Presentation: You can see that the program has created new variables in the Workspace. RUN AN M-FILE PowerPoint Presentation: >> V = [1 3, sqrt (5)] V = 1.0000 3.0000 2.2361 >> A = [1 2 3;4 5 6;7 8 0] A = 1 2 3 4 5 6 7 8 0 ARRAYS ARRAY, MATRIX: ARRAY, MATRIX a vector x = [1 2 5 1] x = 1 2 5 1 a matrix x = [1 2 3; 5 1 4; 3 2 -1] x = 1 2 3 5 1 4 3 2 -1 transpose y = x’ y = 1 2 5 1 PowerPoint Presentation: t =1:10 t =1 2 3 4 5 6 7 8 9 10 k =2:-0.5:-1 k =2 1.5 1 0.5 0 -0.5 -1 B = [1:4; 5:8] x = 1 2 3 4 5 6 7 8 ARRAY, MATRIX GENERATING VECTORS FROM FUNCTIONS: GENERATING VECTORS FROM FUNCTIONS zeros(M,N) MxN matrix of zeros ones(M,N) MxN matrix of ones rand(M,N) MxN matrix of uniformly distributed random numbers on (0,1) x = zeros(1, 3 ) x = 0 0 0 x = ones (1, 3 ) x = 1 1 1 x = rand(1,3) x = 0.9501 0.2311 0.6068 MATRIX INDEX: MATRIX INDEX The matrix indices begin from 1 (not 0 (as in C)) The matrix indices must be positive integer Given: A(-2), A(0) Error: ??? Subscript indices must either be real positive integers or logicals. A(4,2) Error: ??? Index exceeds matrix dimensions. CONCATENATION OF MATRICES: CONCATENATION OF MATRICES x = [1 2], y = [4 5], z=[ 0 0] A = [ x y] 1 2 4 5 B = [x ; y] 1 2 4 5 C = [x y ;z] Error: ??? Error using ==> vertcat CAT arguments dimensions are not consistent. OPERATORS (ARITHMETIC): OPERATORS (ARITHMETIC) + addition - subtraction * multiplication / division ^ power ‘ complex conjugate transpose MATRICES OPERATIONS: MATRICES OPERATIONS Given A and B: Addition Subtraction Product Transpose OPERATORS (ELEMENT BY ELEMENT): OPERATORS (ELEMENT BY ELEMENT) .* element-by-element multiplication ./ element-by-element division .^ element-by-element power THE USE OF “.” – “ELEMENT” OPERATION: THE USE OF “.” – “ELEMENT” OPERATION K= x^2 Erorr: ??? Error using ==> mpower Matrix must be square. B=x*y Erorr: ??? Error using ==> mtimes Inner matrix dimensions must agree. A = [1 2 3; 5 1 4; 3 2 1] A = 1 2 3 5 1 4 3 2 -1 y = A(3 ,:) y= 3 4 -1 b = x .* y b= 3 8 -3 c = x . / y c= 0.33 0.5 -3 d = x .^2 d= 1 4 9 x = A(1,:) x= 1 2 3 PowerPoint Presentation: + Addition - Subtraction * Multiplication .* Element-by-element multiplication / division ./ Element-by-element division \ left division .\ Element-by-element left division ^ power .^ Element-by-element power ' array transpose .' Unconjugated array transpose ARRAYS OPERATORS PowerPoint Presentation: ARRAYS OPERATORS EXAMPLE A = [1 2 3;4 5 6;7 8 0] A = 1 2 3 4 5 6 7 8 0 A*A = 30 36 15 66 81 42 39 54 69 A.*A = 1 4 9 16 25 36 49 64 0 EXERCISES : EXERCISES Enter the following Matrices in matlab using spaces, commas, and semicolons to separate rows and columns: A = B = C = D = D = E = a 5 x 9 matrix of 1’s PowerPoint Presentation: Change the following elements in each matrix: A = B = C = D = D = E = a 5 x 9 matrix of 1’s 76 76 76 76 76 0 0 0 EXERCISES PowerPoint Presentation: SPECIAL MATRICES AND VECTORS Function Description zeros All zeros ones All ones rand Uniformly distributed random elements randne Normally distributed random elements Eye(n) Returns the n-by-n identity matrix. Z = zeros(2,4) Z = 0 0 0 0 0 0 0 0 F = 5*ones(3,3) F = 5 5 5 5 5 5 5 5 5 PowerPoint Presentation: BASIC OPERATIONS AND DESCRIPTIVE STATISTICS Function Description brush Interactively mark, delete, modify, and save observations in graphs cumprod Cumulative product cumsum Cumulative sum linkdata Automatically update graphs when variables change prod Product of array elements sort Sort array elements in ascending or descending order sortrows Sort rows in ascending order sum Sum of array elements corrcoef Correlation coefficients max Largest elements in array mean Average or mean value of array median Median value of array PowerPoint Presentation: Function Description cov Covariance matrix min Smallest elements in array mode Most frequent values in array std Standard deviation var Variance BASIC OPERATIONS AND DESCRIPTIVE STATISTICS PowerPoint Presentation: EXAMPLE A = [1 2 3; 3 3 6; 4 6 8; 4 7 7]; B = [2,7,8,3]; Prod (B) ans = 336   mean(A) % mean of each column ans = 3.0000 4.5000 6.0000   mean(A,2) % mean of each row ans = 2 4 6 6 PowerPoint Presentation: POLYNOMIALS Representing Polynomials Consider the equation To enter this polynomial into MATLAB, use p = [1 0 -2 -5];   PowerPoint Presentation: POLYNOMIAL FUNCTIONS Function Description conv Multiply polynomials deconv Divide polynomials poly Polynomial with specified roots polyder Polynomial derivative polyfit Polynomial curve fitting polyval Polynomial evaluation polyvalm Matrix polynomial evaluation residue Partial-fraction expansion (residues) roots Find polynomial roots PowerPoint Presentation: EXAMPLES To evaluate p at x=5, use   polyval (p,5) ans =110 X = [2 4 5; -1 0 3; 7 1 5]; Y = polyvalm ( p,X ) Y = 377 179 439 111 81 136 490 253 639 PowerPoint Presentation: Roots of Polynomials To find the roots p: r = roots(p)   r = 2.0946 -1.0473 + 1.1359i -1.0473 - 1.1359i   To find a polynomial that have the roots r: p2 = poly(r)   p2 =1.0000 -0.0000 -2.0000 -5.0000 EXAMPLES PowerPoint Presentation: Derivatives To obtain the derivative of the polynomial p = [1 0 -2 -5]; q = polyder(p) q = 3 0 -2 Polynomial curve fitting p = polyfit(x,y,n) finds the coefficients of a polynomial p(x) of degree n that fits the data, x(i) , y(i) x = 0: 0.1: 2.5; y = erf(x); p = polyfit(x,y,4) p = 0.0238 -0.0262 -0.4343 1.2840 -0.0096 EXAMPLES PowerPoint Presentation: Function Description Function 2 Description 3 norm Matrix or vector norm inv Matrix inverse rank Matrix rank subspace Angle between two subspaces det Determinant linsolve Solve a system of linear equations trace Sum of diagonal elements lu LU factorization null Null space chol Cholesky factorization orth Orthogonalization eig Eigenvalues and eigenvectors rref Reduced row echelon form expm Matrix exponential pinv Pseudoinverse funm Evaluate general matrix function LINEAR ALGEBRA FUNCTIONS PowerPoint Presentation: A=[1 -2 3;4 0 6; 2 -1,3] [L,U,P] = lu (A) A = 1 -2 3 4 0 6 2 -1 3 L = 1.0000 0 0 0.2500 1.0000 0 0.5000 0.5000 1.0000 U = 4.0000 0 6.0000 0 -2.0000 1.5000 0 0 -0.7500 P = 0 1 0 1 0 0 0 0 1 EXAMPLES PowerPoint Presentation: LINEAR SYSTEM OF EQUATIONS The system can be solved as: A = [1 0 3;0 5 6;7 8 0];b = [5;-2;3]; x = inv(A)*b x = 2.1765 -1.5294 0.9412 Or y= linsolve ( A,b ) y = 2.1765 -1.5294 0.9412 PROGRAMMING IN MATLAB: SCRIPTS AND FUNCTIONS: PROGRAMMING IN MATLAB: SCRIPTS AND FUNCTIONS M-file Flow control Scripts Function Programming tricks and tips Summary M FILE: M FILE There are four ways of doing code in Matlab. One can directly enter code in a terminal window. This amounts to using Matlabas a kind of calculator, and it is good for simple, low-level work. The second method is to create a script M-le. Here, one makes a file with the same code one would enter in a terminal window. When the le is \run", the script is carried out. The third method is the function M- file. This method actually creates a function, with inputs and outputs. The fourth method will not be discussed here. It is a way to incorporate C code or FORTRAN code into Matlab; this method uses .mex files. PowerPoint Presentation: function[x11,x12,x13,x21,x22,x23]=PCA(a,b,c) %Calculate the mean and population standard deviation of 3 species for i=1:5 d(i)=(a(i)-mean(a))^2; stda=sqrt(sum(d)/5); e(i)=(b(i)-mean(b))^2; stdb=sqrt(sum(e)/5); f(i)=(c(i)-mean(c))^2; stdc=sqrt(sum(f)/5); end %Obtain the z-scores of 3 species for i=1:5 za(i)=(a(i)-mean(a))/stda; zb(i)=(b(i)-mean(b))/stdb; zc(i)=(c(i)-mean(c))/stdc; end N=[za',zb',zc']; M FILE M FILE COND.: M FILE COND. %Obtain the original correlation matrix M=[1,corr(a,b),corr(a,c);corr(a,b),1,corr(b,c);corr(a,c),corr(b,c),1]; [V1,D1]= eig(M); %Calculate the eigenvector and eigenvalues weight1=V1(:,3); %Get the maximum eigenvector score1=N*weight1; %We use the exact same procedure that we used for axis 1, %except that we use a partial correlation matrix %The partial correlation matrix is made up of all pairwise correlations %among the 3 species, independent of their correlation with the axis 1 %sample scores. Hence, axis 2 sample scores will be uncorrelated %with (or orthogonal to) axis 1 scores. PowerPoint Presentation: new=[a,b,c,score1]; M2=[1,corr(a,b),corr(a,c),corr(a,score1);… corr(a,b),1,corr(b,c),corr(b,score1);… corr(a,c), corr(b, c), 1, corr(c,score1);… corr(a,score1),corr(b,score1),corr(c,score1),1]; for i=1:3 for j=1:3 corrnew(i,j)=M2(i,j); end end g=[M2(4,1)*M2(4,1),M2(4,1)*M2(4,2),M2(4,1)*M2(4,3);… M2(4,2)*M2(4,1),M2(4,2)*M2(4,2),M2(4,2)*M2(4,3);… M2(4,3)*M2(4,1),M2(4,3)*M2(4,2),M2(4,3)*M2(4,3)]; corrmatrix=corrnew-g; [V2,D2]=eig(corrmatrix); weight2=V2(:,3); %signs needs to be checked with JMP score2=N*weight2; M FILE COND. FLOW CONTROL - SELECTION: FLOW CONTROL - SELECTION The if-elseif-else construction if <logical expression> <commands> elseif <logical expression> <commands> else <commands> end if height>170 disp(’tall’) elseif height<150 disp(’small’) else disp(’average’) end LOGICAL EXPRESSIONS: LOGICAL EXPRESSIONS Relational operators (compare arrays of same sizes) == (equal to) ~= (not equal) < (less than) <= (less than or equal to) > (greater than) >= (greater than or equal to) Logical operators (combinations of relational operators) & (and) | (or) ~ (not) Logical functions xor isempty any all if (x>=0) & (x<=10) disp (‘x is in range [0,10]’) else disp (‘x is out of range’) end FLOW CONTROL - REPETITION: FLOW CONTROL - REPETITION Repeats a code segment a fixed number of times for index=<vector> <statements> end The <statements> are executed repeatedly. At each iteration, the variable index is assigned a new value from <vector>. for k =1:12 kfac =prod(1:k); disp ([num2str(k),’ ‘,num2str( kfac )]) end EXAMPLE – SELECTION AND REPETITION: EXAMPLE – SELECTION AND REPETITION function y=fact(n) % FACT – Display factorials of integers 1..n if nargin < 1 error(’No input argument assigned’) elseif n < 0 error(’Input must be non-negative’) elseif abs(n-round(n)) > eps error(’Input must be an integer’) end for k=1:n kfac=prod(1:k); disp([num2str(k),’ ’,num2str(kfac)]) y(k)=kfac; end; fact.m REPETITION: ANIMATION DEMO: REPETITION: ANIMATION DEMO The function movie replays a sequence of captured frames Construct a movie of a 360° tour around the Matlab logo % logomovie – make movie of 360 degree logo tour logo; no_frames=40; dtheta=360/no_frames; for frame = 1:no_frames, camorbit(dtheta,0) M(frame) = getframe(gcf); end % now display captured movie movie(gcf,M); logomovie.m FLOW CONTROL – CONDITIONAL REPETITION: FLOW CONTROL – CONDITIONAL REPETITION While-loops while <logical expression> <statements> End <statements> are executed repeatedly as long as the <logical expression> evaluates to true k=1; while prod(1:k)~=Inf, k=k+1; e nd disp([‘Largest factorial in Matlab:’,num2str(k-1)]); PowerPoint Presentation: Solutions to nonlinear equations can be found using Newton’s method Task : write a function that finds a solution to Given , iterate maxit times or until FLOW CONTROL – CONDITIONAL REPETITION PowerPoint Presentation: >> [x,n]=newton(0,1e-3,10) function [x,n] = newton(x0,tol,maxit) % NEWTON – Newton’s method for solving equations % [x,n] = NEWTON(x0,tol,maxit) x = x0; n = 0; done=0; while ~done, n = n + 1; x_new = x - (exp(-x)-sin(x))/(-exp(-x)-cos(x)); done=(n>=maxit) | ( abs(x_new-x)<tol ); x=x_new; end newton.m FLOW CONTROL – CONDITIONAL REPETITION SCRIPTS: SCRIPTS MATLAB simply executes the commands found in the file Example % Investigate the rank of magic squares r = zeros(1,32); %generation a row array 1X 32 % “;” tell the system does not display % the result on the screen for n = 3:32 r(n) = rank(magic(n)); end r bar(r) %display r in bar figure SCRIPTS COND.: SCRIPTS COND. Note: No input/output parameters (Different from functions! ) Write the script in editor, which can be activated by command “edit” in command window, save it with its specific name Next time you want to execute the script just call the name in the command window SCRIPT FILES: SCRIPT FILES Script-files contain a sequence of Matlab commands %FACTSCRIPT – Compute n-factorial, n!=1*2*...*n y = prod(1:n); factscript.m Executed by typing its name >> factscript Operates on variables in global workspace Variable n must exist in workspace Variable y is created (or over-written) Use comment lines (starting with %) to document file! DISPLAYING CODE AND GETTING HELP: DISPLAYING CODE AND GETTING HELP To list code, use type command >> type factscript The help command displays first consecutive comment lines >> help factscript MATLAB SCRIPT FILES: MATLAB SCRIPT FILES A MATLAB script file (Called an M-file) is a text (plain ASCII) file that contains one or more MATLAB commands and, optionally, comments. The file is saved with the extension ".m". When the filename (without the extension) is issued as a command in MATLAB, the file is opened, read, and the commands are executed as if input from the keyboard. The result is similar to running a program in C. The following slide is the contents of an M-file. Note that there are no prompts (>>). PowerPoint Presentation: There are two types of M-files…script files and function files. We start out with script files. Script files are called M-files because the extension on the file is “.m”. Script files are a collection of Matlab commands that when executed are the same as if the commands had been entered from the keyboard. Variables that are used in script files are equivalent to global variables. A variable that originates in a script file is immediately known in the command window. Variables that originated in the command window are known in the script file. This is one are in which script and function files differ. Function files, like C/C++ functions use local variables which must be passed in and out of the function. MATLAB SCRIPT FILES PowerPoint Presentation: % This is a MATLAB script file. % It has been saved as “g13.m". load g13.dat; %Load data file voltage = g13( : , 4); %Extract volts vector time = .005*[1:length(voltage)]; %Create time vector plot (time, voltage) %Plot volts vs time xlabel ('Time in Seconds') % Label x axis ylabel ('Voltage') % Label y axis title ('Bike Strain Gage Voltage vs Time') grid %Put a grid on graph MATLAB SCRIPT FILES PowerPoint Presentation: This example demonstrates several key things about Matlab script files. We’ve got the script file d13.m. In order to invoke it, Matlab’s current working directory must be the same directory as where d13.m is stored, or the entire pathname to the script file must be entered at the command prompt. The load d13.dat command will open the file, d13.dat. Because the entire pathname to d13.dat is not specified, the current working directory must contain d13.dat. The load will open the file and read the entire file into Matlab creating an array called d13 without the “. dat ” extension. Note the semicolon at the end of the line. This will prevent the contents of the array from being echoed to the command window. The second line creates a vector called voltage by reading in all of the rows in column 4 from the d13 matrix. Again, note the semicolon at the end of the line. The third line creates a time vector by multiplying 0.005 times a vector that has elements 1 to the length of the voltage vector. The fourth line plots the time on the x-axis and the voltage on the y-axis opening a new window that contains the plot. Lines 5 and 6 add labels to the x-axis and y-axis respectively. Line seven places a title on the plot and line eight puts a grid on the plot. MATLAB SCRIPT FILES PowerPoint Presentation: The preceding file is executed by issuing a MATLAB command: >> g13 This single command causes MATLAB to look in the current directory, and if a file g13.m is found, open it and execute all of the commands. The result, in this case, is a plot of the data from g13.dat. If MATLAB cannot find the file in the current working directory, an error message will appear. MATLAB SCRIPT FILES PowerPoint Presentation: As the slide indicates, the d13.m script file is executed by entering d13 at the command prompt when the current working directory is set to the same directory in which d13.m exists. If Matlab cannot find the file, it will display an error message. Note, that you can add to Matlab’s default search path so that files do not have to be located in the current directory. MATLAB SCRIPT FILES PowerPoint Presentation: When the file is not in the current working directory, a cd or chdir command may be issued to change the directory. >> cd a:\ % Make a:\ the current working directory >> g13 MATLAB SCRIPT FILES PowerPoint Presentation: If the script file that you want to execute is not in the current directory, then use the cd or chdir commands to move to the correct directory and then execute the script file. Note that there are icons at the top of the command window that allow you to use the mouse to navigate to the desired directory. This may be especially useful when you have some idea of the name or roughly where the file is located rather than knowing the exact name or path. In this example the file is stored on the a: drive at the root level. MATLAB SCRIPT FILES MATLAB DEMO: MATLAB DEMO %MATLAB Example use of ginput clear, clf , hold off axis ([0, 10, 0, 10]) hold on plot ([1, 2, 2, 1, 1],[2, 2, 3, 3, 2]) text (1, 1.6, 'Click inside box to quit') while 1 [x, y, buttun ] = ginput (1) if buttun == 1, plot (x, y, '+r'), end if buttun == 2, plot (x, y, ' oy '), end if buttun == 3, plot (x, y, '*g'), end if x > 1 & x < 2 & y > 2 & y < 3, break; end end hold off PowerPoint Presentation: Here we have another script file example…again this one has a lot packed into it. This script file collects mouse clicks and depending on which button was clicked, places a corresponding symbol on the plot window where the mouse was located at the time of the click. Line 1 issues three commands: clear removes all variables from memory, clf clears the figure window, and hold off turns off the plot holding. When the hold is on and multiple plot commands are issued, the plots will be placed on the same figure. In this script the hold is just being initialized to off. Line 2 sets the axis limits for the x and y axes of the plot window. The axis limits can be set at any time, even after the plot is drawn. It’s equivalent to changing the size of a window looking at the plot and gives you the ability to zoom in or out on different regions if you want. Line 3 turns the hold on, this way any plotting commands that are issued will cause the plotting to be on the same plot. MATLAB SCRIPT FILES PowerPoint Presentation: Line 4 plots a box on the graph and line 5 places the text string “Click inside box to quit” inside the box that was plotted, placing the beginning of the text at (1, 1.6). Line 5 starts a while loop that terminates with the second “end” statement. Since the condition of the while loop is “1”, it will operate forever, thus the only way to exit the while loop and terminate the program is to satisfy the final “if” condition within the loop which causes the “break” to execute and the while loop to terminate. Inside the while loop, on line 6, the Matlab function ginput () is used. It returns the x and y coordinates on the plot where the mouse button was clicked as well as which mouse button was clicked. Line 7 is an “if” statement that checks to see if mouse button 1 was clicked. If so, a red “+” is plotted on the graph at the ( x,y ) location where the mouse click was read. The “end” statement on the line ends this “if” condition. MATLAB SCRIPT FILES PowerPoint Presentation: Line 8 is an “if” statement that checks to see if mouse button 2 was clicked. If so, a yellow “o” is plotted on the graph at the (x,y) location where the mouse click was read. The “end” statement on the line ends this “if” condition. Line 9 is an “if” statement that checks to see if mouse button 3 was clicked. If so, a green “*” is plotted on the graph at the (x,y) location where the mouse click was read. The “end” statement on the line ends this “if” condition. Line 10 is the final “if” condition. It checks to see if the (x,y) coordinates of mouse click fall within 1<x<2 and 2<y<3, which are the limits of the text box. If so, then the “break” is executed and the while loop ends. Line 11 is the “end” statement for line 10. Line 12 is the “end” statement for the while loop. Line 13 turns off the plot hold, thus allowing multiple plot windows to be opened again. MATLAB SCRIPT FILES FUNCTIONS: FUNCTIONS Functions describe subprograms Take inputs, generate outputs Have local variables (invisible in global workspace) [output_arguments]= function_name(input_arguments) % Comment lines <function body> function [z]=factfun(n) % FACTFUN – Compute factorial % Z=FACTFUN(N) z = prod(1:n); factfun.m >> y=factfun(10); PowerPoint Presentation: Do we need to re-write newton.m for every new function? No ! General purpose functions take other m-files as input. >> help feval >> [f,f_prime]=feval(’myfun’,0); function [f,f_prime] = myfun(x) % MYFUN– Evaluate f(x) = exp(x)-sin(x) % and its first derivative % [f,f_prime] = myfun(x) f=exp(-x)-sin(x); f_prime=-exp(-x)-cos(x); myfun.m FUNCTIONS PowerPoint Presentation: Can update newton.m >> [x,n]=newtonf(’myfun’,0,1e-3,10) function [x,n] = newtonf(fname,x0,tol,maxit) % NEWTON – Newton’s method for solving equations % [x,n] = NEWTON(fname,x0,tol,maxit) x = x0; n = 0; done=0; while ~done, n = n + 1; [f,f_prime]=feval(fname,x); x_new = x – f/f_prime; done=(n>maxit) | ( abs(x_new-x)<tol ); x=x_new; end newtonf.m FUNCTIONS FUNCTION IN MATLAB: FUNCTION IN MATLAB Heavily used: integration, differentiation, optimization, … >> help ode45 Find the solution to the ordinary differential equation function x_dot = myodefun(t,x) % MYODEFUN – Define RHS of ODE x_dot(1,1)=x(2); x_dot(2,1)=-x(1)+0.1*(1-x(1)^2)*x(2); myodefun.m >> ode45(‘ myodefun ’,[0 10],[1;-10]); WRITING USER DEFINED FUNCTIONS : WRITING USER DEFINED FUNCTIONS Functions are m-files which can be executed by specifying some inputs and supply some desired outputs. The code telling the Matlab that an m-file is actually a function is You should write this command at the beginning of the m-file and you should save the m-file with a file name same as the function name function out1= functionname (in1) function out1= functionname (in1,in2,in3) function [out1,out2]= functionname (in1,in2) PowerPoint Presentation: Examples Write a function : out=squarer (A, ind) Which takes the square of the input matrix if the input indicator is equal to 1 And takes the element by element square of the input matrix if the input indicator is equal to 2 Same Name WRITING USER DEFINED FUNCTIONS PowerPoint Presentation: Another function which takes an input array and returns the sum and product of its elements as outputs The function sumprod(.) can be called from command window or an m-file as WRITING USER DEFINED FUNCTIONS NOTES: NOTES “%” is the neglect sign for Matlab (equaivalent of “//” in C). Anything after it on the same line is neglected by Matlab compiler. Sometimes slowing down the execution is done deliberately for observation purposes. You can use the command “pause” for this purpose pause %wait until any key pause(3) %wait 3 seconds USEFUL COMMANDS: USEFUL COMMANDS The two commands used most by Matlab users are >>help functionname >> lookfor keyword FUNCTIONS: FUNCTIONS Functions are M-files that can accept input arguments and return output arguments. The names of the M-file and of the function should be the same. FUNCTION EXAMPLE I: FUNCTION EXAMPLE I Background of AIC AIC is used to compare the quality of nested models AIC requires a bias-adjustment in small sample sizes FUNCTION HEAD (COMMENTS): FUNCTION HEAD (COMMENTS) %AICad Function %Date:Dec.29th, 2008 %Purpose: Calculate the adjusted % Akaike’s Information Criteria (AIC) %InPut: AIC % n (the sample size) % K (the number of parameters in the model) %OutPut: AICad % delta % weight %Functions Called: None %Called by: None IN COMMAND WINDOW: IN COMMAND WINDOW >>AIC=[-123; -241.7; -92.4; -256.9]; >>n=12; >>K=[4;8;2;6]; >> [AICad, delta, w] = CalAIC(AIC, n, K) AICad = delta = w = -83.0000 89.9000 0.0000 -97.7000 75.2000 0.0000 -80.4000 92.5000 0.0000 -172.9000 0 1.0000 PowerPoint Presentation: >>a=[66;48;26;15;11]; >>b=[25;30;55;20;50]; >>c=[24;31;42;49;58]; >>[score1, score2]=PCA(a,b,c) score1 = score2 = -2.2233 -0.1963 -1.1519 -0.0743 0.8734 -1.0888 0.4871 1.5120 2.0147 -0.1526 IN COMMAND WINDOW FUNCTION EXAMPLE II: FUNCTION EXAMPLE II Background of PCA Comparing more than two communities or samples Sample Post Oak Red Oak Water Oak 1 66 25 24 2 48 30 31 3 26 55 42 4 15 20 49 5 11 50 58 MATLAB FUNCTION FILES: MATLAB FUNCTION FILES A MATLAB function file (called an M-file) is a text (plain ASCII) file that contains a MATLAB function and, optionally, comments. The file is saved with the function name and the usual MATLAB script file extension, ".m". A MATLAB function may be called from the command line or from any other M-file. Lect 19 P. 99 Winter Quarter PowerPoint Presentation: Now that we’ve seen a script file, we’re going to move to function files. Function files in Matlab are very much like functions in C/C++. The key difference between function files and script files is that variables in function files are local. Any variables that are used within a function file need to be specified within the function or passed in as arguments in the argument list. You may want to point out the similarities between C/C++ functions and Matlab function files. One difference between the two is that while a C/C++ function can only “return” one value, Matlab functions can return as many as desired. The function file should have the same name as the function itself with the “.m” extension added to it. Unlike C/C++ functions which can only be called from within a program, Matlab function files can be called directly from the command window, from a script file, or from another function file. MATLAB FUNCTION FILES PowerPoint Presentation: When the function is called in MATLAB, the file is accessed, the function is executed, and control is returned to the MATLAB workspace. Since the function is not part of the MATLAB workspace, its variables and their values are not known after control is returned. Any values to be returned must be specified in the function syntax. MATLAB FUNCTION FILES PowerPoint Presentation: This first bullet points out the reason that variables inside of function files are local and not known to the command window is that executing a function file causes control to switch out of the Matlab workspace into the function file’s workspace. As the second and third bullet points indicate, the function file is not part of the Matlab workspace and therefore those variables that exist within the function file and their corresponding values are not known to the command window when control is returned from the function file. In order to transfer the values of desired variables back to the Matlab workspace, they must be passed back according to the function call syntax. What this boils down to is that variables that are being passed into the function need to appear in parentheses to the right of the function name during the function call and variables that are being passed back from the function to the Matlab workspace must appear in square brackets to the left of the equals sign in the function call and function definition. MATLAB FUNCTION FILES PowerPoint Presentation: The syntax for a MATLAB function definition is: function [val1, … , valn] = myfunc (arg1, … , argk) where val1 through valn are the specified returned values from the function and arg1 through argk are the values sent to the function. Since variables are local in MATLAB (as they are in C), the function has its own memory locations for all of the variables and only the values (not their addresses) are passed between the MATLAB workspace and the function. MATLAB FUNCTION FILES PowerPoint Presentation: Most of the information on this slide has been previewed on the previous slide. Arguments that are going into the function appear within parentheses to the right of the function name when the function is called. This is how you would get variables from the Matlab workspace or another function file into the called function. Values that are being determined within the function and returned by the function appear in square brackets prior to the equal sign on the line on which the function is called. These values will be returned by the function back to the Matlab workspace of the workspace of another function if this function were called within another function. Just as in C/C++, it’s the value of the variables that’s being passed. Addresses are NOT passed between workspaces. MATLAB FUNCTION FILES PowerPoint Presentation: It is OK to use the same variable names in the returned value list as in the argument. The effect is to assign new values to those variables. As an example, the following slide shows a function that swaps two values. Using the same variable names in the return list of a Matlab function call as in the argument list has the effect of assigning new values to those variables.. This is a key idea to get across. MATLAB FUNCTION FILES EXAMPLE OF A MATLAB FUNCTION FILE: EXAMPLE OF A MATLAB FUNCTION FILE function [ a , b ] = swap ( a , b ) The function swap receives two values, swaps them, and returns the result. The syntax for the call is [a, b] = swap (a, b) where the a and b in the ( ) are the values sent to the function and the a and b in the [ ] are returned values which are assigned to corresponding variables in your program. temp=a; a=b; b=temp; PowerPoint Presentation: Here we have an example of a swap function that has the same variables in its argument list as it does in its returned values list. In this example a and b are passed into the function. Within the function, temp is assigned a’s value, a is assigned b’s value and temp, which is a’s original value, is assigned to b. So, by the end of swap, the values of a and b have been swapped. Then, the swapped a and b are returned. To actually have the swap of a and b have an effect in the workspace that called swap requires that in the call to the function, the same variables were used in the calling “return” list and the calling “argument” list. A side note here…the comments that occur immediately after the first line of the function definition will be displayed in the command window if the user types help function_name at the command prompt. So, in this example, if the user were, at the command prompt, to type help swap, then the six comment lines that appear in the function definition above, would be displayed in the command window. EXAMPLE OF A MATLAB FUNCTION FILE PowerPoint Presentation: To use the function a MATLAB program could assign values to two variables (the names do not have to be a and b) and then call the function to swap them. For instance the MATLAB commands: >> x = 5 ; y = 6 ; [ x , y ] = swap ( x , y ) result in: x = 6 y = 5 EXAMPLE OF A MATLAB FUNCTION FILE PowerPoint Presentation: Here we see the result of calling the swap function. Note that the variables in the function call do not have to be a and b, since a and b are local to the function definition. What is necessary is that the variables in square brackets and in parentheses have the same name. When called with initial values of x=5 and y=6, swap switches the values of x and y in the calling workspace. Hopefully some carryover from C/C++ explanation of functions will help out here, but this is somewhat of an abstract point to get a grasp of and quite possibly should be gone over slowly on the board or with an example that demonstrates visually what is taking place. It is slightly different than what happens in the C/C++ examples of swap. EXAMPLE OF A MATLAB FUNCTION FILE PowerPoint Presentation: Referring to the function, the comments immediately following the function definition statement are the "help" for the function. The MATLAB command: >>help swap %displays: The function swap receives two values, swaps them , and returns the result. The syntax for the call is [ a, b] = swap (a, b) where the a and b in the ( ) are the values sent to the function and the a and b in the [ ] are returned values which are assigned to corresponding variables in your program. EXAMPLE OF A MATLAB FUNCTION FILE PowerPoint Presentation: As quickly mentioned on an earlier slide, when entering help function_name at the cojmmand prompt, the comment information that appears immediately beneath the first line of the function will be displayed as help information in the command window. MATLAB FUNCTION FILES PowerPoint Presentation: The MATLAB function must be in the current working directory. If it is not, the directory must be changed before calling the function. If MATLAB cannot find the function or its syntax does not match the function call, an error message will appear. Failure to change directories often results in the error message: Undefined function or improper matrix assignment. MATLAB FUNCTION FILES PowerPoint Presentation: A heads up for the students and a quick reminder…the Matlab function that is being called must exist in the current working directory, or be in a directory that is specified as part of Matlab’s default search path, otherwise Matlab will not be able to find the function and will return an error message. Not finding the function and finding the function but with a “signature” that does not match that of the function file, will result in an error message. That error message may be somewhat obtuse and may be along the lines of that given in the slide. So, it’s a good idea for both student and instructors to be on the lookout for error messages that do not appear to have anything to do with the problem at hand. MATLAB FUNCTION FILES PowerPoint Presentation: When the function file is not in the current working directory, a cd or chdir command may be issued to change the directory. >> cd a:\ % Make a:\ the current working directory MATLAB FUNCTION FILES PowerPoint Presentation: A reminder to make sure you change your working directory to the directory in which the function file exists prior to executing the function file. Either the cd or chdir commands can be used, as well as the icons at the top of the command window. MATLAB FUNCTION FILES PowerPoint Presentation: Unlike C, a MATLAB variable does not have to be declared before being used, and its data type can be changed by assigning a new value to it. For example, the function factorial ( ) on the next slide returns an integer when a positive value is sent to it as an argument, but returns a character string if the argument is negative. MATLAB FUNCTION FILES PowerPoint Presentation: As the slide indicates, Matlab is more flexible in dealing with variables changing their data types on the fly than C would be. All that is required to change the data type of a variable, is to assign the variable to a new value. After having gotten used to the strict data typing of C this might take students some practice to get used to. MATLAB FUNCTION FILES PowerPoint Presentation: function [n] = factorial (k) The function [n] = factorial(k) calculates and returns the value of k factorial. If k is negative, an error message is returned. if (k < 0) n = 'Error, negative argument'; elseif k<2 n=1; else n = 1; for j = [2:k] n = n * j; end end MATLAB FUNCTION FILES PowerPoint Presentation: Here we see the factorial function. It takes in argument “k” and returns value “n”. The main point here is that if k is less than zero, the factorial cannot be computed and n is assigned a string error message as its value. Otherwise, if the factorial can be computed, n is assigned the value of the factorial. So, on the fly Matlab is able to handle assigning to the same variable, different types of values. MATLAB FUNCTION FILES FLOW CONTROL EXAMPLES I: FLOW CONTROL EXAMPLES I Selector: 2-way: if rand < 0.3 %Condition flag = 0; %then_expression_1 else flag = 1; %then_expression_2 end % endif Multiple-ways: if A > B 'greater‘ elseif A < B 'less‘ elseif A == B 'equal‘ else error('Unexpected situation‘) end FLOW CONTROL EXAMPLES II: FLOW CONTROL EXAMPLES II Loop >>Generate a matrix for i = 1:2 for j = 1:6 H(i,j) = 1/(i+j); end end >>H H = 0.5000 0.3333 0.2500 0.2000 0.1667 0.1429 0.3333 0.2500 0.2000 0.1667 0.1429 0.1250 PowerPoint Presentation: Loop Cond. >>%Obtain the result is a root of the polynomial x 3 - 2x – 5 a = 0; fa = - Inf ; b = 3; fb = Inf ; while b-a > eps *b x = ( a+b )/2; fx = x^3-2*x-5; if sign( fx ) == sign( fa ) a = x; fa = fx ; else b = x; fb = fx ; end end >>x x = 2.09455148154233 FLOW CONTROL EXAMPLES II PROGRAMMING TIPS AND TRICKS: PROGRAMMING TIPS AND TRICKS Programming style has huge influence on program speed! tic; X=-250:0.1:250; for ii=1:length(x) if x(ii)>=0, s(ii)=sqrt(x(ii)); else s(ii)=0; end; end; toc tic x=-250:0.1:250; s=sqrt(x); s(x<0)=0; toc; slow.m fast.m Loops are slow: Replace loops by vector operations! Memory allocation takes a lot of time: Pre-allocate memory! Use profile to find code bottlenecks! SUMMARY: SUMMARY User-defined functionality in m-files Stored in current directory, or on search path Script-files vs. functions Functions have local variables, Scripts operate on global workspace Writing m-files Header (function definition), comments, program body Have inputs, generate outputs, use internal variables Flow control: ”if...elseif...if”, ”for”, ”while” General-purpose functions: use functions as inputs Programming style and speed Vectorization, memory allocation, profiler CURVE FITTING: Required Toolboxes: Statistics Toolbox Curve Fitting Toolbox Spline Toolbox CURVE FITTING PowerPoint Presentation: Curve fitting matches mathematical models to data Is a powerful tool if it can be used to make accurate predictions PURPOSE OF CURVE FITTING CURVE FITTING: CURVE FITTING Plotting a line of best fit in Matlab can be performed using either a traditional least squares fit or a robust fitting method. Robust Vs Least Squares Demo (robustdemo) 1 2 3 4 5 6 7 8 9 10 -2 0 2 4 6 8 10 12 Least squares Robust PowerPoint Presentation: A least squares linear fit minimizes the square of the distance between every data point and the line of best fit polyfit (X,Y,N) finds the coefficients of a polynomial P(X) of degree N that fits the data Uses least-square minimization N = 1 (linear fit) [ P] = polyfit (X,Y,N) returns P, a matrix containing the slope and the x intercept for a linear fit [Y] = polyval (P,X) calculates the Y values for every X point on the line of best fit CURVE FITTING PowerPoint Presentation: Example: Draw a line of best fit using least squares approximation for the data in exercise 2 [ var1, var2] = textread ('testdata2.txt','%f%f','headerlines',1) P = polyfit (var1,var2,1); Y = polyval (P,var1); close all figure(1) hold on plot(var1,var2,'ro') plot(var1,Y) CURVE FITTING PowerPoint Presentation: A least squares linear fit minimizes the square of the distance between every data point and the line of best fit A robust fit is less effected by small numbers of outliers P = robustfit(X,Y) returns the vector B of the y intercept and slope, obtained by performing robust linear fit ‘robustdemo’ gives a good graphical example comparing robust and least squares line fitting CURVE FITTING HIGHER ORDER CURVE FITTING: HIGHER ORDER CURVE FITTING Method 1 Polyfit can be used to calculate any polynomial fitting function of the form: y = polyval ( p,x ) returns the value of a polynomial of degree n evaluated at x. The input argument p is a vector of length n+1 whose elements are the coefficients in descending powers of the polynomial to be evaluated. x can be a matrix or a vector. In either case, polyval evaluates p at each element of x. CURVE FITTING: CURVE FITTING Example: Calculate a polynomial fit of order 2, 3, and 4 for the data in the previous example CURVE FITTING EXAMPLE: CURVE FITTING EXAMPLE 2 nd Order Polynomial Fit: %read data [var1, var2] = textread (‘week8_testdata2.txt','%f%f','headerlines',1) % Calculate 2 nd order polynomial fit P2 = polyfit (var1,var2,2); Y2 = polyval (P2,var1); % Plot fit close all figure(1) hold on plot(var1,var2,'ro') [sortedvar1, sortind] = sort(var1) plot(sortedvar1,Y2(sortind),'b*-') PowerPoint Presentation: 2ND ORDER POLYNOMIAL FIT 2 nd Order payment fit CURVE FITTING EXAMPLE: CURVE FITTING EXAMPLE Add 3 rd Order Polynomial Fit: % Calculate 3 rd order polynomial fit P3 = polyfit (var1,var2,3); Y3 = polyval (P3,var1); % Add fit to figure figure(1) plot(sortedvar1,Y3(sortind),’g*-') PowerPoint Presentation: 2nd Order Polynomial Fit: 3rd Order Polynomial Fit: CURVE FITTING EXAMPLE PowerPoint Presentation: Add 4 th Order Polynomial Fit: % Calculate 4 th order polynomial fit P4 = polyfit (var1,var2,4); Y4 = polyval (P4,var1); % Add fit to figure figure(1) plot(sortedvar1,Y4(sortind),’k*-') CURVE FITTING EXAMPLE PowerPoint Presentation: 2nd Order Polynomial Fit: 3rd Order Polynomial Fit: 4th Order Polynomial Fit: CURVE FITTING EXAMPLE ASSESSING GOODNESS OF FIT: ASSESSING GOODNESS OF FIT The tough part of polynomial regression is knowing that the "fit" is a good one. Determining the quality of the fit requires experience, a sense of balance and some statistical summaries. PowerPoint Presentation: One common goodness of fit involves a least-squares approximation. This describes the distance of the entire set of data points from the fitted curve. The normalization of the residual error minimizing the square of the sum of squares of all residual errors. The coefficient of determination (also referred to as the R 2 value) for the fit indicates the percent of the variation in the data that is explained by the model. ASSESSING GOODNESS OF FIT PowerPoint Presentation: This coefficient can be computed via the commands: ypred = polyval ( coeff,x ); % predictions dev = y - mean(y); % deviations - measure of spread SST = sum(dev.^2); % total variation to be accounted for resid = y - ypred ; % residuals - measure of mismatch SSE = sum(resid.^2); % variation NOT accounted for normr = sqrt (SSE) % the 2-norm of the vector of the residuals for the fit Rsq = 1 - SSE/SST; % R 2 Error (percent of error explained) The closer that Rsq is to 1, the more completely the fitted model "explains" the data. ASSESSING GOODNESS OF FIT PowerPoint Presentation: Example: Calculate the R 2 error and Norm of the residual error for a 2 nd order polynomial fit for the data in the previous example ASSESSING GOODNESS OF FIT PowerPoint Presentation: Example Solution % recall var1 contains x values and var2 contains y values of data points ypred = polyval(P2,var1); dev = var2 - mean(2); SST = sum(dev.^2); resid = var2 - ypred; SSE = sum(resid.^2); normr = sqrt(SSE); Rsq = 1 - SSE/SST; Normr = 5.7436 Rsq = 0.8533 The residual norm and R 2 error indicate goodness of fit 2nd Order Polynomial Fit: ASSESSING GOODNESS OF FIT LIMITATIONS OF POLYFIT: LIMITATIONS OF POLYFIT Only finds a least squares best polynomial function fit Cannot be used to interpolate curves or fit other standard functions Requires several lines of code and the polyval() function HIGHER ORDER CURVE FITTING: HIGHER ORDER CURVE FITTING Method 2 Curve Fitting Tools can be accessed directly from the figure window: To access curve fitting directly from the figure window, select ‘basic fitting’ from the ‘tools’ pulldown menu in the figure window. This is a quick and easy method to calculate and visualize a variety of higher order functions including interpolation PowerPoint Presentation: Method 2 Plot data from previous exercise Try a variety of curve fittings HIGHER ORDER CURVE FITTING PowerPoint Presentation: Caution: Higher order polynomial fits should only be used when a large number of data points are available Higher order polynomial fitting functions may fit more the data more accurately but may not yield an interpretable model HIGHER ORDER CURVE FITTING PowerPoint Presentation: Method 2 Curve Fitting from Figure Window Advantages: Quick and easy to plot fits from existing data Easy accessibility of: Function Coefficients Fitting Equations Residual errors The value of fitting function at any value of x HIGHER ORDER CURVE FITTING PowerPoint Presentation: Method 3 Curve Fitting Toolbox The curve fitting toolbox is accessible by the ‘ cftool ’ command Very powerful tool for data smoothing, curve fitting, and applying and evaluating mathematical models to data points HIGHER ORDER CURVE FITTING CURVE FITTING TOOLBOX: CURVE FITTING TOOLBOX 1. Loading Data Sets Before you can import data into the Curve Fitting Tool, the data variables must exist in the MATLAB workspace. You can import data into the Curve Fitting Tool with the Data GUI. You open this GUI by clicking the Data button on the Curve Fitting Tool. The Data Sets pane allows you to: Import predictor (X) data, response (Y) data, and weights. If you do not import weights, then they are assumed to be 1 for all data points. Specify the name of the data set. Preview the data. Click the Create data set button to complete the data import process. PowerPoint Presentation: 2. Smoothing Data Points If your data is noisy, you might need to apply a smoothing algorithm to expose its features, and to provide a reasonable starting approach for parametric fitting. The two basic assumptions that underlie smoothing are: The relationship between the response data and the predictor data is smooth. The smoothing process results in a smoothed value that is a better estimate of the original value because the noise has been reduced. CURVE FITTING TOOLBOX PowerPoint Presentation: 2. Smoothing Data Points The Curve Fitting Toolbox supports these smoothing methods: Moving Average Filtering: Lowpass filter that takes the average of neighboring data points. Lowess and Loess: Locally weighted scatter plot smooth. These methods use linear least squares fitting, and a first-degree polynomial ( lowess ) or a second-degree polynomial (loess). Robust lowess and loess methods that are resistant to outliers are also available. Savitzky-Golay Filtering: A generalized moving average where you derive the filter coefficients by performing an unweighted linear least squares fit using a polynomial of the specified degree. CURVE FITTING TOOLBOX PowerPoint Presentation: Smoothing Method and Parameters Span: The number of data points used to compute each smoothed value. For the moving average and Savitzky-Golay methods, the span must be odd. For all locally weighted smoothing methods, if the span is less than 1, it is interpreted as the percentage of the total number of data points. Degree: The degree of the polynomial used in the Savitzky-Golay method. The degree must be smaller than the span. CURVE FITTING TOOLBOX PowerPoint Presentation: Excluding Data Points It may be necessary to remove outlier points from a data set before attempting a curve fit Typically, data points are excluded so that subsequent fits are not adversely affected. Can help improve a mathematical model’s predictability CURVE FITTING TOOLBOX PowerPoint Presentation: Excluding Data Points The Curve Fitting Toolbox provides two methods to exclude data: Marking Outliers: Outliers are defined as individual data points that you exclude because they are inconsistent with the statistical nature of the bulk of the data. Sectioning: Sectioning excludes a window of response or predictor data. For example, if many data points in a data set are corrupted by large systematic errors, you might want to section them out of the fit. For each of these methods, you must create an exclusion rule , which captures the range, domain, or index of the data points to be excluded. CURVE FITTING TOOLBOX PowerPoint Presentation: Plotting Fitting Curves You fit data with the Fitting GUI. You open this GUI by clicking the Fitting button on the Curve Fitting Tool. CURVE FITTING TOOLBOX PowerPoint Presentation: Plotting Fitting Curves The Fit Editor allows you to: Specify the fit name, the current data set, and the exclusion rule. Explore various fits to the current data set using a library or custom equation, a smoothing spline , or an interpolant . Override the default fit options such as the coefficient starting values. Compare fit results including the fitted coefficients and goodness of fit statistics. CURVE FITTING TOOLBOX PowerPoint Presentation: Plotting Fitting Curves The Table of Fits allows you to: Keep track of all the fits and their data sets for the current session. Display a summary of the fit results. Save or delete the fit results. CURVE FITTING TOOLBOX PowerPoint Presentation: Analyzing Fits You can evaluate (interpolate or extrapolate), differentiate, or integrate a fit over a specified data range with the Analysis GUI. You open this GUI by clicking the Analysis button on the Curve Fitting Tool. CURVE FITTING TOOLBOX PowerPoint Presentation: Analyzing Fits To Test your Model’s Predictions: Enter the appropriate MATLAB vector in the Analyze at Xi field. Select the Evaluate fit at Xi check box. Select the Plot results and Plot data set check boxes. Click the Apply button. The numerical extrapolation results are displayed CURVE FITTING TOOLBOX PowerPoint Presentation: Saving Your Work You can save one or more fits and the associated fit results as variables to the MATLAB workspace. You can then use this saved information for documentation purposes, or to extend your data exploration and analysis. In addition to saving your work to MATLAB workspace variables, you can: CURVE FITTING TOOLBOX PowerPoint Presentation: Saving Your Work Generating an M-file: You may want to generate an M-file so that you can continue data exploration and analysis from the MATLAB command line. You can run the M-file without modification to recreate the fits and results that you created with the Curve Fitting Tool, or you can edit and modify the file as needed CURVE FITTING TOOLBOX PowerPoint Presentation: Saving Your Work Generating an M-file: The M-file captures: All data set variable names, associated fits, and residuals Fit options such as whether the data should be normalized, the fit starting points, and the fitting method You can recreate the saved fits in a new figure window by typing the name of the M-file at the MATLAB command line. Note that you must provide the appropriate data variables as inputs to the M-file. These variables are given in the M-file help. CURVE FITTING TOOLBOX PowerPoint Presentation: Exercise Load the data file ‘week8_testdata2.txt’ from week 8 Use the curve fitting toolbox smooth the data using a 5 point moving average Exclude all points with y values less then -1 Fit a 4 th order polynomial through the smoothed data points Generate an m-file that can be used to re-calculate the fitted curve CURVE FITTING TOOLBOX MATLAB ROUTINES: MATLAB ROUTINES MATLAB has several routines for numerical integration ode45, ode 23, ode 113, ode 15s, ode 23s, etc. Here we will introduce two of them: ode45 and ode23 ode23 uses 2 nd -order and ode45 uses 4 th -order Runge-Kutta integration. We will learn more about Runge-Kutta method in the class. INTEGRATION BY ODE23 AND ODE45: MATLAB COMMAND: INTEGRATION BY ODE23 AND ODE45: MATLAB COMMAND [t, x] = ode45(‘xprime’, [t 0 ,t f ], x 0 ) Where, Xprime is a string variable containing the name of the m-file for the derivatives. t 0 is the initial time t f is the final time x 0 is the initial condition vector for the state variables t a (column) vector of time x an array of state variables as a function of time NOTE: NOTE We need to generate a m-file containing expressions for differential equations first. We’ll examine common syntax employed in generating the script or m-file These objectives will be achieved through 2 examples: Example-1 on Single-Variable Differential Equation Example-2 on Multi-Variable Differential Equation DIFFERENTIAL EQUATION OF A SINGLE-VARIABLE : DIFFERENTIAL EQUATION OF A SINGLE-VARIABLE EXAMPLE 1: START-UP TIME OF A CSTR : EXAMPLE 1: START-UP TIME OF A CSTR Objective: Solve differential mole balance on a CSTR using MATLAB integration routine. Problem description: A CSTR initially filled in 2mol/L of A is to be started up with specified conditions of inlet concentration, inlet and outlet flow rates. The reactor volume and fluid density is considered to be constant. Refer to Module3b class notes for more details. Reaction : A → B Rate Kinetics : (-r A ) = k  C A Initial Condition : at t=0, C A = C A,initial = 2 mol/L V EXAMPLE 1: EXAMPLE 1 The following first-order differential equation in single-variable (C A ) is obtained from mole balance on A: Recall, that mass balance yields GENERATING A M-FILE TITLED CSTR.M: GENERATING A M-FILE TITLED CSTR.M function dx=cstr (t, x) % define constants k=0.005; %mol/L-s V=10; % Reactor volume in L vin=0.15; % Inlet volumetric flow rate in L/s Ca0=10; % Inlet concentration of A in mol/L %For convenience sake, declaring that variable x is Ca Ca=x %define differential equation dx=(vin/V)*Ca0-(vin/V+k)*Ca; Purpose of function files: Purpose of function files As indicated above, the function file generates the value of outputs every time it called upon with certain sets of inputs of dependent and independent variables For instance the cstr.m file generates the value of output (dx), every time it is called upon with inputs of independent variable time (t) and dependent variable (x) NOTE : For cstr.m file, the output dx is actually dCa/dt and x is equal to Ca. function dx=cstr (t, x) function output=function_name (input1, input2) SCRIPT FILE: COMMON SYNTAX FUNCTION FILE: COMMAND STRUCTURE : FUNCTION FILE: COMMAND STRUCTURE function dx = CSTR (t, x) Define constants (e.g. k, Ca0, etc.) (Optional) Write equations in terms of constants Define differential equations that define outputs ( dx =…) function output=function_name (input1, input2) FILE & FUNCTION NAME: FILE & FUNCTION NAME Example: m-file titled cstr.m function dx=cstr (t, x) % define constants k=0.005; %mol/L-s V=10; % Reactor volume in L Function name should match file name INPUTS AND OUTPUTS: INPUTS AND OUTPUTS Example: m-file titled cstr.m function dx=cstr (t, x) % define constants k=0.005; %mol/L-s V=10; % Reactor volume in L Inputs are independent variable (t) and dependent variable (x=Ca) Output is differential, dx = dCa/dt WRITING COMMENTS: WRITING COMMENTS Example: m-file titled cstr.m function dx=cstr (t, x) % define constants k=0.005; %mol/L-s V=10; % Reactor volume in L Any text written after “ % ” symbol is considered to be commented SEMICOLON AT THE END OF AN EXPRESSION: SEMICOLON AT THE END OF AN EXPRESSION Example: m-file titled cstr.m function dx=cstr (t, x) % define constants k=0.005; %mol/L-s V=10; % Reactor volume in L Semi-colon simply suppresses SCREEN printing of the expression. GENERATING THE SCRIPT FILE: GENERATING THE SCRIPT FILE dx=cstr1 (t, x) %constant k=0.005; %mol/L-s vout=0.15; % L/s Ca0=10; %mol/L % The following expression describe disturbance in input flow rate if(t <=2) vin=0.15+.05*t elseif(t<=4) vin=0.25-0.05*(t-2); else vin=0.15; end % define x1 and x2 V=x(1,:) Ca=x(2,:) % write the differential equation dx(1,:)=vin-vout; dx(2,:)=(vin/V)*(Ca0-Ca)-k*Ca; SCRIPT FILE: NEW SYNTAX: SCRIPT FILE: NEW SYNTAX RECOGNIZING MULTIVARIABLE SYSTEM: RECOGNIZING MULTIVARIABLE SYSTEM The first important point to note is that x is a vector of 2 variables, x1 (=V) and x2(=Ca) Also, dx is a vector of two differential equations associated with th

Related presentations