Download presentation
Presentation is loading. Please wait.
Published byToby Johnston Modified over 8 years ago
1
INTRODUCTION TO MATLAB 1
2
OUTLINE: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display Facilities Flow Control Using of M-File Writing User Defined Functions Conclusion 2
3
W HAT IS M ATLAB ? Matlab is basically a high level language which has many specialized toolboxes for making things easier for us Assembly High Level Languages such as C, Pascal etc. Matlab 3
4
W HAT 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 4
5
MATLAB SCREEN Command Window type commands Current Directory View folders and m-files Workspace View program variables Double click on a variable to see it in the Array Editor Command History view past commands save a whole session using diary 5
6
V ARIABLES No need for types. i.e., All variables are created with double precision unless specified and they are matrices. After these statements, the variables are 1x1 matrices with double precision int a; double b; float c; Example: >>x=5; >>x1=2; 6
7
ARRAY, MATRIX a vector x = [1 2 5 1] x = 1 2 5 1 a matrixx = [1 2 3; 4 5 6;7 8 9] x = 1 2 3 4 5 6 7 8 9 transposey = x’ y = 1 4 7 2 5 8 3 6 9 7
8
LONG ARRAY, MATRIX 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] B = 1 2 3 4 5 6 7 8 8
9
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 9
10
M ATRIX I NDEX 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. 10
11
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. 11
12
OPERATORS (ARITHMETIC) +addition -subtraction *multiplication /division ^power ‘complex conjugate transpose 12
13
M ATRICES O PERATIONS Given A and B: AdditionSubtractionProductTranspose 13
14
OPERATORS (ELEMENT BY ELEMENT).*element-by-element multiplication./element-by-element division.^element-by-element power 14
15
T HE USE OF “.” – “E LEMENT ” O PERATION 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 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 15
16
BASIC TASK: PLOT THE FUNCTION SIN(X) BETWEEN 0≤X≤4Π Create an x-array of 100 samples between 0 and 4π. Calculate sin(.) of the x-array Plot the y-array >>x=linspace(0,4*pi,100); >>y=sin(x); >>plot(y) 16
17
PLOT THE FUNCTION E -X/3 SIN(X) BETWEEN 0≤X≤4Π Create an x-array of 100 samples between 0 and 4π. Calculate sin(.) of the x-array Calculate e -x/3 of the x-array >>x=linspace(0,4*pi,100); >>y=sin(x); >>y1=exp(-x/3); 17
18
PLOT THE FUNCTION E -X/3 SIN(X) BETWEEN 0≤X≤4Π Multiply the arrays y and y1 correctly Plot the y2-array >>y2=y.*y1; >>plot(y2) 18
19
D ISPLAY F ACILITIES plot(.) stem(.) Example: >>x=linspace(0,4*pi,100); >>y=sin(x); >>plot(y) >>plot(x,y) Example: >>stem(y) >>stem(x,y) 19
20
D ISPLAY F ACILITIES title(.) xlabel(.) ylabel(.) >>title(‘This is the sinus function’) >>xlabel(‘x (secs)’) >>ylabel(‘sin(x)’) 20
21
O PERATORS ( RELATIONAL, LOGICAL ) == Equal to ~= Not equal to < Strictly smaller > Strictly greater <= Smaller than or equal to >= Greater than equal to & And operator | Or operator 21
22
F LOW C ONTROL if for while break …. 22
23
C ONTROL S TRUCTURES If Statement Syntax if (Condition_1) Matlab Commands elseif (Condition_2) Matlab Commands elseif (Condition_3) Matlab Commands else Matlab Commands end Some Dummy Examples if ((a>3) & (b==5)) Some Matlab Commands; end if (a<3) Some Matlab Commands; elseif (b~=5) Some Matlab Commands; end if (a<3) Some Matlab Commands; else Some Matlab Commands; end 23
24
C ONTROL S TRUCTURES For loop syntax for i=Index_Array Matlab Commands end Some Dummy Examples for i=1:100 Some Matlab Commands; end for j=1:3:200 Some Matlab Commands; end for m=13:-0.2:-21 Some Matlab Commands; end for k=[0.1 0.3 -13 12 7 -9.3] Some Matlab Commands; end 24
25
C ONTROL S TRUCTURES While Loop Syntax while (condition) Matlab Commands end Dummy Example while ((a>3) & (b==5)) Some Matlab Commands; end 25
26
U SE OF M-F ILE Click to create a new M-File Extension “.m” A text file containing script or function or program to run 26
27
U SE OF M-F ILE If you include “;” at the end of each statement, result will not be shown immediately Save file as Denem430.m 27
28
W RITING U SER D EFINED F UNCTIONS 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) 28
29
W RITING U SER D EFINED F UNCTIONS 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 29
30
W RITING U SER D EFINED F UNCTIONS 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 30
31
N OTES : “%” 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 31
32
U SEFUL C OMMANDS The two commands used most by Matlab users are >>help functionname >>lookfor keyword 32
33
NUMERICAL SOLUTIONS OF NONLINEAR EQUATIONS Nonlinear algebraic equations are encountered in many scientific applications. fzero will solve single equations. Matlab’s fsolve command can solve system of equations. Nonlinearity implies potential for No solution Multiple solutions 33
34
Model Problem 34
35
Convert to Functions 35
36
HOW DOES FSOLVE WORK? This command finds the roots of systems of functions We supply a set of functions and Matlab will find all the independent variables such that all the functions are zero (or nearzero). 36
37
D EFINE F UNCTIONS Save this to a file called eqns.m 37
38
D EFINE F UNCTIONS 38
39
C ALLING THE SOLVER 39
40
ODE’S MATLAB has several routines for numerical integration ode45, ode23, ode113, ode15s, ode23s, 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. 40
41
INTEGRATION BY ODE23 AND ODE45: MATLAB COMMAND [t, x] = ode45(‘xprime’, [t 0,t f ], x 0 ) where xprimeis 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 ta (column) vector of time xan array of state variables as a function of time 41
42
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 42
43
DIFFERENTIAL EQUATION OF A SINGLE- VARIABLE 43
44
E XAMPLE 1: S TART - 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. Reaction: A → B Rate Kinetics: (-r A ) = k C A Initial Condition: at t=0, C A = C A,initial = 2 mol/L V 44
45
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 45
46
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; 46
47
S CRIPT F ILE : C OMMON S YNTAX 47
48
P URPOSE 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) 48
49
F UNCTION F ILE : C OMMAND S TRUCTURE 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) 49
50
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 50
51
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 51
52
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 52
53
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. 53
54
END OF SCRIPT FILE: COMMON SYNTAX 54
55
COMMAND FOR INTEGRATION OF DIFFERENTIAL EQUATION 55
56
EXAMPLE-1 enter the following MATLAB command [t, x]=ode45(‘cstr’,[0 500],[2]’); to see the transient response, use plot function plot(t, x); 56
57
E XAMPLE -2: M ULTI - VARIABLE D IFFERENTIAL E QUATIONS 57
58
E XAMPLE 2: CSTR R ESPONSE TO CHANGE IN VOLUMETRIC FLOW RATE. Objective: Solve differential mole balance on a CSTR using MATLAB integration routine. Problem description: CSTR operating at SS is subjected to a small disturbance in inlet volumetric flow rate while the outlet volumetric flow rate is kept constant. Both total mass balance and species mole balance must be solved simultaneously. Refer to Module3b class notes for more details. V 58
59
EXAMPLE 2 First-order differential equation in two-variables – V(t) and C A (t): Equations (1) and (2) must be solved simultaneously. (1) (2) 59
60
G ENERATING 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; 60
61
S CRIPT F ILE : N EW S YNTAX 61
62
RECOGNIZING MULTIVARIABLE SYSTEM function dx=cstr1 (t, x) % constant k=0.005; %mol/L-s vout=0.15; % L/s Ca0=10; %mol/L 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 the 2 variables 62
63
DEFINING ARRAYS % define x1 and x2 V=x(1,:) Ca=x(2,:) The value of these variables change as a function of time. This aspect is denoted in MATLAB syntax by defining the variable as an array. Thus variable 1 can be indicated as x(1,:) and variable 2 as x(2,:) For bookkeeping purposes or convenience sake, the two variables are re-defined as follows 63
64
DEFINING DIFFERENTIAL EQUATIONS % write the differential equation dx(1,:)=vin-vout; dx(2,:)=(vin/V)*(Ca0-Ca)-k*Ca; There are two differential equations – dV/dt and dCa/dt – that must be solved. These two equations are represented in vector form as “dx” Two differential equations must be defined. The syntax is shown below 64
65
END OF “SCRIPT FILE: NEW SYNTAX” 65
66
COMMAND FOR INTEGRATION OF DIFFERENTIAL EQUATION 66
67
EXAMPLE-2 enter the following MATLAB command [t, x]=ode45(‘cstr1’,[0 500],[10 7.5]’); to see the transient responses, use plot function plot(t, x(:,1); plot(t, x(:,2); Initial conditions for the two variables, i.e. V=10 L and CA=7.5 mol/L at time t=0 67
68
E XAMPLE -2 Type the following Matlab commands [t, x]=ode45('cstr1',[0:0.1:500],[10 ; 7.5]) Plot x1 and x2. 68
69
69
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.