Академический Документы
Профессиональный Документы
Культура Документы
In Bioprocess Engineering
For
Introduction to MATLAB 3
Part 1 Basics 4
2
Introduction to MATLAB.
The command window is the main window in which you communicate with the
MATLAB interpreter. The MATLAB displays a prompt (>>) indicating that is ready to
accept commands from you.
The command diary causes a copy of all subsequent terminal input and most of the
resulting output to be written on the named file. DIARY OFF suspends it. DIARY ON
turns it back on. DIARY, by itself, toggles the diary state. By typing diary followed by
the name of an already existing file, input will be appended to that file.
Using this diary command you will be able to document your work.
3
Part 1
BASICS
4
Vectors and matrices can be appended to build larger matrices, e.g. E=[A,B;C,D]
To disable the echoing results you could include a semicolon after each command
line.
To check existing list, you could type who or whos
To extract elements:
a) A(1,2) gives the element at row 1 and column 2
b) A(3,:) gives the third row of A
c) A(:,4) gives the fourth column of A
d) A([3,2],[2,1]) extracts rows 3 and 2, and columns 2 and 1
To remove rows and columns:
a) A(2,:)=[] removes the 2nd row
b) A(:,1)=[] removes the 1st column
Reshaping and vectorization
a) A(:) yields a vectorized column
[a11 ; a21 ; …;a n1 ; …; a1n; …;a nn]
b) reshape(A,m,n) yields a matrix of size m by n by
building it column-wise
5
19. column-wise sum s=sum([1,2,3;4,5,6])
( = [ 5,7,9] )
20. column-wise product p=prod([1,2,3;4,5,6])
( = [ 4, 10, 18] )
sorting
21. sort cols in ascending order V = sort(A)
if A = [ 5, 3 ] then V= [ 1, 3 ]
[ 1, 4 ] [5, 4 ]
22. sorting and getting indices [V,K] = sort(A)
Elementwise operation: precede operator by a dot, e.g. A.*B, A./B, A.^2
III. Plotting
2D plots
plot(x,y) uses default
plot(x,y,x,z) combines plot of y vs x and z vs x
plot(x,y,'-',x,z,'--') specifies how each plot is drawn:
solid line for x-y and dashed for x-z
Labeling
xlabel('Time (sec)') labeling the x-axis
ylabel('Temperature') labels the y-axis
title('Case 1') puts title on top of plot
text(1.2, 3.0, 'Case 1') puts text on specified location
gtext('Case 2') text is place with the aid of the mouse
(or use the menu bar in the figure window)
6
mesh(x,y,z) mesh plot
surf(x,y,z) surface plot
surfl(x,y,z) surface plots with lighting
shading interp smoothens shading scheme as interpolated
colormap(gray) changes coloring scheme to gray scale
brighten(-0.5) darkens picture ( if >0 then it brightens)
view([10,60]) changes view to azimuth=10 o and
elevation=60o
IV. Printing
print sends plot to printer
print h:\sample1.ps saves the plot as a file
print -deps h:\sample2.eps specifies format
(or you can use the menu in the figure window)
V. Workspaces
clear erases all variables
clear a, B, Temperature erases only specified variables
diary h:\case1.dry saves all terminal activity and saves in file
case1.dry
save h:\assign1.mat saves workspace
save h:\assign1.mat a, B
saves only specified variables
save h:\assign1.mat a, B -ascii
saves in ascii format
load h:\assign1.mat loads workspace
load h:\data1.any loads from a file and creates a
matrix named data1
( or you can use menu items for importing data and changing paths)
7
- Method 3: using “ones”, “zeros” and “repmat”
c) Permuting arrays
permute(A,[2,1,3]) changes the dimension indexing,
(where 1,2,3 are the this is essentially like the transpose, except
dimensions, not sizes) it applies on any dimension.
VII. Structures
Features/Motivation:
- helps encapsulate and organize information of different types
- uses text fields, instead of numeric fields
- can be collected as arrays
- can have subfields
- most commands require the options to come from structures
- most commands can output to structures
a) Creating Structures
- Method 1: Use period to create fields and subfields
student.IDNumber=1234;
student.Name='Hank Hill';
- Method 2: Use the struct command
student=struct('IDNumber',1234,...
'Name','Hank Hill');
- For building structure arrays, just start numbering
student(2)=struct('IDNumber',5678,...
'Name','Robert Plant');
b) Extracting Information: just type the structure name including the fields
student(2)
student(2).Name
c) Removing fields
student = rmfield( student , 'IDNumber' )
8
- Instead of matrices, cell arrays can have different types of elements
a) Creation:
Use assignments with “curly brackets”
A = { [1,2;3,4], ‘Testing’; {[1,2] ;3}} , 3+5i }
b) Extracting information:
A{1,1} should yield the element in {1,1}
A{2,1}{1,1} assuming element {2,1} is a cell,
then extracts the {1,1}th element
IX. M-files
Features/Motivation
- using the Matlab editor or any text editor such as notepad
- to write a user-define function that could take different inputs and yields
different outputs
- collect subfunctions together for better organization of files
- several Matlab functions need user-supplied functions in forms of m-files.
9
% c) norm = sqrt( y' * y )
y = A*x;
if nargin==3
y = y + b;
end
if nargout == 2, % if norm is required
norm=y'*y;
end
10
Part 2.
Ordinary Differential Equations
y(0) = 2
d/dt y(0) = -1
2. You need to convert to state space form. Let x1 = y and x2 = dy/dt, then we have
3. Next, create an m-file using either Matlab's editor or any text editor, e.g. "notepad":
function dx = tutorialEqn1(t,x)
% x is the state vector
% to minimize parentheses you could put them
% in other variables
x1=x(1);
x2=x(2);
% write the state equations
dx1 = x2;
dx2 = -3*x2 -2*x1 +4*exp(-2*t) - 5;
% collect the derivatives into a column vector
dx = [dx1;dx2];
then save as an m-file, e.g. tutorialEqn1.m
4. In matlab, you can now invoke the ode solvers. For example, you can use ode45
command:
11
Remarks:
a) Use the '@' symbol followed by the filename (without the file extension)
b) [0 10] is the range of time values
c) [2;-1] is the initial condition
d) [t,x] is the solution output. t stores the time values while x stores the solution
where column 1 is x(1), etc.
6. Passing of parameters: you can also pass parameters (either scalar of matrix). For
instance, suppose you want to simulate the matrix equation: dx/dt = Ax. Then you can
use the general function:
function dx = lindiff(t,x,A)
dx = A*x;
Scenario: since ode45 may not have fixed integration points, you may need to
interpolate. Another alternative is to use the command deval .
However, this requires that the solution output is a structure.
Example: (assuming file lindiff.m given in item 6 above already exists)
>> A=[0 1;-2 -2];
>> testSoln = ode45(@lindiff,[0 10],[0 -1],[],A);
>> new_t=linspace(0,10,101);
>> new_y=deval(testSoln,new_t);
This will result in an output that is uniformly incremented in t=0.1
8. Changing Options.
This requires creating a structure object conforming to ODE45. To create, use odeset.
12
For a list of available fields,
>> testOptions=odeset
This should list all the fields with empty (defaulted) values.
So, for example if we want to change the relative tolerance to 1e-5, and absolute
tolerance to [1e-4;1e-2] we could use
>> testOptions=odeset('RelTol',1e-5,'AbsTol',...
[1e-4;1e-2])
After all changes have been included, run the simulation using the created options
structure,
Example The combustion of methane in oxygen can be represented by the chemical equation
Our task is to determine the unknown coefficients x1, x2, x3, and x4. There are three elements
involved in this reaction: carbon (C), hydrogen (H), and oxygen (O).
We write these as homogeneous equations, each having zero on its right hand side:
x1 – x3 = 0
4x1 – 2x4 = 0
2x2 – 2x3 – x4 = 0
To complete the system, we define an auxiliary equation by arbitrarily choosing a value for one
of the coefficients:
x4 = 1
A= 1 0 –1 0
4 0 0 –2
0 2 –2 –1
13
00 0 1
x= x1 x2 x3 x4
b= 00 0 1
After starting MATLAB, we enter the matrix A and the column vector b. (In what follows, » is
the MATLAB prompt.)
Next we compute x = A–1b, in which A–1 is the inverse of A. The function inv() computes
matrix inverses:
» x = inv(A)*b
x= 0.5000
1.0000
0.5000
1.0000
Finally, we note that the stoichiometric coefficients are usually chosen to be integers. Divide the
vector x by its smallest value:
» x = x/0.5
x= 1
2
1
2
14
Part 3.
Simulink® Basics
1. A simple example.
Suppose you want to model the response of a first order process model given by the
following equation.
dT/ dt = 1/ Tin )
T (0) = T 0
where is the residence time parameter, Tin is the inlet temperature and T is the
temperature of the continuously stirred tank.
>> simulink
( Alternatively, you can use the Matlab launch pad and double click on
Simulink icon. )
A model window should now pop out. This is where we will be adding our simulation
blocks.
Step 3. Import blocks from the Library Browser to the Model window.
15
Figure 1.
Next, in the Library Browser, select the "Sources" subdirectory (left side).
On the right side of the Browser, select the "Step" block and drag-drop it
into the Model window.
Finally, in the Library Browser, select the "Sinks" subdirectory (left side).
On the right side of the Browser, select the "Scope" block and drag-drop it
into the Model window.
After all these blocks have been imported, the blocks can be moved around to
match the positions shown in Figure 2.
16
Figure 2.
At this point, it may be instructive to layout the roles and connections among
these five blocks:
17
Finally, double-click the Gain Block. Another parameter window should popout.
Suppose we want to use a value of = 4 for our time constant. This
means the reciprocal, (1/=0.25. Thus, in the parameter window for the Gain
block, change the gain from 1 to 0.25, and click [OK]. ( In the Model window,
the value of 0.25 might not show. You can resize the Gain block by clicking
on it once, and then dragging the black corners to resize it.)
Method 2: Manual.
Try connecting the Gain block with the Integrator block. First, move the
cursor to the left port of the Gain block until the cursor changes to a cross
symbol. Next, click-drag the cursor to the input port of the Integrator (a
dotted line should be dragging behind), then release the mouse-click.
Using either method 1 or method 2 to connect the blocks to match Figure 9.
Figure 9.
Next, we need to tap into (i.e. split) the T signal that goes to the Scope block,
and feed it back to the Sum block. First, position the cursor somewhere in the
middle portion of the signal line connecting the Integrator block and the
Scope block as shown in Figure 9. Next, while depressing the CTRL key,
click-drag the cursor (which should turn to a cross once you depressed the right
button of the mouse) until it is positioned on top of the "minus" port of the Sum
block, then release the buttons. A new split line should appear. (You can
resize the signal line by clicking on it once and then dragging the black
corners.) We now have the final configuration for our model shown in Figure
3.
Figure3.
18
Step 5. Perform the simulation.
[Simulation parameters...]
To see the results, double-click the Scope block. A figure with a plot should
pop out. To see the whole plot, click the “Autoscale” button.
Go to the Simulink Library Browser and select the Sinks subdirectory (on the
left side). From the right side of the browser, drag-drop the [To Worskspace]
block into the Model window and drag another split signal to this block.
Double-click the [To Workspace] block. A parameter window should pop-out.
[Simulation
parameters...] submenu once more. This time choose the [Workspace I/O]
tab. Click on the Time variable and change the name from tout to time. Also, near
the bottom of the window, change the Format to: Array. Click [OK].
Start the simulation by clicking the “Run” button. Next, go back to the Matlab
command window. You should now have the two vectors available in the
workspace: time and T, which you can plot or perform other forms of data
processing via Matlab commands.
19
b) Invoking a Simulink run from Matlab command window.
Sometimes, it may be more efficient to run the simulation from the command
window. For instance, you could change parameters for a range of say 10 values
using a script file and then collect the results in a structure or a file for further
processing.
- To read the value of 'Gain' parameter in the Gain block, use the following
command:
>> g_svalue=get_param('simple/Gain','Gain')
Remarks:
i) The string, 'simple/Gain', identifies the Gain block in the
model we called simple (since we saved the model as
simple.mdl earlier).
Tip: If you are unsure about the path name for a block, you can first
go to the model window and click on the block of interest. Then go
back to the Matlab command window and type the command gcb,
(which stands for "get current block"):
>> gcb
ans =
simple/Gain
ii) The second string, 'Gain', is one of the parameters in the parameter
window. Another parameter you could try to read is
'Multiplication', among others.
Note: This command line will yield a string result. To change the
string to a numeric value, you will need to use the Matlab function:
str2num, i.e.
>> g_value=str2num(g_svalue)
g_value = 0.2500
>> set_param('simple/Gain','Gain','0.30')
Note: The input for the 'Gain' parameter is a string, hence we used '0.30'.
If you go back to the model window, the value shown in the Gain block
should have changed from 0.25 to 0.30.
- To run the Simulink simulation from a command window, type the following:
>> sim('simple')
-
Example: Suppose you want to run the Simulink model, simple, which
20
we have built so far, for several values of gain and graph the results all
together in a single plot. One way is to use create a script file as shown below
and run it.
%
% Script file for running the Simulink model 'simple'
% for different values of gain
open_system('simple')
% Initializations
% ===============
tagCollect =[] ;
timeCollect =[] ;
TCollect =[] ;
plotcolors ='bgcmkbgcmkbgcmk' ;
nvals = 0 ;
% Calculations
% ============
for gval=0.2:0.2:1.0
nvals = nvals + 1 ;
gvalStr = num2str(gval,3) ;
set_param('simple/Gain','Gain',gvalStr) ;
sim('simple') ;
timeCollect = [timeCollect, time] ;
TCollect = [TCollect, T] ;
tag = ['Gain = ',gvalStr] ;
tagCollect = [tagCollect,{tag}] ;
end
end
% Plotting
% ========
hold off
for i=1:nvals
plot(timeCollect(:,i),TCollect(:,i),plotcolors(i));
hold on
end
hold off
legend(tagCollect) ;
xlabel('Time (mins)') ;
ylabel('Temperature (^oF)') ;
Remarks:
i) We included a line :
open_system('simple')
This is to make sure the Model is open prior to the use of commands
set_param and sim. (If the model, simple, is already open, it will not do
anything.)
ii) The variable plotcolors is a string array that would indicate the colors
used for plotting. For example, 'bcg' will mean the sequence black, cyan,
green.
iii) tagCollect is a cell array, so be careful to use the curly brackets as written
in the script. We use a cell array because this is what is required by the
21
command legend.
iv) Note the use of commands, hold on and hold off to allow the plot
command not to erase previous plots.
v) Since when using set_param, the gain value should be a string, we need to
convert the numeric value of gval to a string as follows:
gvalStr = num2str(gval,3) ;
where 3 signifies the string will show three significant figures.
Part 4.
Subsystems in Simulink®
Suppose we want to model the control of the temperature and flow rate as shown in
Figure 1.
where the temperature of the flow out is described by the following equation:
Remarks:
i) To rename a block, double-click the name and then change the text.
ii) To change the direction of the ports in Mult3 block, right click and
the select [Format] [Rotate block] twice.
_
iii) To change the direction of the outport of block Sum1, right-click and
22
select [Format] [Rotate block] once.
_
b) Next, layout the blocks and connect the blocks to match Figure 1.
[Select All].
b) From the menu again, select [Edit]
_
[Create Subsystem].
c) Rename the subsystem to be : Temperature Mixing Subsystem.
d) Resize the subsystem and move the inports and outports so they match
Figure 2.
Figure 2.
23
Note: You can “open” the subsystem by double-clicking the subsystem block.
(you can continue to edit the subsystem when the subsystem is opens as a
separate window).
Table 2.
Figure 3
24
i) Click on the "Go to Parent"-button. This would send you back to the
Model window.
j) Right-click on "PI Temperature Controller" and select [Copy].
Right-click at a different position in the Model window and select
[Paste]. Rename the new subsystem block as "PI Flow
Controller".
k) Go back to the Simulink Library Browser and add some more blocks into
the Model window as described in Table 3.
25
Figure 4
26
Part 5
Finding Steady States and Linearization via Simulink®
2. Build a Simulink model
function dx = bioreactor(t,x,D,x2f)
%
% model for bioreactor process
% where, x1 = biomass concentration
% x2 = substrate concentration
% D = dilution rate
% x2f= substrate feed
x1 = x(1) ;
x2 = x(2) ;
mumax = 0.53 ; % hr^(-1)
km = 0.12 ; % g/liter
k1 = 0.454 ; % liter/g
Y = 0.4 ; %
mu = mumax*x2/(km+x2+k1*x2^2) ;
dx1 = (mu - D)*x1 ;
dx2 = D*(x2f-x2)-mu*x1/Y ;
dx = [dx1;dx2] ; function [sys,x0,str,ts]= ...
bioreactor_sfcn(t,x,u,flag, ...
x1_init,x2_init)
switch flag
case 0 % initialize
str=[] ;
ts = [0 0] ;
s = simsizes ;
s.NumContStates = 2 ;
s.NumDiscStates = 0 ;
s.NumOutputs = 2 ;
s.NumInputs = 2 ;
s.DirFeedthrough = 0 ;
s.NumSampleTimes = 1 ;
sys = simsizes(s) ;
x0 = [x1_init, x2_init] ;
case 1 % derivatives
D = u(1) ;
x2f = u(2) ;
sys = bioreactor(t,x,D,x2f);
27
case 3 % output
sys = x ;
case {2 4 9} % 2:discrete,
% 4:calcTimeHit,
% 9:termination
sys =[] ;
otherwise
error(...
['unhandled flag =',...
num2str(flag)]) ;
end
>> X0=[];
>> U0=[0.3;4];
>> Y0=[];
>> IX=[];
28
>> IU=[1;2];
>> IY=[];
Remarks:
i) X0, U0 and Y0 are the state vector, input vector and output vector that will be
fixed while the function attempts to find the steady state. Note that since we
will not constrain the states and outputs, we can set these to null.
ii) IX, IU and IY indicates which values of X0, U0 and Y0 will be held
fixed. In our case, we want both input vector to be fixed, so we set
IU = [1;2].
b) run the trim function:
>> [X,U,Y,DX]=TRIM('bioreactor_sys',X0,U0,Y0,IX,IU,IY);
>> X
X =
0.9943
1.5141Thus, the function found X=(0.9943,1.5141) as the steady state.
4. Linearization via the linmod function. >>
[A,B,C,D]=linmod('bioreactor_sys',X,U0);
29
Reference:
3) Introduction to MATLAB 6 for Engineers, William J Palm III, McGraw Hill Publishers, 2001
30