CHAPTER 1. Introduction to Scilab. Scilab is a software package (more less
same as matlab) that provides an environment which uses matrices (both full and
...
CHAPTER
1
Introduction to Scilab Scilab is a software package (more less same as matlab) that provides an environment which uses matrices (both full and sparse) as it basic data type. Algorithms are available for the numerical solution of differential equations, optimisation problems, interpolation and quadrature. FORTRAN and C codes (any user-defined or library functions) can be easily linked into Scilab. The package provides excellent two and three dimensional graphics which can be readily incorporated into reports and publications. Simple user interfaces can also be design and built using Scilab. Moreover the package is available for all standard operating system such as Windows, Macs, LINUX and UNIX. This chapter gives a basic idea on Scilab. The objective of this chapter is to give the user an idea of what Scilab can do.
1.1. THE SCILAB Scilab, developed at INRIA for system control and signal processing applications, is made of three distinct parts: an interpreter, libraries of functions (Scilab procedures) and libraries of FORTRAN and C routines. These routines (which, strictly speaking, do not belong to Scilab but are interactively called by the interpreter) are of independent interest and most of them are available through Netlib. A few of them have been slightly modified for better compatibility with Scilab’s interpreter. A key feature of the Scilab syntax is its ability to handle matrices: basic matrix manipulations such as concatenation, extraction or transpose are immediately performed as well as basic operations such as addition or multiplication. Scilab also aims at handling more complex objects than numerical matrices. For instance, control people may want to manipulate rational or polynomial transfer matrices. This is done by manipulating lists and typed lists which allow a natural symbolic representation of complicated mathematical objects such as transfer functions, linear systems or graphs. Polynomials, polynomial matrices and transfer matrices are also defined and handled by the scilab. The syntax used for manipulating these matrices is identical to that used for manipulating constant vectors and matrices. Scilab provides a variety of powerful primitives operations for the analysis of non-linear systems. Integration of explicit and implicit dynamic systems can be accomplished numerically. The scicos toolbox allows the graphic definition and simulation of complex interconnected hybrid systems. There also exist numerical optimization facilities for non linear optimization (including non differentiable optimization), quadratic optimization and linear optimization. Scilab has an open programming environment where the creation of functions and libraries of functions is completely in the hands of the user. Functions are recognized as data objects in Scilab and, thus it can
2 Programming in Scilab 4.1
be manipulated or created as other data objects. For example, functions can be defined or called inside Scilab and passed as input or output arguments of other functions. It supports a character string data type which, in particular, allows the on-line creation of functions. Matrices of character strings are also manipulated with the same syntax as ordinary matrices. Scilab is easily interfaced with FORTRAN or C subprograms. This allows us to use the standardized packages and libraries of the FORTRAN or C in the interpreted environment of Scilab. The general principle of Scilab is to provide the following sort of computing environment: • • •
•
To have data types which are varied and flexible with syntax that is natural and easy to use. To provide a reasonable set of primitives operations that serve as a basis for a wide variety of calculations. To have an open programming environment where new primitives functions (or library) are easily added. A useful tool distributed with Scilab is intersci, which is a tool for building interface programs to add new primitives, i.e., to add new modules of FORTRAN or C code into Scilab. To support library development through “toolboxes” of functions devoted to specific applications (linear control, signal processing, network analysis, non-linear control, etc.)
1.2. SCILAB ARCHITECTURE Scilab is divided into a set of directories. The main directory is SCIDIR, and it contains the startup file scilab.star, the copyright file notice.tex, and the configure file. The subdirectories are the following: •
•
• • •
• • • •
bin is the directory of the executable files. In Unix/Linux systems the starting script is scilab and in Windows95/NT operating system it is runscilab.exe. The executable code of Scilab: scilex on Unix/Linux systems and scilex.exe on Windows95/NT are there. This directory also contains Shell scripts for managing or printing Postscript/LATEX files produced by Scilab. demos is the directory of demos. The file alldems.dem allows adding a new demo which can be run by clicking the “Demos” button in front menu panel. This directory contains the codes corresponding to various demos. They are often useful for beginners. Most of plot commands are illustrated by simple demo examples. examples contains useful examples of how to link external programs to scilab, using dynamic link or intersci doc is the directory of the Scilab documentation, by default, which is in SCIDIR/doc/intro/ intro.tex. geci contains source code and binaries for GeCI which is an interactive communication manager created in order to manage remote executions of software and allow exchanges of messages between those programs. It offers the possibility to exploit numerous machines on a network, as a virtual computer, by creating a distributed group of independent software (help communications for a detailed description). GeCI is used for the link of Xmetanet with Scilab. pvm3 contains source code and binaries of the PVM version 3 which is another interactive communication manager. imp is the directory of the routines managing the Postscript files for print. libs contains the Scilab libraries (compiled code). macros contains the libraries of functions which are available on-line. New libraries can easily be added (see the Makefile). This directory is divided into a number of subdirectories which
Introduction to Scilab 3
•
•
•
•
• • • • • •
contain “Toolboxes” for control, signal processing, etc... Strictly speaking Scilab is not organized in toolboxes: functions of a specific subdirectory can call functions of other directories; for example, the subdirectory signal is not self-contained but its functions are all devoted to signal processing. man is the directory containing the manual, which divided into sub-manuals. The LATEX code is produced by a translation of the UNIX format Scilab manual (see the subdirectory SCIDIR/ man). To get information about an item, one should enter help item in Scilab or use the help window facility obtained with help button. To get information corresponding to a key-word, one should enter apropos key-word or use apropos in the help window. All the items and keywords known by the help and apropos commands are in .cat and whatis files located in the man subdirectories. To add new items to the help and apropos commands the user can extend the list of directories available to the help browser by editing the file SCIDIR/man/Chapters. maple is the directory which contains the source code of Maple functions which allow the transfer of Maple objects into Scilab functions. For efficiency, the transfer is made through FORTRAN code generation which is dynamically linked to Scilab. routines is a directory which contains the source code of all the numerical routines. The subdirectory default is important since it contains the source code of routines which are necessary to customize Scilab. In particular user’s C or FORTRAN routines for ODE/DAE simulation or optimization can be included here (they can be also dynamically linked). intersci contains the program provided for building interface programs necessary to add new Fortran or C primitives to Scilab. This program is executed by the intersci script in the bin/ intersci directory. scripts is the directory that contains the source code of shell scripts files. Note that the list of printer’s names known by Scilab is defined there by an environment variable. tests : this directory contains evaluation programs for testing Scilab’s installation on a machine. The file “demos.tst” tests all the demos. tmp : some examples written by users for courses, etc have been added in this directory. util contains some utility functions for calling Scilab as a sub-routine or for making the documentation. xless is the Berkeley file browsing tool. xmetanet is the directory which contains xmetanet, a graphic display for networks. Type metanet() in Scilab environment to use it.
1.3. INSTALLING SCILAB Scilab is an open source software and is distributed in binaries for Windows95/NT systems and several popular Unix/Linux-XWindow systems such as: Dec Alpha (OSF V4), Dec Mips (ULTRIX 4.2), Sun Sparc stations (Sun OS), Sun Sparc stations (Sun Solaris), HP9000 (HP-UX V10), SGI Mips Irix, PC Linux. All of these binaries versions include tk/tcl interface. 1.3.1. Scilab Installation under Linux 1. Get the binary file (scilab-4.1.bin.linux-i686.tar.gz) and save it in the directory where you want to install Scilab () 2. Launch the following commands : [$SHELL] cd
4 Programming in Scilab 4.1
[$SHELL] tar xzf scilab-4.1.bin.linux-i686.tar.gz [$SHELL] cd scilab-4.1 [$SHELL] make 3. To launch Scilab : [$SHELL] cd /scilab-4.1 [$SHELL] bin/scilab 1.3.2. Scilab Installation under Windows 1. Get the binary file (scilab-4.1.exe) and double click on this file to install the Scilab. 2. To launch Scilab, go in startup menu and double click on Scilab 4.1 Scilab uses a large internal stack for its calculations. This size of this stack can be reduced or enlarged by the stacksize command. The default dimension of the internal stack can be adapted by modifying the variable newstacksize in the scilab.star script.
1.4. GETTING STARTED WITH SCILAB Scilab can be executed by running the scilab script in the directory SCIDIR/bin (SCIDIR denotes the directory where Scilab is installed). This shell script runs Scilab in an Xwindow environment (this script file can be invoked with specific parameters such as -nw for “no-window”). Immediatly the Scilab window with the following banner and prompt represented by the —>. Fig 1.1 shows the screen shot of Scilab running in a Windows XP environment.
Fig. 1.1. Screen Shot of Scilab
During the execution of the scilab programs, several libraries (see the SCIDIR/scilab.star file from the scilab library) are automatically loaded. 1.4.1. Editing a Command Line Before the discussion on sample programs, let me introduce the briefly on how to edit a command line. You can enter a command line by typing after the prompt or clicking with the mouse on a part on a window and copy it at the prompt in the Scilab window. The usual Emacs commands are at your
Introduction to Scilab 5
disposal for modifying a command (Ctrl+ means hold the CONTROL key while typing the character ), for example: • • • • • • • • • • • •
Ctrl+p recall previous line Ctrl+n recall next line Ctrl+b move backward one character Ctrl+f move forward one character Ctrl+h delete previous character Ctrl+d delete one character (at cursor) Ctrl+a move to beginning of line Ctrl+e move to end of line Ctrl+k delete to the end of the line Ctrl+u cancel current line Ctrl+y yank the text previously deleted Ctrl+c interrupt Scilab and pause after carriage return. Clicking on the Control/stop button enters a Ctrl+c. As said before you can also cut and paste using the mouse. This way will be useful if you type your commands in an editor. Another way to “load” files containing Scilab statements is available with the File/File Operations button. 1.4.2. Controls The Scilab window has the following controls in the menu bar. • •
Stop interrupts execution of Scilab and enters in pause mode Resume continues execution after a pause entered as a command in a function or generated by the Stop button or Control C. • Abort aborts execution after one (or several) pause, and returns to top-level prompt • Restart clears all variables and executes startup files • Quit quits Scilab • Kill kills Scilab shell script • Demos for interactive run of some demos • File Operations facility for loading functions or data into Scilab, or executing script files. • Help: invokes on-line help with the tree of the man and the names of the corresponding items. It is possible to type directly help in the Scilab window. • Graphic Window: select active graphic window New buttons can be added by the addmenu command. Note that the command SCIDIR/bin/scilab -nw invokes Scilab in the “no-window” mode. 1.4.3. Customizing the Scilab The different parameters of the windows opened by Scilab can be easily changed. The way for doing that is to edit the files contained in the directory X11-defaults. The first possibility is to directly customize these files. Another way is to copy the right lines with the modifications in the .Xdefaults file of the home directory. These modifications are activated by starting again Xwindow or with the command xrdb .Xdefaults. Scilab will read the .Xdefaults file: the lines of this file will cancel and replace the corresponding lines of X11-defaults.
6 Programming in Scilab 4.1
A simple example: Xscilab.color*Scrollbar.background: red Xscilab*vpane.height: 500 Xscilab*vpane.width: 500 in .Xdefaults will change the 500x650 window to a square window of 500x500 and the scrollbar background color changes from green to red.
1.5. SAMPLE PROGRAMS FOR BEGINNERS This section introduces all the basic fundamental concepts used in the scilab. The detailed discussions of all the topics are follows. Let me start discussing some simple commands used in scilab. At the end of the every command (press key) carriage return to interpret and execute the same. —>//Command with NO semicolon —>a=3 a = 3. —>//Command with semicolon —>a=2; —>
Note that when a command with no semicolon at the end, will calculate the expression or statement issued and will show the answer. If there is a semicolon at the end of the statement, it will not look for manipulation just save the content to that variable. —>//Commands to add two variables —>a=1; —>A=2; —>a+A ans = 3. —>//Two commands on the same line —>c=[1 2];b=1.5 b = 1.5
Introduction to Scilab 7
—>//A command on several lines —>u=1000000.000000*(a*sin(A))^2+... —> 2000000.000000*a*b*sin(A)*cos(A)+... —> 1000000.000000*(b*cos(A))^2 u = 81268.994
The semi-colon at the end of the command that gives the values 1 and 2 to the variables a and A, suppresses the display of the result. Note that Scilab is case-sensitive. Then two commands are processed and the second result is displayed because it is not followed by a semi-colon. The last command shows how to write a command on several lines by using “...”. This sign is only needed in the on-line typing for avoiding the effect of the carriage return. The chain of characters that follows the // is not interpreted (it is a comment line). —>a=1;b=1.5; —>2*a+b^2 ans = 4.25 —>//Now we have created variables and they can be listed by typing:
Who command will give us the list of previously defined variables a, b together with the initial environment composed of the different libraries and some specific “permanent” variables. 1.5.1. Matrix Operations Now let’s get started by doing a few simple matrix manipulations. A 3-by-3 matrix is created by simply typing, at the Scilab prompt: —>a = [1,10,20; 5,6,7; 12,11,45] a = 1.
10.
20.
8 Programming in Scilab 4.1
5. 12.
6. 11.
7. 45.
—>//It’s easy to get the transposed matrix: -->a’ ans = 1. 10. 20.
5. 6. 7.
12. 11. 45.
A few other primitive functions are: —>//Sum the column elements —>sum(a, ‘c’) ans = 31. 18. 68. —>//Sum the row elements —>sum(a, ‘r’) ans = 18.
27.
72.
—>//The diagonal elements of a matrix can be obtained —>diag(a) ans = 1. 6. 45.
Elements can be extracted from matrices in many different ways - the simplest is the standard indexing procedure. Writing a(1,2) would yield the element at row 1 and column 2 (note that the index starts at 1 not the 0). Indexing a matrix beyond its bound will result in an error. Writing to a non-existent index will result in the matrix growing dynamically. —>//To place the data (3) in 3x4 position of the matrix —>a(3,4) = 3 a = 1. 5. 12.
10. 6. 11.
20. 7. 45.
0. 0. 3.
We can create a vector of numbers 1,2,3, ... 10 by just by using a ‘colon’ operator. That is 1:10 means start from 1 to 10 by incrementing 1.
Introduction to Scilab 9
—>a = 1:10 a = 1. 2.
3.
4.
5.
—>1:2:10 ans = 1. 3.
5.
7.
9.
6.
7.
8.
9.
10.
Note that 1:2:10 means create a vector starting from 1, each successive element being computed by adding 2, until the value becomes greater than 10. The example given below is an expression which mixes constants with existing variables. The result is retained in the standard default variable ans. —>I=1:3 I = 1.
2.
3.
—>W=rand(2,4); —>W(1,I) ans = 0.2113249
0.0002211
0.6653811
0.0002211 0.3303271
0.6653811 0.6283918
—>W(:,I) ans = 0.2113249 0.7560439 —>W($,$-1) ans = 0.6283918
First we have defined a vector of indices I, and W, which is a random 2 × 4 matrix. Other commands will show us how to extract sub-matrices from W. The colon symbol stands for “all rows” or “all columns”. The $ symbol stands for the last row or last column index of a matrix or vector. The function sqrt will help us to find the square root of any numbers. —>sqrt([4 ans 2.
-4])
= 2.i
Above command is calling a function (or primitive) with a vector argument. The response is a complex vector.
10 Programming in Scilab 4.1
1.5.2. Simple Plotting Let’s look at an example to plot simple sine wave. Our objective is to plot one full cycle of the sin curve (from 0 to 2*PI) – let’s take 240 points in between, so each division would be 2*PI/240. First we create a vector containing all the angle values in this range and then we plot it (%pi is a constant standing for the value of PI): —>x = 0:(2*%pi)/240:2*%pi x = column 1 to 5 0.
0.0261799
0.0523599
0.0785398
0.1047198
column 6 to 9 0.1308997
0.1570796
0.1832596
0.2094395
0.2879793
0.3141593
0.3926991
0.4188790
column 10 to 13 0.2356194
0.2617994
column 14 to 17 0.3403392 0.3665191 [More (y or n ) ?]
Now, we use a simple plot function to plot the sin wave: —>plot(x, sin(x))
Above command will given us the following sin wave in Fig 1.2.
Fig. 1.2. Sin Wave Plotting
1.5.3. Writing Scilab Scripts Let me introduce fundamentals of writing simple Scilab scripts. Here is an example of a ‘for’ loop which can be entered at the Scilab prompt itself:
Introduction to Scilab 11
—>s = 0 s = 0. —>for i=1:3:10 —> s = s + i —>end s =
s
1. =
s
5. =
s
12. =
22. [More (y or n ) ?]
Such kind of all the control structures, loops, and other programming structures will be discussed in the third chapter. 1.5.4. Defining Functions Functions can also be defined in scilab by entered at the Scilab prompt. The syntax of the function definition is discussed below with an example: —>function [r] = my_sqr(x) —> r = x * x —>endfunction —>my_sqr(3) ans = 9. —>
After the keyword ‘function’, we supply a list of ‘output values’. Any value written to an ‘output’ value will be ‘returned’ by the function. The argument ‘x’ is the input argument to the function. The function returns the value ‘r’ which is the square of ‘x’. The question obviously is what if we want to return two values. We try the following at the Scilab prompt: —>function [r1, r2] = foo (x, y) —> r1 = x + y;r2 = x - y —>endfunction —>[p, q] = foo(10, 20)
12 Programming in Scilab 4.1
q
=
p
- 10. = 30.
—>
Note the special way we call the function. The value of ‘r1’ will get transferred to ‘p’ and value of ‘r2’ to ‘q’. The following invocation of function ‘foo’ demonstrates the fact that the language is dynamically typed. —>[p, q] = foo([1,2], 1) q =
p
0. =
1.
2. 3. —>[p, q] = foo([1,2], [3,4,5]) !—error 8 inconsistent addition at line 2 of function foo [p, q] = foo([1,2], [3,4,5])
called by :
—>
It is possible to store function definitions in a file and load them at a later time. Suppose the above function definition is stored in a file called ‘fun.sci’. We need to simply invoke file name, at the Scilab prompt to execute the function: —>exec(‘fun.sci’)
Function declaration, definition, and calling are further discussed in the chapter 3. 1.5.5. Signals and Scilab We encounter ‘signals’ everywhere. The PC speaker generates sound by converting electrical signals to vibrations. We see objects around us because these objects bounce back light signals to our eyes. Our TV and radio receive electromagnetic signals. We are immersed in a ‘sea of signals’! Analysis of signals is therefore of central importance in most branches of science and engineering. It seems that most complex things in this world can be explained on the basis of simpler things. Joseph Fourier’s insight was that complex time varying signals can be expressed as a combination of simple sin/cos curves of varying frequency and amplitude. This section verifies the assumption by plotting a few simple equations with the help of Scilab. We have already seen how to plot a sine wave. Let’s now discuss another simple script to find the sum of two ‘sin’ signals. —>delta = (2*%pi)/240
Introduction to Scilab 13
delta
=
0.0261799 —>x = 0:delta:2*%pi —>a = sin(x) - (1/2)*sin(2*x) —>plot(x, a)
This will plot the figure as in Fig 1.3:
Fig. 1.3
When we keep on adding the term (1/3)*sin(3*x) to the above sin wave, it may look like. b = sin(x) - (1/2)*sin(2*x) + (1/3)*sin(3*x)
When the term is added to the series, the next term would be -(1/4)*sin(4*x), the next one +(1/ 5)*sin(5*x) and so on. Here is what we get when we plotted this series with 200 terms in it (you will have to write a function to do this for you):
Fig. 1.4
14 Programming in Scilab 4.1
1.5.6. Determining the Components of a Signal We have discussed in the above section that when we add different frequency and amplitude sin wave, the resultant signal looks totally different. Now the question is that to find out what combination of sin’s (frequency and amplitude) gave rise to that particular signal if some numbers that represent a complex waveform is given? Let’s first write a function which performs simple numerical ‘integration’ over the range 0 to 2*PI. We divide the area under our curve into tiny strips, each of width say 2*PI/240. The area of a strip at point ‘x’ (0 < x < 2*PI) will be its height multiplied by the width, which will be sin(x) * (2*PI/240). This is the idea behind the integration function, which can be typed at the Scilab prompt. The argument to integrate is a vector of sin values in the range 0 to 2*PI-delta, where delta is (2*PI)/240. The difference between two successive values in the vector is ‘delta’. —>function [r] = integrate(a) —> r = sum(a)*(2*%pi)/240 —>endfunction
Let’s try integrating the simple sin function, sin(x). —>x = 0:delta:(2*%pi-delta) —>integrate(sin(x)) ans = 3.837E-16
We see that the integral is zero. The sin curve has equal area above and below the zero-point. Fig 1.5 is what we get when we try to plot sin(x).*(-sin(x)) (Note that the .* operator performs member wise multiplication of two vectors):
Fig. 1.5
In Fig 1.5 we can see that the function has been shifted completely below the zero-point. It should now move to a non-zero area. —>integrate(sin(x).*(-sin(x))) ans =
Introduction to Scilab 15
- 3.1415927 —>
Scilab tells us it is -PI. Fig 1.6 is the graph we get, when we try to plot sin(2*x).*(-sin(x)).
Fig. 1.6
The graph tells us that the integral should be zero. This can be verify by: —>integrate(sin(2*x).*(-sin(x))) ans = 3.977E-16
By now you might have got a feel of the idea to employ and separate out the components of complex signals. Multiplying a ‘sin’ with negative of a sine of a different frequency gives us zero – we get nonzero results only when the frequencies matches. Say our complex signal is: sin(x) - (1/2)*sin(2*x) + (1/3)*sin(3*x) - (1/5)*sin(5*x)
If we multiply this with -sin(x), what we get is: sin(x).*(-sin(x)) - (1/2)*sin(2*x).*(-sin(x)) + (1/3)*sin(3*x).*(-sin(x)) - (1/5)*sin(5*x).*(-sin(x))
The first term gives us -PI, all other terms become zero. The fact that we are getting a non zero value tells us that sin(x) is present in the signal. Now we multiply the signal with -sin(2*x). If we get a nonzero result, that means that sin(2*x) is present in the signal. We repeat this process as many times as we wish. Now let us see how do we get the amplitude of each component? Let’s try out another experiment: —>b = sin(x) - (1/2)*sin(2*x) + (1/3)*sin(3*x) - (1/4)*sin(4*x) —>integrate(b.*(-sin(x))) ans = - 3.1415927
16 Programming in Scilab 4.1
—>integrate(b.*(-sin(2*x))) ans = 1.5707963 —>integrate(b.*(-sin(3*x))) ans = - 1.0471976 —>integrate(b.*(-sin(4*x))) ans = 0.7853982
Here we see that dividing each result by -PI gives us the amplitude of each component of the signal. More on this section is discussed in the Scilab Graphics chapter. 1.5.7. Handling Polynomials In this section let us discuss about how to handle polynomials. Polynomials can be represented using the scilab as follows. —>p=poly([1 2 3],’z’,’coeff’) p
= 1 + 2z + 3z2
—>//p is the polynomial in z with coefficients 1,2,3. —>//p can also be defined (or represented) by: —>s=poly(0,’s’);p=1+2*s+s^2 p
= 1 + 2s + s2
A more complicated command that creates a polynomial in matrix form can represented as: —>M=[p, p-1; p+1 ,2] M = 1 + 2s + s2
2s + s2
2 + 2s + s2
2
—>//Determinant of the polynomial matrix can be find as —>det(M) ans = 2 - 4s2 - 4s3 - s4
Introduction to Scilab 17
Definition of a polynomial matrix. The syntax for polynomial matrices is the same as for constant matrices. Calculation of the determinant of the polynomial matrix by the det function. —>F=[1/s F =
,(s+1)/(1-s),
1 1+s s s 1-s 1+2s+s2
s/p
,
s^2
]
s2 1
—>F=[1/s ,(s+1)/(1-s) —> s/p , s^2 ] F =
1 s
1+s 1-s
s2 1
s 1+2s+s2
—>//To show the numerator of the fraction matrix —>F(‘num’) ans = 1
1 + s
s
s2
—>//To show the denominator of the fraction matrix —>F(‘den’) ans = s
1 - s
1 + 2s + s2
1
—>//To show the numerator of the 1x2 element in the fraction matrix —>F(‘num’)(1,2) ans = 1 + s
Definition of a matrix of rational polynomials. (The internal representation of F is a typed list of the form tlist(‘the type’,num,den) where num and den are two matrix polynomials). Retrieving the numerator and denominator matrices of F by extraction operations in a typed list. Last command in the above section is the direct extraction of entry 1,2 of the numerator matrix F(‘num’). —>pause
18 Programming in Scilab 4.1
-1->pt=return(s*p) —>pt pt
= s + 2s2 + s3
Here we move into a new environment using the command pause and we obtain the new prompt -1-> which indicates the level of the new environment (level 1). All variables that are available in the first environment are also available in the new environment. Variables created in the new environment can be returned to the original environment by using return. Use of return without an argument destroys all the variables created in the new environment before returning to the old environment. The pause facility is very useful for debugging purposes. —>F21=F(2,1);v=0:0.01:%pi;frequencies=exp(%i*v); —>response=freq(F21(‘num’),F21(‘den’),frequencies); —>plot2d(v’,abs(response)’,[-1],’011',’ ‘,[0,0,3.5,0.7],[5,4,5,7]); —>xtitle(‘ ‘,’radians’,’magnitude’);
magnitude
radians
Fig. 1.7
Introduction to Scilab 19
Definition of a rational polynomial by extraction of an entry of the matrix F defined above. This is followed by the evaluation of the rational polynomial at the vector of complex frequency values defined by frequencies. The evaluation of the rational polynomial is done by the primitive freq. F12(‘num’) is the numerator polynomial and F12(‘den’) is the denominator polynomial of the rational polynomial F12. Note that the polynomial F12(‘den’) can be also obtained by extraction from the matrix F using the syntax F(‘num’)(1,2). The visualization of the resulting evaluation is made by using the basic plot command plot2d (see Figure 1.7). —>w=(1-s)/(1+s);f=1/p f =
1 1+2s+s2 —>horner(f,w) ans
=
1+2s+s2 4
The function horner performs a (possibly symbolic) change of variables for a polynomial (for example, here, to perform the bilinear transformation f(w(s))). —>A=[-1,0;1,2];B=[1,2;2,3];C=[1,0]; —>Sl=syslin(‘c’,A,B,C); —>ss2tf(Sl) ans = 1 1+s
2 1+s
Definition of a linear system in state-space representation. The function syslin defines here the continuous time (‘c’) system Sl with state-space matrices (A,B,C). The function ss2tf transforms Sl into transfer matrix representation. —>s=poly(0,’s’); —>R=[1/s,s/(1+s),s^2] R = 1 s s 1+s
s2 1
—>Sl=syslin(‘c’,R); —>tf2ss(Sl) ans =
20 Programming in Scilab 4.1
ans(1) lss
A
B
(state-space system:)
C
D
X0
dt
ans(2) = A matrix = - 0.5 - 0.5
- 0.5 - 0.5 ans(3) = B matrix =
- 1. 1.
1. 1.
0. 0.
ans(4) = C matrix = - 1.
0. ans(5) = D matrix =
0
s2
1
ans(6) = X0 (initial state) = 0. 0. ans(7) = Time domain = c
Definition of the rational matrix R. Sl is the continuous-time linear system with (improper) transfer matrix R. tf2ss puts Sl in state-space representation with a polynomial D matrix. Note that linear systems are represented by specific typed lists (with 7 entries). —>sl1=[Sl;2*Sl+eye()] sl1 = 1 s s 1+s
s2 1
2+s 2s s 1+s
2s2 1
—>size(sl1) ans = 2.
3.
—>size(tf2ss(sl1)) ans =
2.
3.
Introduction to Scilab 21
sl1 is the linear system in transfer matrix representation obtained by the parallel inter-connection of Sl and 2*Sl +eye(). The same syntax is valid with Sl in state-space representation. —>deff(‘[Cl]=compen(Sl,Kr,Ko)’,[ ‘[A,B,C,D]=abcd(Sl);’; —> ‘A1=[A-B*Kr ,B*Kr; 0*A ,A-Ko*C]; Id=eye(A);’; —> ‘B1=[B; 0*B];’; —> ‘C1=[C ,0*C];Cl=syslin(‘’c’’,A1,B1,C1)’ ])
On-line definition of a function, called compen which calculates the state space representation (Cl) of a linear system (Sl) controlled by an observer with gain Ko and a controller with gain Kr. Note that matrices are constructed in block form using other matrices. —>A=[1,1 ;0,1];B=[0;1];C=[1,0];Sl=syslin(‘c’,A,B,C); —>Cl=compen(Sl,ppol(A,B,[-1,-1]),... —> ppol(A’,C’,[-1+%i,-1-%i])’); —>Aclosed=Cl(‘A’),spec(Aclosed) Aclosed = 1. 1. - 4. - 3. 0. 0. 0. 0. ans = -
0. 4. - 3. - 5.
0. 4. 1. 1.
1. 1. 1. + i 1. - i
Call to the function compen defined above where the gains were calculated by a call to the primitive ppol which performs pole placement. The resulting Aclosed matrix is displayed and the placement of its poles is checked using the primitive spec which calculates the eigenvalues of a matrix. (The function compen is defined here on-line by deff as an example of function which receive a linear system (Sl) as input and returns a linear system (Cl) as output. In general Scilab functions are defined in files and loaded in Scilab by getf). —>//Saving the environment in a file named : myfile —>save(‘myfile’) —>//Request to the host system to perform a system command —>unix_s(‘rm myfile’) —>//Request to the host system with output in this Scilab window —>unix_w(‘date’) Thu Nov 12 15:54:58 MET 1998
22 Programming in Scilab 4.1
Relation with the Unix environment. —>foo=[‘void foo(a,b,c)’; —> ‘double *a,*b,*c;’ —> ‘{ *c = *a + *b;}’] foo = void foo(a,b,c) double *a,*b,*c; { *c = *a + *b;} —>write(‘foo.c’,foo); —>unix_s(‘make foo.o’) —>link(‘foo.o’,’foo’,’C’); —>deff(‘[c]=myplus(a,b)’,... —> ‘c=fort(‘’foo’’,a,1,’’d’’,b,2,’’d’’,’’out’’,[1,1],3,’’d’’)’) —>myplus(5,7) ans = 12.
Definition of a column vector of character strings used for defining a C function file. The routine is compiled (needs a compiler), dynamically linked to Scilab by the link command, and interactively called by the function myplus. —>deff(‘[ydot]=f(t,y)’,’ydot=[a-y(2)*y(2) -1;1 0]*y’) —>a=1;y0=[1;0];t0=0;instants=0:0.02:20; —>y=ode(y0,t0,instants,f); —>plot2d(y(1,:)’,y(2,:)’,[-1],’011',’ ‘,[-3,-3,3,3],[10,2,10,2]) —>xtitle(‘Van der Pol’)
Definition of a function which calculates a first order vector differential f(t,y). This is followed by the definition of the constant a used in the function. The primitive ode then integrates the differential equation defined by the Scilab function f(t,y) for y0=[1;0] at t=0 and where the solution is given at the time values. t = 0,.02,.04,…,20
(Function f can be defined as a C or FORTRAN program). The result is plotted in Figure 1.8 where the first element of the integrated vector is plotted against the second element of this vector.
Introduction to Scilab 23
Van der Pol 3
II
-3 -3
II
3
Fig. 1.8
—>m=[‘a’ ‘cos(b)’;’sin(a)’ ‘c’] m = a
cos(b)
sin(a)
c
—>//m*m’
—> error message : not implemented in scilab
—> deff(‘[x]=%c_m_c(a,b)’,[‘[l,m]=size(a);[m,n]=size(b);x=[];’; —> ‘for j=1:n,y=[];’; —> ‘for i=1:l,t=’’ ‘’;’; —> ‘for k=1:m;’; —> ‘if k>1 then t=t+’’+(‘’+a(i,k)+’’)*’’+’’(‘’+b(k,j)+’’)’’;’; —> ‘else t=’’(‘’ + a(i,k) + ‘’)*’’ + ‘’(‘’ + b(k,j) + ‘’)’’;’; —> ‘end,end;’; —> ‘y=[y;t],end;’; —> ‘x=[x y],end,’]) —>m*m’ ans = (a)*(a)+(cos(b))*(cos(b))
(a)*(sin(a))+(cos(b))*(c)
(sin(a))*(a)+(c)*(cos(b))
(sin(a))*(sin(a))+(c)*(c)
24 Programming in Scilab 4.1
Definition of a matrix containing character strings. By default, the operation of symbolic multiplication of two matrices of character strings is not defined in Scilab. However, the (on-line) function definition for %cmc defines the multiplication of matrices of character strings (note that the double quote is necessary because the body of the deff contains quotes inside of quotes). The % which begins the function definition for %cmc allows the definition of an operation which did not previously exist in Scilab, and the name cmc means “chain multiply chain”. This example is not very useful: it is simply given to show how operations such as * can be defined on complex data structures by mean of scpecific Scilab functions. —>deff(‘[y]=calcul(x,method)’,’z=method(x),y=poly(z,’’x’’)’) —>deff(‘[z]=meth1(x)’,’z=x’) —>deff(‘[z]=meth2(x)’,’z=2*x’) —>calcul([1,2,3],meth1) ans =
−6+11x − 6x2 +x3 —>calcul([1,2,3],meth2) ans
=
−48+44x − 12x2 +x3
A simple example which illustrates the passing of a function as an argument to another function. Scilab functions are objects which may be defined, loaded, or manipulated as other objects such as matrices or lists. —>quit
Exit from Scilab.