Scilab and Scicos Revised

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 143
At a glance
Powered by AI
Scilab is an open-source alternative to MATLAB that is free, highly supported, and powerful for mathematical computing and technical applications.

Scilab is a matrix-oriented mathematical software package similar to MATLAB. It allows matrix manipulations, plotting, animation, and programming capabilities through its open architecture.

The main components of Scilab are an interpreter, libraries of functions (procedures, macros), and interfaces for other programming languages.

SCILAB and SCICOS- Emerging

Open Source Alternative to


MATLAB

Compiled by
Dr. PISUPATI SADASIVA SUBRAMANYAM
SENIOR MEMBER,I.E.E.E.
VIGNANA BHARATHI INSTITUE OF
TECHNOLOGY,
HYDERABAD-501301.
What is Scilab?
Scilab is a mathematical software
Similar software: Matlab, Mathematica,
Octave, Euler Math Toolbox, Maxima,
What is special about Scilab: free, highly
supported, powerful, many users,
Home page of Scilab: www.scilab.org
A short introduction of Scilab:
http://hkumath.hku.hk~nkt/Scilab/IntroToScil
ab.html
What is Scilab? (Contd.)

Scilab is matrix-oriented, just like Matlab

It allows matrix manipulations, 2D/3D plotting,


animation, etc.

It is an open programming environment that allows


users to create their own functions and libraries

Its editor has a built-in, though elementary, debugger


What is Scilab ? (Contd.)

Main components of Scilab are:


An interpreter
Libraries of functions (procedures, macros)
Interfaces for Fortran, Tcl/Tk, C, C++, Java,
Modelica, and LabVIEWbut not for Python
and/or Ruby

Which is better, Matlab or Scilab?


Matlab outperforms Scilab in many respects,
but Scilab is catching up. The use of Matlab
is motivated only in special circumstances
due to its high cost
2. Installing and Running Scilab

First, you must have the software. Go to the download section


in the Scilab homepage, find a right version for your operating
system (platform), and then click to download. For easy
installation, it is advisable to download the installer (for binary
version). Then double click the downloaded file and follow the
instructions to complete the installation.
To run Scilab, type
scilex
in the command prompt in the folder bin under the
installation directory, or click the shortcut in the start menu if
you use Windows. To exit the program, type
exit
or close the window of the main program.
3. Documentation and Help

To find the usage of any function, type


help function_name
For example:
help sum
If you want to find functions that you do not
know, you may just type
help
and search for the keywords of the functions.
Finally, if you want more information, you may
visit the Scilab homepage. There is a section
called documentation. It is very resourceful
4. Scilab Basics

Common Operators
+ addition
- subtraction
* multiplication
/ division
^ power
' conjugate transpose
Here is a list of common operators in Scilab:
FUNCTIONS IN SCILAB
The term function in Scilab to (at least):

Mathematical functions in general

Scilabs built-in functions

User defined functions (UDF)


Common Functions:
Some common functions in Scilab are:

sin, cos, tan, asin, acos, atan, abs, min, max, sqrt, sum
Eg., when we enter:
sin(0.5)
then it displays:
ans =
0.4794255

Another example:
max(2, 3, abs(-5), sin(1))
ans =
5
SCILAB-ADVANTAGES
Numeric computing is better suited for complex tasks than
symbolic computing

Not all mathematical problems have closed form solutions, numeric


computing will therefore always be needed

Scilab is similar to Matlab and keeps developing even closer. It is


quite easy to step from one to the other

Scilab requires less disk space than Matlab and GNU Octave
It includes a Matlab-to-Scilab translator (.m files to .sci files)
Data plotting is said to be simpler than with GNU Octave (but the
trend is toward more complex handle structures)

The Xcos toolbox installs automatically with Scilab, be it, that Xcos is
not compatible with Simulink

Scilab installs without immediate problems on Windows computers

Scilab is freeif your wasted time and frustrations are worth


nothing. The fight for a limited number of expensive licenses
(Matlab, Mathematica, etc.) is not an issue in professional life
Special Constants

We may wish to enter some special constants


like, i (sqrt(-1)) and e. It is done by entering
%pi %i %e
respectively. There are also constants
%t %f
which are Boolean constants representing
true and false, respectively. Boolean
variables would be introduced later.
The Command Line

Multiple commands, separated by commas, can be put


on the same command line:
A = [1 2 3], s = tan(%pi/4) + %e
A=
1. 2. 3.
s=
3.7182818
Entering a semi-colon at the end of a command line
suppresses showing the result (the answer of the
expression):
A = [1 2 3]; s = tan(%pi/4) + %e;
Here the vector [1 2 3] is stored in the variable A, and the
expression tan(%pi/4) + %e is evaluated and stored in s, but the
results are not shown on the screen.
A long command instruction can be broken with line-wraps by
using the ellipsis (...) at the end of each line to indicate that the
command actually continues on the next line:
s = 1 -1/2 + 1/3 -1/4 + 1/5 - 1/6 + 1/7 ...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;
Anything that is typed after a pair of slashes // will be ignored, and
hence can serve as comments or code annotations:
%e^(%pi * %i) + 1 // should equal 0, as in the Euler's identity
ans =
1.225D-16i
Using the up and down arrow in the command line can recall
previous commands
Data Structures

Scilab supports many data structures.


Examples are: (real or complex) matrix,
polynomial, Boolean, string, function, list,
tlist, sparse, library. Please read the Scilab
documentation for details. To query for the
type of an object, type:
typeof(object)
Strings
To enter a string, enclose it with either single or double
quotations. For example:
'This is a string'
or
"this is also a string"
To concatenate strings, use the operator + :
"Welcome " + "to " + "Scilab!"
ans =
Welcome to Scilab!
There are some basic string handling functions such as
strindex strsplit strsubst part
Please refer to Scilab's documentation for details
Saving and Loading Variables

To save and to load variables, we use the save


and load functions:
save('file_name', var1, var2, ...);
load('file_name', 'var1', 'var2', ...);
where file_name is the name of the file to be
saved or loaded, and var1, var2, ..., are
variable names.
Notice that the variable name has to match
when it is to be saved. Here are some
illustrations
a = 3; b = %f; s = 'scilab';
save('save.dat', a, b, s);
clear a; // delete the variable a
clear b;
clear s;
load('save.dat', 'a', 'b', 's');
// load all the saved variables

load('save.dat','b');
// It loads only variable b, but not
// variable a in the name of b
load('save.dat','b');
// It loads only variable b, but not
// variable a in the name of b

load('save.dat','d');
// It will not show any error messages.
// Variable d is undefined, not empty.

listvarinfile('save.dat');
// list variables in a file saved by
// the function save
Name Type Size Bytes
----------------------------------------------------
a constant 1 by 1 24
b boolean 1 by 1 20
s string 1 by 1 44
5. Dealing with Matrices

Entering Matrices
There are many ways to enter a matrix. Here is
the simplest method:
Separate each element in a row by a blank space
or a comma,
Separate each row of elements with a semi-
colon, and
Put the whole list of elements in a pair of square
brackets.
For example, to enter a 3 x 3 magic square and
assign to the variable M :
M = [8 1 6; 3 5 7; 4 9 2]
M=
8. 1. 6.
3. 5. 7.
4. 9. 2.
Calculating Sums
For a magic square, we may wish to check for its column sums and row sums and the sum of
diagonals. This is done by entering:
sum(M,'c') // column sums
ans =
15.
15.
15.
sum(M,'r') // row sums
ans =
15. 15. 15.
The sum of the main diagonal is easily done with the help of the function diag.
diag(M)
ans =
8.
5.
2.
Subscripts

It is a bit more difficult to find the sum of the other


diagonal. We will show two ways to accomplish it.
One method is to find the sum manually, i.e., to read
the specified elements and then to sum them up.
M(1,3) + M(2,2) + M(3,1)
ans =
15.
It is possible to access elements in a matrix using a
single index. This by treating a matrix as a long
vector formed by stacking up the columns of the
matrix. E.g., the values of M(1), M(2), M(3), M(4),
M(5) are 8, 3, 4, 1, 5, respectively.
Accessing out-of-bound elements will result in an error, like
entering:
M(3,4)
!--error 21
invalid index
A smarter way to get the sum of the other diagonal is to use the
function mtlb_fliplr, where mtlb stands for Matlab. This is to flip
a matrix left-to-right (lr):
mtlb_fliplr(M)
ans =
6. 1. 8.
7. 5. 3.
2. 9. 4.
The desired result would then be obtained by typing
sum(diag(mtlb_fliplr(M))).
The Colon Operator
The colon operator is one of the most important operators in Scilab. The expression
1:10 results in a row matrix with elements 1, 2, ..., 10, i.e.:
1:10
ans =
1. 2. 3. 4. 5. 6. 7. 8. 9. 10.
To have non-unit spacing we specify the increment:
10 : -2 : 2
ans =
10. 8. 6. 4. 2.
Notice that expressions like 10:-2:1, 10:-2:0.3 would produce the same result while
11:-2:2 would not.
Subscript expressions involving colons refer to parts of a matrix. M(i:j, k) shows the i-
th row to j-th row of column k. Similarly,
M(3,2:3)
ans =
9. 2.
Some more examples:
M(3,[3,2])
ans =
2. 9.

M([2,1], 3:-1:1)
ans =
7. 5. 3.
6. 1. 8.
The operator $, which gives the largest value of an index, is
handy for getting the last entry of a vector or a matrix. For
example, to access all elements except the last of the last
column, we type:
M(1:$-1, $)
We sometimes want a whole row or a column. For example, to
obtain all the elements of the second row of M, enter:
M(2,:)
ans =
3. 5. 7.
Now we have a new way to perform operations like
mtlb_fliplr(M). It is done by entering M(:, $:-1:1). However the
function mtlb_fliplr(M) would obtain result faster (in
computation time) than using the subscript expression.
Simple Matrix Generation

Some basic matrices can be generated with a


single command:
zeros all zeros
ones all ones
eye Identity matrix (having 1 in the
main diagonal and 0 elsewhere)
rand random elements (follows either
normal or uniform distribution)
Some illustrations:
zeros(2,3)
ans =
0. 0. 0.
0. 0. 0.

8 * ones(2,2)
ans =
8. 8.
8. 8.

eye(2,3)
ans =
1. 0. 0.
0. 1. 0.

rand(1,3,'uniform') // same as rand(1,3)


ans =
0.2113249 0.7560439 0.0002211
Concatenation
Concatenation is the process of joining smaller size matrices to
form bigger ones. This is done by putting matrices as elements in
the bigger matrix:
a = [1 2 3]; b = [4 5 6]; c = [7 8 9];
d = [a b c]
d=
1. 2. 3. 4. 5. 6. 7. 8. 9.

e = [a; b; c]
e=
1. 2. 3.
4. 5. 6.
7. 8. 9.
Concatenation must be row/column consistent:
x = [1 2]; y = [1 2 3];
z = [x; y]
!-error 6
inconsistent row/column dimensions
We can also concatenate block matrices, e.g.:
[eye(2,2) 5*ones(2,3); zeros(1,3) rand(1,2)]
ans =
1. 0. 5. 5. 5.
0. 1. 5. 5. 5.
0. 0. 0. 0.6525135 0.3076091
Remember that it is an error to access out-of-bound element of a
matrix. However, it is okay to assign values to out-of-bound
elements. The result is a larger size matrix with all unspecified
entries 0:
M = matrix(1:6, 2, 3); M(3,1) = 10
M=
1. 3. 5.
2. 4. 6.
10. 0. 0.
It is remarked that this method is slow. If the size of the matrix is
known beforehand, we should use pre-allocation:
M = zeros(3,3); // pre-allocation
M([1 2], :) = matrix(1:6, 2, 3);
M(3,1) = 10;
Deleting Rows and Columns

A pair of square brackets with nothing in between


represents the empty matrix. This can be used to
delete rows or columns of a matrix. To delete the 1st
and the 3rd rows of a 4x4 identity matrix, we type:
A = eye(4,4);
A([1 3],:) = []
A=
0. 1. 0. 0.
0. 0. 0. 1.
If we delete a single element from a matrix, it results
in an error, e.g.:
A(1,2) = []
!-error 15
submatrix incorrectly defined
If we delete elements using single index expression, the result
would be a column vector:
B=[1 2 3; 4 5 6];
B(1:2:5)=[]
B=
4.
5.
6.
Matrix Inverse and Solving
Linear Systems
The command inv(M) gives the inverse of the matrix M. If
the matrix is badly scaled or nearly singular, a warning
message will be displayed:
inv([1 2;2 4.0000001])
warning
matrix is close to singular or badly scaled. rcond =
2.7778D-09
ans =
40000001. - 20000000.
- 20000000. 10000000.
Solving a system of linear equations Ax = b, i.e., to find x
that satisfies the equation, when A is a square, invertible
matrix and b is a vector, is done in Scilab by entering A\b :
A = rand(3,3), b = rand(3,1)
A=
0.2113249 0.3303271 0.8497452
0.7560439 0.6653811 0.6857310
0.0002211 0.6283918 0.8782165
b=
0.0683740
0.5608486
0.6623569

x=A\b
x=
- 0.3561912
1.7908789
- 0.5271342
Another method is to type inv(A) * b. Although it gives the same result, it is slower
than A\b because the first method mainly uses Gaussian Elimination which saves
some computation effort. Please read the Scilab help file for more details about
the slash operator when A is non-square.
A / b solves for x in the equation xb = A.
Entry-wise operations, Matrix Size

To add 4 to each entry of a matrix M, using M + 4


* ones(M) is correct but troublesome. Indeed this
can be done easily by M + 4. Subtraction of a
scalar from a matrix entry-wise is done similarly.
Multiplying 2 to the second column and 3 to the
third column of M can be achieved by using the
entry-wise multiplication operator .* :
M .* [1:3; 1:3]
Entry-wise arithmetic operations for arrays are:
+ addition
- subtraction
.* multiplication
.^ power
./ right division
.\ left division

Thus, instead of typing


s = 1 -1/2 + 1/3 -1/4 + 1/5 - 1/6 + 1/7 ...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;
one may simply type
s = sum((1:2:12) .\ 1) - sum((2:2:12) .\ 1)
or
s = sum(1 ./ (1:2:12)) - sum(1 ./ (2:2:12))
Note that 1./1:2:12 is interpreted as (1./1):2:12. Similarly,
1:2:12.\1 is interpreted as 1:2:(12.)\1.
To enter the matrix M = [1 2 3 4 5; 6 7 8 9 10], one may use:
M = zeros(2,5);
M(:) = 1:10;
Yet an almost effortless method is to use the function
matrix, which reshapes a matrix to a desired size:
M = matrix(1:10,5,2)'
How to enter N = [1 2; 3 4; 5 6; 7 8; 9 10] easily? Hint: think of
some simple operations on a matrix.
A handy function in Scilab called size returns the dimensions
of the matrix in query:
size(M)
ans =
2. 5.
while size(M,1) returns 2 (number of rows) and size(M,2)
returns 5 (number of columns).
6. The Programming Environment

Creating Functions
Scilab has an open programming environment
that enables users to build their own functions
and libraries. It is done by using the built-in
editor SciPad. To call the editor, type scipad() or
editor(), or click Editor at the menu bar.
The file extensions used by scilab are .sce and
.sci. To save a file, click for the menu File and
choose Save. To load a file, choose Load under
the same menu. To execute a file, type
exec('function_file_name');
in the command line, or click for load into Scilab under the
menu Execute.
To begin writing a function, type:
function [out1, out2, ...] = name(in1, in2, ...)
where function is a keyword that indicates the start of a
function, out1, out2 and in1, in2, ..., are variables that are
outputs and inputs, respectively, of the function; the variables
can be Boolean, numbers, matrices, etc., and name is the
name of the function. Then we can enter the body of the
function. At the end, type:
endfunction
to indicate the end of the function.
Comment lines begin with two slashes //. A sample function is
given as below:
function [d] = distance(x, y)
// this function computes the distance
// between the origin and the point (x, y)
d = sqrt(x^2 + y^2);
endfunction
A Scilab function can call upon itself recursively. Here is an
example.
Unlike Matlab, Scilab allows multiple function declaration (with
different function names) within a single file. Also Scilab allows
overloading (it is not recommended for beginners). Please refer
to the chapter overloading in its help file for details.
Flow Control

A table of logical expressions is given below:


== equal
~= not equal
>= greater than or equal to
<= less than or equal to
> greater than
< less than
~ not
If a logical expression is true, it returns a Boolean
variable T (true), otherwise F (false).
The if statement
It has the basic structure:
if condition
body
end
The body will be executed only when the condition statement
is true. Nested if statements have the structure:
if condition_1
body_1
elseif condition_2
body_2
elseif condition_3
body_3
elseif ...
...
end
As an example, we make use of the fact that a Scilab function can call upon
itself recursively to write a function which gives the n-th Fibonacci number in
the sequence 0, 1, 1, 2, 3, 5, 8, 13, ... :
function [K] = fibonacci(n)
//function [K] = fibonacci(n)
//Gives the n-th term of the Fibonacci sequence 0,1,1,2,3,5,8,13,...
if n==1
K = 0;
elseif n==2
K = 1;
elseif n>2 & int(n)==n // check if n is an integer greater than 2
K = fibonacci(n-1) + fibonacci(n-2);
else
disp('error! -- input is not a positive integer');
end
endfunction
Note that this is not an efficient way to find the n-th Fibonacci number when n
is large
The for loop
It has the basic structure:
for variable = initial_value : step : final_value
body
end
The loop will be executed a fixed number of times specified
by the number of elements in the array variable. A slightly
modified version is:
str = 'abcdr';
s = ''; // an empty string
for i = [1 2 5 1 3 1 4 1 2 5 1]
s = s + part(str, i);
end
disp(s);
s = abracadabra
The while loop
It has the basic structure:
while condition
body
end
The loop will go on as long as the condition statement is
true. Here we give an example of the Euclidean Algorithm.
function [n1] = hcf(n1, n2)
// n1 and n2 are positive integers
if n2 > n1
tem = n2; n2 = n1; n1 = tem; // to ensure n1>=n2
end

r = pmodulo(n1, n2); // remainder when n2 divides n1


n1 = n2; n2 = r;

while r ~= 0
r = pmodulo(n1, n2);
n1 = n2; n2 = r;
end

endfunction
The break and continue commands
They are for ending a loop and to immediately start the next iteration,
respectively. For example:
// user has to input 10 numbers and for those which
// are integers are summed up, the program are
// prematurely once a negative number is entered.

// It is not well written but just to illustrate the


// use of the "break" and "continue" commands
result = 0;
for i = 1:10
tem = input('please input a number');
if tem < 0
break;
end
if tem ~= int(tem) //integral part
continue;
end
result = result + tem;
end
Some Programming Tips
The concept of Boolean vectors and matrices is important.
The function find is useful too. It reports the indices of true
Boolean vectors or matrices. For example:
M = [-1 2; 4 9]; M > 0
ans =
FT
TT

M(M > 0)'


ans =
4. 2. 9.
end
In contrast,
find(M > 0)
ans =
2. 3. 4.

M(find(M>0))'
ans =
4. 2. 9.
We remark that M(M>0) gives results quicker than M(find(M>0)
because the find function is not necessary here.
It is important to distinguish & and and, | and or. The first one of
each pair is entry-wise operation and the other one reports truth
value based on all entries of a Boolean matrix.
M = [0 -2; 1 0]; M==0 | M==1
ans =
TF
TT

and(M >= 0) // true iff all entries are true


ans =
F

or(M == -2) // false iff all entries are false


ans =
T
Debugging

The most tedious work in programming is to


debug. It can be done in two ways: either using
Scilab's built-in debugger, or modifying the
program so that it serves the same purpose as a
debugger.
The Scilab debugger is similar to those
debuggers in other programming languages and
is simple to use. We present the second method
to offer programmers greater flexibilities when
debugging.
To insert breakpoints we use
pause
To end pause we use
abort
To set the output of the function we may use
return
To display variables we use
disp (variable)
For details please read the Scilab documentation.
7. Plotting Graphs

t = (0:1/100:2) * %pi;
y = sin(t);
plot(t,y);
2D Graphs
The plot function has different forms, depending on the input
arguments. If y is a vector, plot(y) produces a piecewise linear
graph of the elements of y versus the index of the elements of
y. When x and y are vectors of the same length, plot(x,y)
produces a graph of y versus x. E.g., to plot the value of the sine
function from zero to 2 pi:
3D Surfaces
The command plot3d(x,y,z) plots 3D surfaces. Here x and y (x-axis and y-axis
coordinates) are row vectors of sizes n1 and n2, and the coordinates must be
monotone, and z is a matrix of size n1xn2 with z(i,j) being the value (height) of the
surface at the point (x(i),y(j)).
8. Scilab versus Matlab
This section is based on some user comments found in the
internet, thus not necessarily all true. It is intended to give
readers a general image about their differences besides those in
syntax.
Matlab has a thorough documentation; the one in Scilab is brief.
Matlab has a lot of optimization on computation, thus it is faster
than Scilab.
Matlab has a very powerful simulation component called
Simulink.
Scilab has Scicos that serves the same purpose but it is weaker.
Matlab has a much better integration with other programming
languages and programs such as C, C++ and Excel.
The graphics component of Scilab is weak (has fewer functions).
Most importantly, Scilab is FREE. It certainly outweighs its
deficiencies. It is remarked that Scilab is more than enough for
casual and educational uses.
Vectors and matrices in Scilab (2)
Matrices in Scilab:
> A = [0 1 0 1; 2 3 4 0]
>B=A
> A * y, x * B, A * B, B * A, (B*A)^2
Special matrices (and vectors):
> ones(2,3), zeros(1,2), eye(3,3)
> rand, rand(3,2)
Empty vector or matrix: > a = [ ]
Building matrix by blocks:
> C = [A 2*A], x = [9 x 7], a = [a 1]
The colon : operator
> 1:10, 1:100, xx = 1:100;
Using ; to suppress answer output
> sum(xx)
> 1:2:10, 3:3:11, 4:1:1, 2:1:0,
> t = 0: 0.1: 2*%pi
> y = sin(t)
> plot(t,y), plot(t,sin(t),t,cos(t))
Task 1: plot the straight lines
y = x +1 and y = exp(x) on the same graph, from
x = 2 to x = 2
Elements of vectors and matrices

Example
> v = rand(4,1)
> v(1), v(3), v([2 4]), v(4:-1:1), v($)
$ means the last entry
Example
> A = [1 2 3 4 5; 6 7 8 9 10]
> A(2,3), A(1,:), A(:, 2), A(:, [4 2])
Programming in Scilab

Click on menu bar to open Scipad; then write


your scilab function file.
Format of a function:
function [out1, out2, ...] = name(in1, in2, ...)
(body of function definition; may have many lines)
endfunction
One file may contain more than one function.
To use the functions, you must load the function
file by choosing File -> Execute the file from the
menu.
Programming in Scilab (2)
A simple function to find the n-th term of the
Fibonnaci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21,
function k = fibo(n)
if n == 1, k = 0;
elseif n==2, k = 1;
else k = fibo(n-1) + fibo(n-2);
end
endfunction
Save the file as fibo.sci (or any other file name).
Execute it from Scilab menu bar
Try, say: > fibo(5), fibo(2), fibo(10), fibo(100)
Programming in Scilab (3)

An improved programme:
function K = fibonacci(n)
//function K = fibonacci(n)
//Gives the n-th term of the Fibonacci
sequence ,1,1,2,3,5,8,13,... if n==1, K = 0;
elseif n==2, K = 1;
elseif n>2 & int(n)==n
// check if n is an integer greater than 2
K = fibonacci(n-1) + fibonacci(n-2);
else disp('error! -- input is not a positive integer');
end
endfunction
Programming in Scilab (4)

Programming Task (challenging!): write a


programme to automate Task 5, which is to
perform the following experiment m times. The
experiment is to simulate tossing a coin n times
and find the longest run (k) of consecutive Hs
or Ts in the resulting sequence.
For each time you do the experiment, youll get
a number k. Therefore you should get m
numbers k1, k2, , km at the end.
Inputs of the function are m, n; output is a
vector k = [ k1 k2 km].
electronics circuits with active components can be modeled and simulated using the
Scicos internal Modelica support.
Electro/Hydraulic Components Palette
Go to Scicos Home page
Modelica integration inside Scilab

Scicos includes a compiler for a subset of


Modelica language. This subset covers most
continous-time parts of the Modelica
language and a minimum support for the
discrete parts. Currently, this compiler does
not cover index reduction and initial
equations.
Scicos & RTA Lab Demo

RTAI-Lab is a palette of blocks and programs that allow


you to design models that can be compiled for
the RTAI real-time patch to the Linux operating system.
A Linux kernel that is patched with RTAI (Real-Time
Application Interface) can run hard real-
time programs. Hard-real time is essential to control
systems where timing precision must be guaranteed with
high accuracy (e.g. instruments, robots, etc.).

RTAI-Lab is not distributed within the Scilab/Scicos


package. TheRTAI-Lab source code can be found within
the RTAI distribution in directory $RTAI/rtai-lab. It
contains both Scilab and Matlab subdirectories.
The snapshot shows:
Part of the RTAI-Lib palette, which includes real-time sources,
sinks, and interfaces to acquisition cards using Comedi.
Part of a model that interfaces to a device with 6 sensors. This
model can be compiled directly from within Scicos into a real-
time executable.
The xrtailab / RTAI-Lab Graphical User Interface program
that connects with the real-time executable. In this case we
are displaying only 2 data sources on the Scope and one
source on the meter
System-Observer demo

Start demo: The System-Observer demo is viewable by


clicking in the main Scilab window on Demos-->Scicos--
>System-Observer.cosf.

Super Blocks: One may click on the various blocks to see


how they are defined. Now click on one of the Super
Blocks. You see it contains a Continuous-Time Linear
State-Space block, also known as CLSS. If you now click
on it, a window opens up where you see how the
corresponding matrices are defined. It turns out the
matrices are defined by symbolic parameters (Scilab
variables) A and B. Symbolic parameters are defined in
the context of the diagram. Click [Cancel] and then close
the previous window (entitled "System").
Symbolic parameters are defined in the context of the diagram.
Click [Cancel] and then close the previous window (entitled
"System").

Diagram context: In the System-Observer window click on


Edit-->Context. This is where the symbolic parameters are
defined.

Run simulation: Click on Simulate-->Run

Source code: The Scicos diagrams for all the demos are in the
directory $SCI/demos/scicos/
Scicos is a graphical dynamical system
modeler and simulator. User can create block
diagrams to model and simulate the dynamics of
hybrid dynamical systems (continuous and
discrete time) and compile such models into
executable code. It is used for signal processing,
systems control, queuing systems, and to study
physical and biological systems.

It is possible that Scilab/Scicos is currently the


most complete alternative to commercial packages
for dynamic systems modeling and simulation
packages such as MATLAB/Simulink and
MATRIXx/SystemBuild."
1. SCICOS CODE GENERATOR:
http://www.scicos.org/CodeGen_doc.pdf

2. Scicos: Block diagram modeler/simulator:


http://www.scicos.org/

3. Porting Scicos-Flex to Scilab 5.0


Flex" means "flexibility". The Scicos internal code generator is not capable to produce true
executable "stand-alone" code. Vendors provide external libraries of Scicos computational
functions fully independent from the Scilab/Scicos environment. These libraries are based on
general purpose C code that can be easily cross compiled for DSP and micro controllers.

the code generated is, for the internal section, fully device and board agnostic. This means
that the same Scicos diagrams can be used for simulation and different target implementation
with not modifications at all or, for the code generation, only changing the device/board specific
input/output blocks.

http://wiki.scilab.org/Porting%20Scicos-Flex%20to%20Scilab%205.0
4. Real-Time Systems Laboratory. RETIS Lab.
Mauro Marinoni [[email protected]]. Scilab/Scicos Code.
Generator for Flex
http://www.artist-embedded.org/docs/Events/2008/RT-
Kernels/SLIDES/s6-Scicos.pdf
5. Scilab/Scicos Code Generator for FLEX
http://www.evidence.eu.com/scilabscicos-code-generator-flex-and- !

xenomai-products.html
Concept
To develop a single-click digital control automatic code generation
tool for the FLEX boards!
6. Free & Open Source Simulation Software
(Modeling, Simulation, Control and Visualization)

http://www.linkedin.com/groups/ScicosFLEX-embedded-code-
generator-100- 1389147.S.57376484

Scicos-FLEX embedded code generator 10.0


released! Manager's Choice
Paolo G. Software Engineer
Dear all,

just a quick mail to inform you we just released the


ScicosLab Pack 10.0

http://erika.tuxfamily.org/scilabscicos.html
MATH TOOLS - Complex Number
Conversion
Summary :
Convert complex matrices to/from polar (phasor) form
often used in electrical engineering.
Description: It adds only two routines: to_r() and to_p().
These routines
make it easy to work with complex numbers in the polar
(or
phasor) form often used by electrical engineers. In polar
form a complex number is written as a (magnitude,
angle) pair
where the angle is in degrees measured
counterclockwise (CCW) from the positive real axis.
In engineering texts the notation
mag /_ angle is often used, so 10 /_ 45 would represent the
complex number with magnitude 10 at a 45 degree CCW from the
real axis. to_r(10,45) converts this to standard form and
gives 7.07+7.07i.
The routines define and work with two matrix "polar forms".
In the first form the magnitudes and angles are in adjacent
columns of a single matrix. In the second form the magnitudes
and angles are in separate matrices. The to_r() example at
the end of the previous paragraph used the second form. The
same result can be obtained using the first form via
to_r([10 45]).
to_r() is used to convert polar form numbers or matrices
to standard form:

-->// Create a 2x2 impedance matrix.


-->// The impedances are given in a mix of polar and standard forms.
-->Z = [to_r(100, 45) 200+%i*200; to_r(150,90) 200];

-->// Create a voltage vector V(1) = 50 /_0, V(2) = 100 /_ -30


-->V = to_r([50 0; 100 -30]);

Complex matrices should always be in standard form for computation


to_p() is normally used only at the end of a computation to show
a result in polar form:
Calculate currents corresponding to previous Z and V
-->I = ZV
I=

! - 0.2947621 - 0.2717314i !
! 0.2292141 - 0.0289284i !

-->to_p(I)
ans =

! 0.4009023 - 137.32806 !
! 0.2310324 - 7.1930998 !

In this example I(1) = -0.295 - 0.272i = 400 mA /_ -137.3 degrees and


I(2) = 0.229 - 0.029i = 231 mA /_ -7.2 degrees.
First example of using scilab
generating beat waves using scilab:
-->Ts=0.0001;

-->n=-1000:1000;
-->tn=n*Ts;
-->xn=2*cos(40*3.14159*tn).*cos(800*3.14159*tn);
-->plot(tn, xn);

This program shows the Beat waves for the equations given:
X(t)=cos(220t)+cos(2400t)
X(t)=2cos(220t)cos(2400t)

The individual plots and the resultant beat wave is shown below

Plot of frequency equal to 20:


Plot of frequency equal to 400:
Resultant Beat Wave:
This should come as no surprise, that beating forms the basis for
Amplitude modulation.
Matlab/Scilab dictionary
Table of Contents:
abs (Matlab function) Absolute value and complex
magnitude
acos (Matlab function) Inverse cosine
acosh (Matlab function) Inverse hyperbolic cosine
acot (Matlab function) Inverse cotangent
acoth (Matlab function) Inverse hyperbolic cotangent
acsc (Matlab function) Inverse cosecant
acsch (Matlab function) Inverse hyperbolic cosecant
addition (Matlab function) Plus
all (Matlab function) Test to determine if all elements are
nonzero
and (Matlab function) Logical AND
angle (Matlab function) Phase angle
ans (Matlab function) The most recent answer
any (Matlab function) Test to determine if any
nonzeros elements
asec (Matlab function) Inverse secant
asech (Matlab function) Inverse hyperbolic secant
asin (Matlab function) Inverse sine
asinh (Matlab function) Inverse hyperbolic sine
atan (Matlab function) Two-quadrant inverse tangent
atan2 (Matlab function) Four-quadrant inverse tangent
atanh (Matlab function) Inverse hyperbolic tangent
balance (Matlab function) Diagonal scaling to improve
eigenvalue accuracy
bar (Matlab function) Bar histogram
barh (Matlab function) Bar histogram horizontal
beep (Matlab function) Produce a beep sound
besseli (Matlab function) Modified Bessel functions of
the first kind
besselj (Matlab function) Bessel functions of the first
kind
besselk (Matlab function) Modified Bessel functions of
the second kind
bessely (Matlab function) Bessel functions of the second
kind
beta (Matlab function) Beta function
bin2dec (Matlab function) Returns the integer
corresponding to a Given binary representation
bitand (Matlab function) The AND of two integers
bitcmp (Matlab function) The binary complementary of an
integer
bitget (Matlab function) Gets the bit of an integer whose
the positon is given in the input argument
bitor (Matlab function) The OR of two integers
bitxor (Matlab function) Returns the exclusive OR of two
integers
blanks (Matlab function) A string of blanks
box (Matlab function) Display axes border
break (Matlab function) Terminate execution of a for loop or
while loop
case (Matlab function) Case switch
cat (Matlab function) Arrays concatenation
cd (Matlab function) Change/get working directory
ceil (Matlab function) Round up
cell (Matlab function) Create cell array
cell2mat (Matlab function) Convert a cell array into a matrix
cellstr (Matlab function) Convert strings vector (or strings
matrix) into a cell of strings
chol (Matlab function) Cholesky factorization
cla (Matlab function) Clear current axes
clc (Matlab function) Clear Command Window
clear (Matlab function) Remove items from workspace, freeing
up system memory
clf (Matlab function) Clear current figure window
clock (Matlab function) Current time as a date vector
close (Matlab function) Delete specified figure
closereq (Matlab function) Default figure close request
function
colon (Matlab function) Colon
colordef (Matlab function) Set default property values to
display different color schemes
complex (Matlab function) Returns the complex form
corresponding to the given real part and imaginary part
conj (Matlab function) Complex conjugate
continue (Matlab function) Keyword to pass control to the
next iteration of a loop
conv (Matlab function) Convolution
cos (Matlab function) Cosine
cosh (Matlab function) Hyperbolic cosine
cot (Matlab function) Cotangent
coth (Matlab function) Hyperbolic cotangent
cputime (Matlab function) Elapsed CPU time
csc (Matlab function) Cosecant
csch (Matlab function) Hyperbolic cosecant
cumprod (Matlab function) Cumulative product
cumsum (Matlab function) Cumulative sum
date (Matlab function) Current date string
dec2bin (Matlab function) The binary representation of a decimal n
dec2hex (Matlab function) Decimal to hexadecimal number conver
delete (Matlab function) Delete files or graphics objects
det (Matlab function) Determinant
diag (Matlab function) Diagonal including or extracting
diary (Matlab function) Save session to a file
diff (Matlab function) Differences and approximate derivatives
dir (Matlab function) Display directory listing
disp (Matlab function) Display text or array
display (Matlab function) Overloaded method to display an
object
doc (Matlab function) Display online documentation
docopt (Matlab function) Web browser for UNIX platforms
dos (Matlab function) Execute a UNIX command and return
result
double (Matlab function) Conversion to double precision
drawnow (Matlab function) Complete pending drawing events
echo (Matlab function) Echo lines during execution
eig (Matlab function) Find eigenvalues and eigenvectors
elementwise multiplication (Matlab function) Elementwise
mutiplication
elementwise power (Matlab function) Elementwise exponent
elementwise right division (Matlab function) Elementwise left
division
elementwise transpose (Matlab function) Elementwise
transpose
else (Matlab function) Conditionally execute statements
elseif (Matlab function) Conditionally execute statements
end (Matlab function) Last index
eps (Matlab function) Floating-point relative accuracy
equal (Matlab function) Equal to
erf (Matlab function) Error function
erfc (Matlab function) Complementary error function
erfcx (Matlab function) Scaled complementary error function
error (Matlab function) Display error messages
etime (Matlab function) Elapsed time
eval (Matlab function) Execute a string containing an
instruction/expression
exist (Matlab function) Check if a variable or file exists
exit (Matlab function) Ends current session
exp (Matlab function) Exponential
expm (Matlab function) Matrix exponential
eye (Matlab function) Identity matrix
factor (Matlab function) Prime numbers decomposition
false (Matlab function) False array
fclose (Matlab function) Close one or more open files
feof (Matlab function) Test for end-of-file
ferror (Matlab function) Query about errors in file input or
output
feval (Matlab function) Function evaluation
fft (Matlab function) Discrete Fourier transform
fftshift (Matlab function) Shift zero-frequency component of
discrete Fourier transform to center of spectrum
fgetl (Matlab function) Read line(s) from file, discard newline
character
fgets (Matlab function) Read line from file, keep newline
character
fileparts (Matlab function) Return filename parts
filesep (Matlab function) Return the directory separator for
this platform
find (Matlab function) Find indices and values of nonzero
elements
findstr (Matlab function) Find one string within another
fix (Matlab function) Round towards zero
fliplr (Matlab function) Flip matrix in left/right direction
flipud (Matlab function) Flip matrix in up/down direction
floor (Matlab function) Round down
fopen (Matlab function) Open a file or obtain information about
open files
for (Matlab function) Repeat statements a specific number of
times
format (Matlab function) Control display format for output
fprintf (Matlab function) Write formatted data to file
fread (Matlab function) Read binary data to a file
frewind (Matlab function) Move the file position indicator to the
beginning of an open file
fscanf (Matlab function) Read formatted data to file
fseek (Matlab function) Set file position indicator
ftell (Matlab function) Get file position indicator
full (Matlab function) Convert sparse matrix to full matrix
fullfile (Matlab function) Build a full filename from parts
function (Matlab function) Function definition
fwrite (Matlab function) Write binary data to a file
gamma (Matlab function) Gamma function
gammaln (Matlab function) Logarithm of gamma function
getenv (Matlab function) Get environment variable
global (Matlab function) Define a global variable
graymon (Matlab function) Set graphics defaults for gray-
scale monitors
great (Matlab function) Greater than
great equal (Matlab function) Greater or equal to
grid (Matlab function) Grid lines for two- and three-
dimensional plots
hankel (Matlab function) Hankel matrix
help (Matlab function) Display help
helpbrowser (Matlab function) Display Help browser for
access to full online documentation
helpdesk (Matlab function) Display Help browser
helpwin (Matlab function) Provide access to and display help
for all functions
hess (Matlab function) Hessenberg form of a matrix
hold (Matlab function) Hold current graph
home (Matlab function) Move the cursor to the upper left
corner of the Command Window
horzcat (Matlab function) Horizontal concatenation
i (Matlab function) Imaginary unit
if (Matlab function) Conditionally execute statements
ifft (Matlab function) Inverse discrete Fourier transform
imag (Matlab function) Complex imaginary part
input (Matlab function) Request user input
int16 (Matlab function) Convert to 16-bit signed integer
int32 (Matlab function) Convert to 32-bit signed integer
int8 (Matlab function) Convert to 8-bit signed integer
interp1 (Matlab function) One_dimension interpolation function
inv (Matlab function) Matrix inverse
isa (Matlab function) Detect an object of a given type
iscell (Matlab function) Determine if input is a cell array
ischar (Matlab function) Determine if item is a character array
isdir (Matlab function) Determine if item is a directory
isempty (Matlab function) True for empty matrix
isequal (Matlab function) Determine if arrays are numerically equal
isfield (Matlab function) Determine if input is a structure array field
isfinite (Matlab function) True for finite elements
isglobal (Matlab function) Determine if item is a global variable
ishandle (Matlab function) Determines if values are valid graphics
object handles
ishold (Matlab function) Return hold state
isinf (Matlab function) True for infinite elements
isinteger (Matlab function) Detect whether an array has
integer data type
isletter (Matlab function) True for letters of the alphabet
islogical (Matlab function) Determine if item is a logical array
isnan (Matlab function) Detect NaN elements of an array
isnumeric (Matlab function) Determine if input is a numeric
array
ispc (Matlab function) Determine if PC (Windows) version
isreal (Matlab function) Determine if all array elements are
real numbers
isscalar (Matlab function) Determine if input is scalar
isspace (Matlab function) Detect elements that are ASCII
white spaces
issparse (Matlab function) Test if matrix is sparse
isstr (Matlab function) Determine if item is a character array
isstruct (Matlab function) Determine if input is a structure
array
isunix (Matlab function) Determine if Unix version
isvector (Matlab function) Determine if input is a vector
j (Matlab function) Imaginary unit
keyboard (Matlab function) Invoke the keyboard in a file
kron (Matlab function) Kronecker tensor product
left division (Matlab function) Left division
length (Matlab function) Length of vector
less (Matlab function) Smaller than
less equal (Matlab function) Smaller or equal to
linspace (Matlab function) Linearly spaced vector
load (Matlab function) Load workspace variables from disk
log (Matlab function) Natural logarithm
log10 (Matlab function) Common (base 10) logarithm
log2 (Matlab function) Base 2 logarithm and dissect
floating point number
logical (Matlab function) Convert numeric values to logical
lookfor (Matlab function) Search for specified keyword in
all help entries
lower (Matlab function) Convert string to lower case
lu (Matlab function) LU matrix factorization
max (Matlab function) Maximum
min (Matlab function) Minimum
mkdir (Matlab function)
mod (Matlab function) Modulus after division
more (Matlab function) Display Command Window output
one screenful at a time
multiplication (Matlab function) Mutiplication
nargin (Matlab function) Number of function input arguments
nargout (Matlab function) Number of function output arguments
ndims (Matlab function) Number of array dimensions
norm (Matlab function) Vector and matrix norms
not (Matlab function) Negation
not equal (Matlab function) Not equal to
num2str (Matlab function) Number to string conversion
ones (Matlab function) Create an array of all ones
or (Matlab function) Logical OR
otherwise (Matlab function) Default part of switch/select statement
pause (Matlab function) Halt execution temporarily
perms (Matlab function) Array of all permutations of vector components
permute (Matlab function) Permute the dimensions of an array
pi (Matlab function) Ratio of a circle's circumference to its diameter
pie (Matlab function) circular graphic
plot (Matlab function) Linear 2-D plot
pow2 (Matlab function) Base 2 power and scale floating-point numbers
power (Matlab function) Exponent
primes (Matlab function) Returns the primes numbers included
between 1 and given number
prod (Matlab function) Product of array elements
qr (Matlab function) Orthogonal-triangular decomposition
quit (Matlab function) Terminate session
rand (Matlab function) Uniformly distributed random numbers and
arrays
randn (Matlab function) Normally distributed random numbers and
arrays
rcond (Matlab function) Matrix reciprocal condition number estimate
real (Matlab function) Real part of a complex number
realmax (Matlab function) Largest positive floating-point number
realmin (Matlab function) Smallest positive floating-point number
rem (Matlab function) Remainder after division
repmat (Matlab function) Replicate and tile an array
reshape (Matlab function) Reshape array
return (Matlab function) Return to the invoking function
right division (Matlab function) Right division
round (Matlab function) Round to nearest integer
save (Matlab function) Save workspace variables from disk
schur (Matlab function) Schur decomposition
setstr (Matlab function) Set string flag
sign (Matlab function) Signum function
sin (Matlab function) Sine
sinh (Matlab function) Hyperbolic sine
size (Matlab function) Array dimension
sort (Matlab function) Sort elements in ascending order
sparse (Matlab function) Create sparse matrix
sqrt (Matlab function) Square root
strcmp (Matlab function) Compare strings
strcmpi (Matlab function) Compare strings ignoring case
strfind (Matlab function) Find one string within another
strrep (Matlab function) String search and replace
struct (Matlab function) Create struct array
subtraction (Matlab function) Minus
sum (Matlab function) Sum of array elements
surf (Matlab function) 3-D surface plot
svd (Matlab function) Singular value decomposition
switch (Matlab function) Switch among several cases based on expression
tan (Matlab function) Tangent
tanh (Matlab function) Hyperbolic tangent
tic (Matlab function) Starts a stopwatch timer
title (Matlab function) Display a title on a graphic window
toc (Matlab function) Read the stopwatch timer
toeplitz (Matlab function) Toeplitz matrix
transpose (Matlab function) Transpose
tril (Matlab function) Lower triangular part of a matrix
triu (Matlab function) Upper triangular part of a matrix
true (Matlab function) True array
type (Matlab function) List file
uigetdir (Matlab function) Standard dialog box for selecting a directory
uint16 (Matlab function) Convert to 16-bit unsigned integer
uint32 (Matlab function) Convert to 32-bit unsigned integer
uint8 (Matlab function) Convert to 8-bit unsigned integer
unix (Matlab function) Execute a UNIX command and return result
upper (Matlab function) Convert string to upper case
varargin (Matlab function) Pass variable numbers of arguments
varargout (Matlab function) Return variable numbers of arguments
vertcat (Matlab function) Vertical concatenation
waitforbuttonpress (Matlab function) Wait for key or mouse button press
warning (Matlab function) Display warning messages
while (Matlab function) Repeat statements an indefinite number of times
who (Matlab function) List variables in the workspace
whos (Matlab function) List variables in the workspace
winqueryreg (Matlab function) Get item from Microsoft Windows registry
xlabel (Matlab function) Display a string along the x axis
ylabel (Matlab function) Display a string along the y axis
zeros (Matlab function) Create an array of all zeros
zlabel (Matlab function) Display a string along the z axis
EMBEDDED INFORMATION:
Scilab comes with some built-in information structures. The major ones are:

The Help Browser that can be accessed from various windows. Its utility
improved with Scilab 5.3.1 when demonstrations were included, but the
Help Browser is still a hard nut for newbies. It confuses by sometimes
referring to obsolete functions

Demonstrations that can be accessed from the Console. Not really tutorials
and some of them act funny, some may cause Scilab to crash, and others
still ask for a C compiler

Error messages displayed on the Console. Quite basic messages,


sometimes confusing, sometimes too brief

What is really missing is an embedded tutorial (or even a users manual of the
Matlab style) that is updated with each Scilab
SCILAB INFORMATION ON THE WEB:
The main portal is Wiki Scilab, <http://wiki.scilab.org/Tutorials>, were most of the
accessible tutorials are listed
Scilabs forge <http://forge.scilab.org/> is a repository of work in progress, many of
which exist only in name. Its set of draft documents is valuable
Wiki Scilabs HowTo page <http://wiki.scilab.org/howto> has some articles of
interest
Free sites:
Scilab File Exchange website <http://fileexchange.scilab.org/>. A new
discussion forum managed by the Scilab team and dedicated to easily exchange
files, script, data, experiences, etc.
Google discussion group at <http://groups.google.com/group/ comp.soft-
sys.math.scilab/topics>
MathKB <http://www.mathkb.com/>. Contains, among other things, a Scilab
discussion forum. Mostly advanced questions
spoken-tutorial <http://spoken-tutorial.org/Study_Plans_Scilab/>. Screencasts
under construction by IIT Bombay. Scilab basics
SCILAB INFO ON WEB ( CONTD.)

YouTube has some video clips on Scilab, but nothing really valuable

Equalis <http://www.equalis.com>. By registering you gain free


access to the discussion forum
<http://usingscilab.blogspot.com/> used to be a very good blog but is
now terminally ill. Worth checking the material that is still there
Scilab India <http://scilab.in/> is basically a mirror of Scilab Wiki,
with added obsolete material and a less active discussion forum

If you know German:


German technical colleges produce helpful basic tutorials on Scilab
(better than their French counterparts). Search the Internet e.g. using
the terms Scilab + Einfhrung and limit the language option to
German
Simulation of cars waiting at a
toll booth using Scilab

Jianfeng Li
Institute of Industrial Process Control, Control Science and
Engineering Department,zhejiang university
2006.9
Introduction
The queue systems performance index
The optimal number of servers
Simulation
Conclusion
Introduction

Queuing theory
It is the study of the waiting line phenomena.
It is a branch of applied mathematics utilizing concepts from the
field of stochastic processes.
It is the formal analysis of this phenomenon in search of finding
the optimum solution to this problem so that everybody gets
service without waiting for a long time in line.
Introduction

The queue system is composed of


the arrival process the queue discipline the service process

If there is one server in all service process, it is


called single-server system.
If the server number is more than one and each
sever can serve customers independently, it is called
multi-server system
Introduction

Usually, the service system is evaluated by


performance indexes, such as
Service intensity
Average queuing length
Average queuing time
Average stay time
Probability of the service desks being idle
The probability of the customers having to wait
Introduction
The basic service process is the following:

busy
the customers arrive queuing system waiting line

free

served according to the prescribed queuing discipline

finished

leave the system


Introduction

The terms customer, server, service time, and


waiting time may acquire different meanings in
different applications.
In this article
The customers are cars arriving at a toll booth
The servers are the workers in the tool booth
The service times are the payment times
The queue systems performance
index
In the simulation of cars waiting at a toll booth,
some necessary condition assumptions and notation
definitions should be made.
Assumptions:
The arrival time and service time follow exponential distribution.
The waiting queue is infinite.
The queue systems performance
index
Notations:
: the arrival rate of the car
: the service rate of the car
: the service intensity
Ls: the average quantity of cars in the system
Lq: the average quantity of cars in the waiting queue
Ws: the average time of each car stay in the system
Wq: the average time of each car stay in the waiting queue
The queue systems performance
index

according to John DC Littles formula, we


only discuss two usual models.
Standard M/M/1 service model.
Standard M/M/C service model.
Standard M/M/1 service model

The arrival time and service time of cars can be


discretional distribution.
The number of server is one.
The car source and service space are infinite.
The queuing discipline is first come first service.
Standard M/M/1 service model

So the major performance indexes are:


Service intensity:
Probability of the server being idle:
P0 1
Probability of n cars in the system: Pn n (1 )
1
Ls ; Lq ; Ws ; Wq

Standard M/M/C service model
The arrival time and service time of cars can be
discretional distribution.
the number of server is C and they are parallel
connection .
Servers work independently and the average service
rate is the same.
The car source and service space are infinite.
The queuing discipline is first come first service.
Standard M/M/C service model

So the major performance indexes are:


Service intensity: c
C 1
1 K 1 1 c 1
Probability of the server being idle: P0 [ ( ) ( ) ]
K 0 K ! C ! 1
The average quantity of cars in the waiting queue: (c )c P0
Lq
C !(1 ) 2
The average quantity of cars in the system:
Ls Lq c
The average time of each car stay in the system:
1
Ws Wq
Probability of the car has to waiting after arriving:


1 n
P( n c ) ( ) P0
n c c !c n c

The optimal number of servers
Step 1, according to [ out
N min, find ] the initialization number of

servers ;
N Nmin
Step 2, compute the performance indexes, such as the average
quantity of cars in the waiting queue, the average time of each car
stay in the system, and the average time of each car stay in the
waiting queue. Comparing them with desired indexes, if it is
dissatisfied, go to step 3; otherwise, the optimal number of servers is
N and the process is end.
Step 3, let , go to step 2.

N N 1
Simulation
In this system, the arrival time and service time of car are similar to
the exponential distribution.
Assume that the left time of the ith car is the begin service time of
the (i+1)th car.
All the events can be classified to two sorts: one is the arrival event of
cars; the other is the leave event of car.
When the arrival event and the leave event occur at a same time,
disposed the former first.
Simulation

In Scilab simulation
environment, the average
arrival rate of cars, the
average service rate of cars
and the simulation
terminate time are given by
the following:
Simulation

In the simulation platform we present, the


draw mode of SCILAB is set to be animate all
along so that a gliding process can be
observed.
Simulation

The animation demo can be described as:


Simulation

Assume that the terminate time of simulation is 240


sec.
The average arrival rate is 0.18.
And the average service rate is 0.1.
The minimum servers number can be found out:
N [ ]
min =1.

The queuing discipline is first come first serve.


Simulation
The simulation results can be calculated:
The average quantity of cars in the waiting queue is: 15
The max quantity of cars in the waiting queue is: 26
The average quantity of cars in the system is: 16
The average time of each car stay in the waiting queue is: 146sec
The average time of each car stay in the system is: 162sec
All the served cars number is: 22
Simulation
Let N N min,the
1 number of server become 2.
The simulation process is similar to the above single
servers systems. The different is that, in the simulation,
when the second car arrival, it can be serviced
immediately because there are two servers in the
system. So the car will pass the toll booth with less
waiting time.
Simulation
The simulation results with two servers are:
The average quantity of cars in the waiting queue is:3
The max quantity of cars in the waiting queue is: 6
The average quantity of cars in the system is: 4
The average time of each car stay in the waiting queue is: 29sec
The average time of each car stay in the system is: 41sec
All the served cars number is: 42
Simulation

Comparing the above results with desired


performance index, it is found that when
there are two servers, the demands can be
satisfied.
So, it is recommended to open two servers.
Conclusion
Queuing theory have been used in almost every domain
of social and natural science as a tool to solve many
problems. In this article, queuing theory is used to solve
the problem of cars waiting in a tool booth.
Using the tools of Scilab, the simulation of a single
queuing multi-servers system is done and the optimal
number of server is obtained.
THE END
CONTACT :

Dr.P.S.SUBRAMANYAM :

[email protected]

You might also like