Sci Lab Primer
Sci Lab Primer
Sci Lab Primer
Niket S. Kaisare, Department of Chemical Engineering, IIT-Madras INTRODUCTION Scilab is an interactive programming environment geared towards numerical computation and analysis. In some respects, it is similar to the popular program Matlab. Scilab is available free of cost and can be downloaded from http://scilab.org. The website also has tutorials to get a user started with using Scilab. This primer is designed assuming that a student has no prior experience with Scilab. The best way to use this primer is to use Scilab interactively while reading this document. Starting Scilab Scilab can be started by clicking the Scilab link in the Windows Start Menu at: Start > All Programs > Scilab > Scilab-4.1.1 The specific version of Scilab installed on your machine may be different. The Scilab command prompt appears as: --> This indicates that Scilab is now ready to accept commands. Getting Help The Scilab help browser can be launched by pressing the F1 key, or by clicking on the help menu or by typing help on the command prompt. VARIABLES AND MATRICES Defining variables A variable can be defined as a scalar as follows: -->a = 1 a = 1. --> The variable a now has the value of 1. Scilab displays the contents of the variable on the next lines. A semicolon at the end of the line suppresses display. A matrix can be entered in a similar manner. The elements of a row are separated by a comma or a space, whereas various rows are separated by a semi-colon or a carriage return (the enter key). Examples: -->b = [1 2 3 4 5] b = 1. 2. 3. 4. 5.
-->c = [1; 2; 3; 4; 5] c = 1. 2. 3. 4. 5.
Similarly, a 2*3 matrix (two rows, three columns) can be defined as follows: -->d = [1, 2, 3; 4, 5, 6] d = 1. 4. 2. 5. 3. 6.
Any element of the matrix or vector can be accessed by addressing its location. -->d(2,1) ans = 4. -->b(2) ans 2. -->b(2,1) !--error 21 invalid index -->b(1,2) ans = 2. In the first command above, we accessed the element of matrix d on row 2 and column 1. Since b is a row vector, the second element can be accessed either as b(2) or b(1,2). However, b(2,1) returns an error because vector b does not have row 2. Matrix Transpose ' is the transpose command. Examples: -->b' ans = 1. 2. 3. 4. 5. -->d' ans = 1. 2. 3. 4. 5. 6. =
Scilab Constants The names of Scilab-defined constants start with %. The list of useful constants: -->%pi %pi = 3.1415927 -->%e %e = 2.7182818 -->%t %t = T -->7.5 + 4*%i ans = 7.5 + 4.i Note that %t and %f are Boolean (true / false), %i is the complex unity, and %s and %z may be used to define laplace and Z-transforms, respectively. Matrix sizes There are two commands used to obtain sizes of the matrices: length and size. The former is meaningful only for vectors (row or column). Examples: -->length(c) ans = 5. -->size(d) ans = 2. 3.
-->length(d) ans = 6. Note that length command when used with a matrix does not give an error. The size can directly be assigned to two variables [nbr_rows, nbr_columns] using size as: -->[m,n] = size(d) n = 3. m = 2.
Matrix Vectors A matrix can be constructed from an existing matrix or a vector. Rows or columns can be added to a matrix. Examples: -->e = [d, [0 0.4; 3.2 2.1]] e = 1. 2. 3. 0. 0.4 4. 5. 6. 3.2 2.1 In the above example, d is a 2*3 matrix. The command [0 0.4; 3.2 2.1] creates a 2*2 matrix. This matrix is appended to the existing matrix, resulting in a 2*5 matrix. Likewise, we can also use the following operation to append a vector to an existing matrix (or an existing vector): -->f = [e;b] f = 1. 4. 1. 2. 5. 2. 3. 6. 3. 0. 3.2 4. 0.4 2.1 5.
-->g = [e;c] !--error 6 inconsistent row/column dimensions The second command above did not work because matrix e is a 3*5 matix, while c is a 5*1 vector. In order to append an additional row, the number of columns have to be the same (f has 5 columns and c has 1 column; however, e and b both had 5 columns). An entire row/column of a matrix can be accessed as follows -->f(:,1) ans = 1. 4. 1. -->f(3,2:5) ans = 2. 3. 4. 5.
In the first example, the first column of f is returned. One can also return a range of rows/columns as in the second example, where the second to fifth elements of row 3 are returned. MATRIX OPERATIONS Addition, Subtraction and Scalar Multiplication The usual rules of matrix addition and subtraction are applicable: the two matrices should have the same size. Exception: if a scalar is added (or subtracted) to a matrix, it gets added to each element of the matrix. Scalar multiplication also follows the normal rules. Examples: -->p = [4 5 7; -2 0.5 1]; // 2*3 matrix
-->q = 2; -->r = [2 1 5; 2 -3 7]; -->s = r'; -->p + q ans = 6. 0. -->p - r ans = 2. - 4. 4. 3.5 2. - 6. 7. 2.5 9. 3.
Matrix Multiplication In order to multiply two matrices, they need to be commutative. Some examples: -->p*r !--error 10 inconsistent multiplication -->p*s ans = 48. 1.5 -->s*p ans = 4. 11. 16. 10. 3.5 4. 6. 28.5 42. Scilab also provides element-by-element multiplication or division of two matrices using the operators .* and ./. The two matrices need to be of the same sizes in order to carry out this operation. Examples: 42. 1.5
-->p ./ p ans = 1. 1. 1. 1. 1. 1.
Power (Square) and Exponential of a Matrix Like the previous case, two different variant exist: taking power of a matrix and taking power of individual elements of a matrix. For example, in case of square of matrix A, we compute A*A, whereas squaring elements of a matrix is nothing but A(i,j)*A(i,j). Matrix exponent and powers are defined only for square matrices. Like previous example, we use ^ for matrix power and .^ for taking power of matrix elements. -->p ^ 2 !--error 20 first argument must be square matrix -->A = [1 4; 0 2] A = 1. 0. -->A .^ 2 ans = 1. 0. -->A ^ 2 ans = 1. 0. 12. 4. 16. 4. 4. 2.
Matrix exponent can be computed using expm whereas exponent of individual elements is computed using exp. -->expm(A) ans = 2.7182818 0. -->exp(A) ans = 18.683097 7.3890561
54.59815 7.3890561
Eigenvalues, Eigenvectors and Diagonalization The eigenvalues can be obtained using the command spec. -->eigenVals = spec(A) eigenVals = 1. 2. Diagonalization of matrix A in the form A = XX 1 is obtained as follows: -->[Lam, X] = bdiag(A) X = 1. 0. Lam 1. 0. = 0. 2. 4. 1.
Singular Value Decomposition Any matrix (square or non-square) can be decomposed in the standard form: A = UV T using singular value decomposition. The diagonal elements of are the singular values and U and V are unitary matrices (i.e., U = UT and V = VT). -->[U,S,V] = svd(A) V = 0.1979452 0.9802131 = 4.5615528 - 0.9802131 0.1979452 0.
0. = 0.9029376 0.4297717
Singular value decomposition is extremely useful in linear systems analysis and control theory. The primer is not completed for the topics listed below. Please refer to the accompanying document (attached below) for additional examples. This document was prepared by Mr. Vishnu Murthy, an MS scholar and Dr. Arun K. Tangirala. SOLVING ALGEBRAIC AND ORDINARY DIFFERENTIAL EQUATIONS LINEAR TIME INVARIANT (LTI) MODELS
[N1,D1]=simp(N,D)
H1=simp(H) N,D : real polynomials or real matrix polynomials H : rational matrix (i.e matrix with entries n/d , n and d real polynomials) [n1,d1]=simp(n,d) calculates two polynomials n1 and d1 such that n1/d1 = n/d . roots - roots of polynomials [x]=roots(p) spec - eigenvalues of matrices and pencils evals=spec(A) det - determinant det(X) inv - matrix inverse inv(X) csim - simulation (time response) of linear system [y [,x]]=csim(u,t,sl,[x0 [,tol]]) u : function, list or string (control) t : real vector specifying times with, t(1) is the initial time ( x0=x(t(1)) ). sl : list ( syslin ) y : a matrix such that y=[y(t(i)] , i=1,..,n x : a matrix such that x=[x(t(i)] , i=1,..,n tol : a 2 vector [atol rtol] defining absolute and relative tolerances for ode solver linspace - linearly spaced vector [v]=linspace(x1,x2 [,n]) x1,x2 : real or complex scalars n : integer (number of values) (default value = 100) v : real or complex row vector
grand - Random number generator(s) Y=grand(m, n, dist_type [,p1,...,pk]) Y=grand(X, dist_type [,p1,...,pk]) Y=grand(n, dist_type [,p1,...,pk]) m, n : integers, size of the wanted matrix Y X : a matrix whom only the dimensions (say m x n ) are used dist_type : a string given the distribution which (independants) variates are to be generated ('bin', 'nor', 'poi', etc ...) p1, ..., pk : the parameters (reals or integers) required to define completly the distribution dist_type Y : the resulting m x n random matrix chisquare : Y=grand(m,n,'chi', Df) generates random variates from the chisquare distribution with Df (real > 0.0) degrees of freedom. Related function(s) :
Gauss Laplace (normal) : Y=grand(m,n,'nor',Av,Sd) generates random variates from the normal distribution with mean Av (real) and standard deviation Sd (real >= 0). Related function(s) uniform (unf) : Y=grand(m,n,'unf',Low,High) distributed in [Low, High) power - power operation (^,.^) t=A^b t=A**b t=A.^b A,t : scalar, polynomial or rational matrix. b :a scalar, a vector or a scalar matrix. sqrt - square root y=sqrt(x) x : real or complex scalar or vector sqrt(x) is the vector of the square root of the x elements. Result is complex if x is negative. sqrtm - matrix square root y=sqrtm(x) x : real or complex square matrix y=sqrt(x) is the matrix square root of the x x matrix ( x=y^2 ) Result may not be accurate if x is not symmetric generates random reals uniformly
Example:1 Enter a matrix and calculate its 1. Eigen values 2. Determinant 3. Inverse 4. square root 5. square -->a=[0 0.9056;-0.7500 -2.564] a =
0. 0.9056 - 0.75 - 2.564 -->spec(a) ans = - 0.3 - 2.264 -->det(a) ans = 0.6792 -->inv(a) ans = - 3.7750294 - 1.3333333 1.1042403 0. -->sqrt(a) ans = 0 0.9516302 0.8660254i 1.6012495i -->sqrtm(a) ans = 2.459D-17 + 0.4015509i - 2.702D-17 - 0.4412434i 2.238D-17 + 0.3654291i 1.011D-16 + 1.650831i -->a.^2 ans = 0. 0.8201114 0.5625 6.574096 -->a^2 ans = - 0.6792 - 2.3219584 1.923 5.894896 -->s=poly(0,'s'); -->a=[0 s+1; s+2 s] a = 0 2+s -->det(a) ans = 2 - 2 - 3s - s 1+s s
2+s ---------
Example: 2 Create a simple system G(s)=1/(s+1) and plot its Impulse response Step response Ramp response Sine response
-->s=%s; // first create a variable -->num=1; -->den=s+1; -->tf=num/den tf = 1 ----1+s -->//tf is not yet usable object -->//create a scilab continuous system LTI object -->tf1=syslin('c',tf) tf1 = 1 ----1+s -->// create a time axis, -->t=linspace(0,10,500); -->imp_res=csim('imp',t,tf1); -->step_res=csim('step',t,tf1); -->ramp_res=csim(t,t,tf1); -->plot(t,imp_res),xgrid(),xtitle('Impulse response','time','response'); -->plot(t,step_res),xgrid(),xtitle('Step response','time','response');
-->s1=tf2ss(tf1) s1 = s1(1) (state-space system:) !lss A B C D X0 dt ! s1(2) = A matrix = - 1. s1(3) = B matrix = 1. s1(4) = C matrix = 1. s1(5) = D matrix = 0. s1(6) = X0 (initial state) = 0. s1(7) = Time domain = c -->tf2=ss2tf(s1) // state space to transfer function tf2 = 1 ----1+s
Example:3 Create a transfer function G(s)=(s+1)/(s^2+3s+2) -->s=%s -->num=s+1; -->den=s^2+3*s+2; -->tf=num/den tf = 1 -----
2+s -->//this is not the required form -->// so, inorder to avoid this we use simp_mode(%f) -->simp_mode(%f)
Script file in scilab: Example: 1 // normal distribution n=2048; a=grand(n,1,'nor',1,20); s=0; m=0; for i=1:n s=s+a(i,1); end compmean=s/n s=0; for i=1:n s=s+(a(i,1)-m)^2; end copmsd=sqrt(s/(n-1)) actulmean=mean(a) actualsd=stdev(a)
histplot(20,a) Example:2 Frequency response // Magnitude plot s=%s; num=1; den=s+1; tf=syslin('c',num/den) x=0:0.1:2*%pi; m=sqrt(1+x^2); mag=m^(-1); subplot(2,1,1),plot2d1("gln",x,mag),xtitle('frequency response','w','AR'),xgrid(), subplot(2,1,2),bode(tf,0.01,100);
Functios in scilab: Example:1 function [r1,r2]=qroots(a,b,c) // this function is used to calculate the roots of quadratic equation
//equation: ax^2+bx+c=0 // inputs a,b,c are coefficients of equation r1=(-b+sqrt(b^2-4*a*c))/(2*a) r2=(-b-sqrt(b^2-4*a*c))/(2*a) endfunction
Scicos: Example: Consider an isothermal reactor where the following reactions take place
Assuming a constant volume, the following equations describe the system behavior
Simulate using scicos: the dilution rate F/V is the manipulated variable and inlet concentration CAf is disturbance Simulate the system for initial conditions CAO=10gmol/l, CBO=0 gmol/l Initial concentration CAf=10 gmol/l F/V = 0.5714 min-1 where: k1 = 5/6; k2 = 5/3; k3 = 1/6;
sub block
Exercise
Question: 1 Solve the system of equations: 2x+y=1, x+2y+z=2, y+z=4; and also calculate its Eigen values Determinant Inverse Square root Square Question:2 Consider the following equations x + y=2, x + (1+e)y = 4 obtain A-1, det of A, eig values and solve x & y. for e=0.01, Question: 3 Create G(s) = (s2-1)/(s3+6s2+11s+6) and calculate its poles and zeros. Convert in state space representation. Plot its impulse response and step response. Question: 4 Consider an isothermal reactor where the following reactions take place
Assuming a constant volume, the following equations describe the system behavior
Simulate using scicos: the dilution rate F/V is the manipulated variable and inlet concentration CAf is disturbance Simulate the system for initial conditions CAO=10gmol/l, CBO=0 gmol/l Initial concentration CAf=10 gmol/l F/V = 2.8744min-1 where: k1 = 5/6; k2 = 5/3; k3 = 1/6;