matlab primer for che 225 - george n....

13
MATLAB primer for CHE 225 The following pages contain a brief description of the MATLAB features are used in CHE 225. This document is best used in conjunction with the MATLAB codes posted on Vista.

Upload: vandung

Post on 02-Aug-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

MATLAB primer for CHE 225 The following pages contain a brief description of the MATLAB features are used in CHE 225. This document is best used in conjunction with the MATLAB codes posted on Vista.

Find root of a single function using fzero fzero(@function_file_name, #guess) or… fzero(@(variable_name)variable_expression, #guess) Examples: f(x)=x3-3x+1 Function file named fun2.m function f = fun2(x) f = x^3-3*x+1; >> fzero(@fun2, 1) ans = 1.5321 >> fzero(@(x)x^3-3*x+1,1) ans = 1.5321 Notes: This example illustrates the use of a function file. See function files f.m, fun.m and myfun.m for additional examples of function files

Common loop structures: for-end and while-end: The following is not the complete code. For codes, please refer to the script files posted on Vista. For-End Note: Please read this explanation in conjunction with the file nrfor.m Be sure to include your guess values outside of the loop because the loop will successively change the value of that variable within the loop. for i=1:100 This means that for each of 100 iterations, this loop is to be run if e<emax break end

The if-statement is necessary to stop the loop when an acceptable result has been achieved

end While-End Note: Please read this explanation in conjunction with the file nrwhile.m Be sure to include your guess values outside of the loop because the loop will successively change the value of that variable within the loop. Before starting the loop, error must be specified: e=error>emax This is necessary to ensure that the loop actually begins (if the error value “e” is an unspecified variable, then it has a value of zero and the loop will stop there, giving you your guess value as the final answer) while e>emax

This means that while the error is still larger than the maximum desired error, then the loop will continue running

n=n+1 This statement changes the number “n” to match the number of iterations, ensuring that your if-statement will serve its desired purpose if n=100

break end

The if statement is necessary so that, in the event that your method does not lead you to an acceptable root, the computer will not be hung indefinitely

end

Matrix Building

- Commas or spaces designate numbers in new columns - Semicolons designate a break to the next row

Example: >> A=[1,0,1;0,1,0;0,0,1] 1 0 1 0 1 0 0 0 1 Cell referencing: Using matrix A created above: 1 0 1 0 1 0 0 0 1 Reference the highlighted number with this function: new_variable = reference_matrix(row, column) Example: >> a=A(3,2) a = 0

Find the solutions to a set of linear equations using linsolve: Given that matrix A is a square (n X n) matrix, and matrix B is a corresponding (n X 1) matrix, then: >> inv(A) ans = [inverse matrix of A] >> linsolve(A,B) ans = [(n X 1) matrix with solutions to unknown variables] Use either inv(A)*B or ;linsolve function to achieve same result

Find solutions to multiple non-linear equations using fsolve: Designate variables using variable_name(#) as shown in example function file below: System of equations: 2x-y-e-x=0 -x+y-e-y=0 Assign x=x(1), y=x(2) in function file function F=myfun(x) F=[2*x(1)-x(2)-exp(-x(1)) -x(1)+x(2)-exp(-x(2))]; The guess is a matrix corresponding to how many unknown variables you have: [xguess, yguess] >> fsolve(@myfun,[1,1]) Optimization terminated: first-order optimality is less than options.TolFun. ans =

0.7847 1.1132 Notes: The syntax of the function file is extremely important for the fsolve function to give you results in MATLAB. To be a 100% sure, write equation in the same format as shown above. For instance, write 2*x(1) instead of x(1)*2. Stick to the same notation/convention.

Utilizing dot operator in MATLAB: Unlike conventional matrix operations involving multiplication, division, or powers, dot multiplication in MATLAB allows for a special case of end-prodcuts: Example: A= 1 2 B= 3 6 4 2 4 7 >> A.*B ans= 3 12 16 14 >> A./B

ans = 0.3333 0.3333 1.0000 0.2857 >> B.^2

ans = 9 36 16 49 Integrate difficult functions using quad: f(x)=x2+2x+1 NOTICE: you must use the dot operator in all instances in which there is a power, multiplication, or division symbol. (Technically, the dot is not necessary next the the constant 2 in 2.*x, but it does not hurt to put it) function f=quadfun(x) f=x.^2+2.*x+1 >> quad(@quadfun,0,1)

ans = 2.3333

Approximate the area under a curve using trapz: Suppose you have a table of data points where Y is dependent on X: X x1 x2 x3 x4 x5 x6 x7 X8 x9 x10 Y y1 y2 y3 y4 y5 y6 y7 Y8 y9 y10 >> X=[x1, x2, x3, …., x10]; >> Y=[y1, y2, y3, …., y10]; The following function will give you an approximation of the area under the plotted curve using the trapezoidal method: >> trapz(X,Y)

Import data from Microsoft Excel for use in MATLAB: xlsread(‘filename.xls’,’Sheet_in_xlsfile’,’range_of_values’) Example: xlsread(‘extraction_graphs.xls’, ‘Sheet1’,’B3:C12’) The above function will create a (10 X 2) matrix of the values located in the cells B3:C12 Note: excel has default sheet names such as Sheet1, Sheet2, and Sheet3, which have no space between the word and the number. Export data from MATLAB to Microsoft Excel: xlswrite(‘filename.xls’,matrix_name, ’Sheet_in_xlsfile’,’range_of_values’) Example: If the matrix you want to export is labeled “A” then: xlsread(‘extraction_graphs.xls’, A, ‘Sheet1’,’B3:C12’) It is also equally effective to simply copy date from the workspace in MATLAB and paste it directly into your excel file.

Numerical solution of ODEs in MATLAB We will go over this topic using the example of reactions in series. Consider the reactions This results in a system of three simultaneous ODEs This results in a system of three simultaneous ODEs. We will solve these differential equations using MATLAB. To follow along, please refer to the function file seriesf.m and the script file series.m (in conjunction with the notes below) Step 1: Creating the Function File We will create a function file seriesf.m that contains the differential equations. % This function file gives the differential equations governing the % concentrations of the following set of reactions % c(1) ----> c(2)------> c(3) % The rate constants are 0.01/s for the first reaction and 1000/s for % the second reaction function dc = seriesf(t,c) dc = [ -0.01*c(1) 0.01*c(1)-1000*c(2) 1000*c(2)]; end Key things to keep in mind

1) seriesf(t,c) – the independent variable has to be specified even though it never occurs in the differential equations as in this case

2) Assign each independent variable to each element of the array (Ca = c(1) and so on)

3) The variable assigned to the function (in this case dc) is also an array. In this case, it will have 3 elements; dc(1) corresponds to dCa/dt and so on.

4) Note that you can use these concepts to set up function files for ANY number of differential equations.

Step 2: Creating the script file The script file instructs MATLAB to solve the differential equation using initial conditions and plot the results. The following code is in “series.m”. Let us break down the code. Note that some parts of the code are omitted for clarity. clear all tfin = 0.05; % time for which the simulation is run c10=1; % initial concentrations c20=0; c30=0; In the above section, we are specifying the initial concentrations and the final time point tn = tfin/100; tf = 0:tn:tfin; %this statement can be used to create an array with multiple elements. In this case the array starts at 0 and has elements with spacing of tn until tfin Note the usage of the “:” operator in this case. The variable tf is an array that starts at 0, ends at tfin and has elements that are spaced apart by tn. Thus in this case, tf is [0 0.0005 0.0010 … 0.05] %use this in conjunction with the function M-file seriesf.m (whuch %contains the differential eqiations. The equations are solved using %two different solvers [t1, c1]=ode45(@seriesf, tf, [c10 c20 c30]); %uses ode45 1) The variable t1 will contain time points at which concentrations are calculated. In this case t1 will be the time points specified by tf. Alternately, you can replace tf with

[ start time <space> end time] e.g. [0 0.05]. When you do this, MATLAB decides suitable time points at which the concentrations need to be calculated (i.e. adaptive step-size determination) 2) The variable c1 is an array that contains 3 columns. The first column corresponds to the first variable in the ODE set (In this case c(1) i.e. Ca), the second corresponds to c(2) and so on. The rows of c1 give the values at different time points given in t1 3) ode45 – this is the name of the MATLAB solver used 4) Specify the function file which contains the differential equation using the @ operator i.e. @seriesf in this case 5) @seriesf is followed by the times over which the ODEs need to be solved. As explained in (1), use a variable such as tf or [0 0.05] 6) Finally, specify the initial conditions. Number of initial conditions needs to be the same as number of differential equations [t2, c2]=ode15s(@seriesf, tf, [c10 c20 c30]); %uses ode15s Same as previous case, except uses a stiff solver. Use a stiff solver when the equations are stiff – typically occurs when time scales in the ODE are vastly different. In this case very slow first reaction (k1 =0.01) relative to fast second reaction (k2 = 1000) plot(t1, c1(:,2), '-b', t2, c2(:,2), '-r') % blue - ode45, red - ode15s 1) The syntax is Plot (xvalue1, yvalue1, how to plot #1 i.e. color, style etc, xvalue2, yvalue2, how to plot #2, … and so on 2) Note use of the “:” operator – c1(:,2) means plot all data points in all rows of the second column of the variable c1 3) The “how to plot it” contains 3 elements – color, symbol and connector (i.e. line or dotted line or dashed line etc). The three elements are put within quotes. The three elements can be chosen from the following list

b blue . point - solid

g green o circle : dotted r red x x-mark -. dashdot c cyan + plus -- dashed m magenta * star (none) no line y yellow s square k black d diamond w white v triangle (down) ^ triangle (up) < triangle (left) > triangle (right) p pentagram h hexagram So in this case ‘--cs’ will create a dashed line with cyan color and square symbols at the data points.