Вы находитесь на странице: 1из 30

A Short Tutorial on Matlab

In Bioprocess Engineering

For

III year B.Tech Biotechnology


Contents

Introduction to MATLAB 3

Part 1 Basics 4

(i) Assigning values to variables,vectors and matrices


(ii) Matrix operations
(iii) Plotting
(iv) Printing
(v) Workspaces
(vi) Multidimensional Arrays
(vii) Structures
(viii) M-files

Part 2 Ordinary differential equations 11

Using MATLAB for calculating stoichiometric


co-efficients 13

Part 3 Simulink Basics 15

Part 4 Subsystems in Simulink 22

Part 5 Steady states & Linerization via Simulink 27

2
Introduction to MATLAB.

MATLAB is a high performance language for technical computing. It integrates


computation, visualization, and programming in an easy-to-use environment. MATLAB
is an interactive system whose basic data element is an array that does not require
dimensioning.

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.

Before beginning this exercise type the following


>> diary L1.txt

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.

The following section provides an overview of the basic syntax of MATLAB


(Parts of this document are taken from the MATLAB demonstration file).

3
Part 1

BASICS

I. Assigning Values to Variables, Vectors and Matrices


Use the equality symbol, e.g. A=3
Variables are case sensitive: temperature is not the same as Temperature
To check values, just type the variable name
There are special constants already available, e.g. pi, Inf
For complex numbers, either use 3+2i or 3+2j
Vectors and matrices are enclosed with square brackets:
a) Elements of rows are separated by commas: A=[1,2,3]
b) Elements of columns are separated by semicolons: B=[1;2;3]
c) Matrices can be seen as columns of row vectors, C=[1,2,3;4,5,6]
Alternatively, use spaces to separate row elements and return keys for column
elements:
B = [ 1 2 3
4 5 6
1 0 1]
To get size information,
a) size(A) yields [# rows, # cols]
b) size(A,1) yields # rows
c) size(A,2) yields # cols
d) length(v) yields # elements in vector v
Some shortcuts are available:
a) A = 1:0.1:2 yields a row vector [1, 1.1, 1.2, … , 1.9, 2]
b) diag([1,2,3]) yields a diagonal matrix [1,0,0 ; 0,2,0 ; 0,0,3]
c) diag([1,2,3],1) yields a matrix
[ 0,1,0,0 ; 0,0,2,0 ; 0,0,0,3 ; 0,0,0,0 ]
d) eye(4) yields an identity matrix of size 4x4
e) zeros(3) yields a matrix of zeros of size 3x3
f) zeros(size(A)) yields a matrix of zeros
having the same size as A
g) ones(3), ones(2,5), ones(size(A))
works the same as zeros() except it produces
a matrix of ones
h) rand(m,n) matrix of uniformly distributed
random numbers of size m by n
i) randn(m,n) matrix of normally distributed random
numbers of size m by n
j) linspace(a,b,n) creates a vector of n elements
linearly spaced from a to b
k) logspace(a,b,n) creates a vector of n elements
logarithmically spaced from 10 a to 10b

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

II. Matrix Operations and other operations


matrix operations
1. addition C=A+B
2. multiplication C=A*B
3. determinant c=det(A)
3. inverse inv(A) or A^(-1)
4. right division C=B/A (same as C=B*inv(A) )
5. left division C=A\B (same as C= inv(A)*B )
6. transpose C=A.' ( Note: C=A' is conjugate
transpose)
7. exponentiation B=A^3
8. matrix exponentiation B=expm(A)
9. rank R=rank(A)
10. eigenvalue/eigenvectors [Eigenvals,Eigenvecs] = eig(A)
11. characeristic polynomial p = poly(A)
12 Kronecker product C=kron(A,B)
14. trace t=trace(A)
15. pseudo-inverse M = pinv(A)
polynomials
16. roots of polynomial R = roots([ 1, 4, 2] )
( = roots of s2+4s+2=0 )
17. polynomial, given roots p=poly([r1,r2])
18. polynomial multiplication p=conv( [1, 4, 2],[-2, 3] )
( = (s2 + 4s + 2)(-2s+3) )
column-wise operation

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)

You can use a limited version of TeX formatting for


a) greek letters and other symbols (see TeX manual)
' \alpha \nabla T ' yields a text : 
b) subscript and superscripts:
'T_{surround}^{a+b}' yields a text : Tsurround
a+b

Axis settings
axis([0,10,-1,1]) specifies x-range as 0 to 10,
and y-range as -1 to 1
axis('square') makes the plot square
axis returns to automatic axis mode
hold freezes the previous plot

3D plots
[x,y]=meshgrid(-10:0.5:10, -2:0.2:2)
initializes x and y matrices
( for the following try z=sin(x/2).*sin(y) )

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)

VI. Some helpful tips


help grabs help information from
functions or script files
cursor up and down keys scrolls through previous commands

VI. Multidimensional Arrays

a) Creating arrays of higher dimensions


- Method 1: set using assignments
Given: A=[1,2; 3,4]
Then type: A(:,:,2)= [11, 22; 33, 44]
- Method 2: using cat function
Given: A=[1,2 ; 3,4]
B = [11 , 22; 33, 44]
Then type: C=cat(3,A,B)

7
- Method 3: using “ones”, “zeros” and “repmat”

b) Dimensions and Reshaping arrays


ndims(A) gets the number of dimensions of A
size(A) gets the size of each dimension of A
reshape(A,[m,n,p]) reshapes A into a multidimensional
array of size [m,n,p] by first collecting
all elements of A in a column and then
distributing according to the specified
size.

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' )

VIII. Cell Arrays


Features/Motivation
- Cell arrays are similar to structures except you use numeric indices.

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

c) Translating to structures and vice versa:


C=cell2struct(A(:),...
{'matrix','name','vector','cell'})
D=struct2cell(C); this converts structure C to cell array
arranged in a column
E=reshape(D,2,2); this will reshape cell array D

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.

a) Example 1. ( simple function )


function y = example1(A,x,b)
%
% y = example1(A,x,b)
% ===================
%
% solves for y=Ax+b
%
%
%
y = A*x + b ;

b) Example 2. ( different inputs and outputs)


function [y,norm] = example2(A,x,b)
%
% [y,norm] = example2(A,x,b)
% ==========================
%
% obtains
% a) y = Ax+b
% b) or y = Ax if b not included

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

c) Example 3. ( includes subfunctions)


function ynorms = example3(Y)
%
% ynorms = example3(Y)
% ====================
%
% obtains ynorms = [ ynorm1, ..., ynormn ]
% where ynormi= xnorm( y(:,i) )
% xnorm(x) = sqrt(x'*x)
%
nycols = size(Y,2);
ynorms =[];
for i = 1:nycols
ycol = Y(:,i);
ynorms=[ynorms, newnorm(ycol)];
end
function xnorm = newnorm(x);
xnorm = sqrt(x'*x);

10
Part 2.
Ordinary Differential Equations

1. Suppose we want to simulate the following set of differential equations:

subject to the following initial conditions,

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:

>> [t,x]=ode45(@tutorialEqn1,[0 10],[2;-1])

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.

5. You can now plot the solutions. For instance,


>> plot(t,x(:,1))
will plot the first column of x.

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;

Suppose, we have defined matrix A to be


>> A = [-3 4 0;0 -1 2;3 3 -6];

with intial condition vector


>> x0 =[ -1 ; 2 ;0.5 ];

then use the following command:


>> [t,x]=ode45(@lindiff,[0 100],x0,[],A);
Note: the '[]' between x0 and A is required as a placeholder for options (see
below, item 8).

7. Evaluating solutions at specified points

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])

To add more changes,


>> testOptions=odeset(testOptions,'Refine',10)

After all changes have been included, run the simulation using the created options
structure,

>> [t,y] = ode45(@lindiff,[0 5],[0 -1],testOptions,A);

Using MATLAB for calculating stoichiometric coefficients

Example The combustion of methane in oxygen can be represented by the chemical equation

x1CH4 + x2O2 x3CO2 + x4H2O

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).

A balance equation can be written for each of these elements:

Carbon (C): 1×x1 + 0×x2 = 1×x3 + 0×x4


Hydrogen (H): 4×x1 + 0×x2 = 0×x3 + 2×x4
Oxygen (O): 0×x1 + 2×x2 = 2×x3 + 1×x4

We write these as homogeneous equations, each having zero on its right hand side:
x1 – x3 = 0
4x1 – 2x4 = 0
2x2 – 2x3 – x4 = 0

At this point, we have three equations in four unknowns.

To complete the system, we define an auxiliary equation by arbitrarily choosing a value for one
of the coefficients:
x4 = 1

The complete system of equations can be written in matrix form as Ax = b, where

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

Thus, the balanced equation is CH4 + 2O2 CO2 + 2H2O

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.

Step 1. Activate SIMULINK

In the command line, type

>> simulink
( Alternatively, you can use the Matlab launch pad and double click on
Simulink icon. )

The simulink library browser should pop out as shown in Figure 1.

Step 2. Create a blank Simulink model window.

On the Library Browser window double-click on the "Create Model" menu


button (as indicated in Figure 1.). Alternatively, you could also select from the
[File] [New] [Model] submenu choice.
_ _

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.

Going back to Figure 1, double-click on the "Math Operations" icon.


The right-side of the Library browser should change. Scroll down until you
find the "Gain" block .

15
Figure 1.

Now drag-drop the "Gain" block into the Model window.


Back to the Library browser, on the right side, scroll down further until you
find the "Sum" block and then drag-drop this block into the Model window.

We need three more blocks which are included in other Simulink


subdirectories. First, click on the "Continuous" subdirectory that is on the
right side of the Library Browser. This should change the left side of the
Library Browser window. Select the "Integrator" block and drag-drop it into the
Model window.

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:

i) The Step block will be used to implement a step change in Tin.


ii) The Sum block will be used to take the difference: (Tin-T). Of course, we
need to change the properties of this block to reflect a difference instead of
a sum (which we will do below).
iii) The Gain block will be used to change the difference (Tin-T) by a factor.
In our case, this factor will be (1/ ). Thus the output of the Gain block
will be (1/ )(Tin-T). In reference to our process model, the calculations
yield the value of the derivative dT/dt.
iv) The Integrator block now takes in the dT/dt signal and outputs the
desired T signal.
v) The Scope block now simply reads in the T signals as a function of time
and plots it in a separate window.

Step 4. Change the properties of the blocks, if needed.


As we mentioned, we need to change the Sum block to obtain a difference. To
do so, double-click the Sum block. In the "List of Signs" input box, change the original
entry to "|+-". Then click the [OK] button to close this window and go back to the
Model window.

Next, double-click the Step block. A parameter window should pop-up.


Match the parameters shown in Figure 8. This means Tin will have a value of
20 until the time, t =3. After that, T in will jump to a value of 30.

Next, double-click the Integrator block. A parameter window should popup.


In the "Initial value:" input box, change it to 20. This means we are setting
To=20.

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.)

Step 5. Connect the Blocks.


Method 1: Short cut.
To connect the Integrator block and the Scope block, first click on the
Integrator block. Next, CTRL-click on the Scope block. An arrow should
connect the two blocks. (Note: the sequence of blocks clicked will determine
the direction of the arrow.)

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.

We could set simulation parameters by first selecting the submenu item


[Simulation]
_

[Simulation parameters...]

Set the stop time to 20.0 and then click [OK].

Next, run the simulation by pressing the “Run” button .

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.

Step 6. Save the model.

In the Model window, select [File]


_

[Save As] and save the model. The file


willd be save with a *.mdl extension. (For later purposes, we will save our
model system as simple.mdl.)

2. Communication between the Matlab’s Command window/workspace ands


Simulink’s Model window.

a) Exporting the outputs to the workspace.

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.

Change the entry in Variable Name to T. Also, change the


Save Format selection to “Array”. Click [OK].
Next, in the Model window, select the [Simulation]
_

[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

- To change the parameter value in a Simulink Model while in a Matlab


command window, use set_param :

>> 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:

dT/dt = [ Fhot Thot + Fcold Tcold – (Fhot + Fcold)T ]/V


and we will control the flow F by manipulating Fcold and control the temperature
T by manipulating Fhot. (For our example, we will use V=0.5).

1. Model the temperature mixing process.


a) Load the blocks and change their names and parameters as given in
Table 1.

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.

2. Group the blocks into a subsystem.


a) From the menu, select [Edit]
_

[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).

3. Create the PI controller subsystems.

a) From the Simulink Library Browser, go to the Ports & Subsystems


subdirectory.
b) Click-drag the Atomic Subsystem block into the Model window.
c) Rename this block: PI Temperature Controller
d) Open the subsystem block (by double-clicking the subsystem block).
e) Delete the line connecting In1 block and Out1 block.
f) Rename In1 as error , and Out1 as u.
g) Next, insert blocks into this subsystem window as prescribed in Table 2.
h) Fix the block layout and connections between blocks to match Figure 3.

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.

Remark: This means a valve transfer function which is slightly underdamped.


l) Next, delete all inport (1,2,3,4) and outport (1,2) blocks.
m) Reposition and connect the blocks to match the Model window shown in
Figure 4

25
Figure 4

n) Run the simulation and plot out the response of T and F.


o) Change the values for the PI ontrollers to improve the response. One
possible set of tuning variables are:

Temperature Controller Flow Controller


Kc 0.1 0.1
Integral Time 2 5

26
Part 5
Finding Steady States and Linearization via Simulink®

1. Consider the biochemical system,


(based on process developed in B. Wayne Bequette, “Process Control: Modeling, Design
and Simulation”, Prentice Hall, 2003, pp. 631-634.)


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

Figure 1. Simulink model: bioreactor_sys.mdl

3. Use the trim function to get steady state.


a) set some more parameters: i.e. we want to fix the input values of D=0.3 and x2f=4.0

>> X0=[];
>> U0=[0.3;4];
>> Y0=[];
>> IX=[];

Figure 2. Set Parameters (in our case, initial conditions)

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);

which results in the following:


A =
0.0000 -0.0678
-0.7500 -0.1304
B =
-0.9943 0
2.4859 0.3000
C =
1.0000 0
0 1.0000
D =
0 0
0 0

29
Reference:

1) A Short Tutorial in MATLAB, Tomas Co , Michigan Technological University.

2) Chemical Stoichiometry using MATLAB , P. K. Andersen and G. Bjedov


Purdue University.

3) Introduction to MATLAB 6 for Engineers, William J Palm III, McGraw Hill Publishers, 2001

30

Вам также может понравиться