introduction to scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf ·...

24
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, extrac- tion or transpose are immediately performed as well as basic operations such as addition or multipli- cation. 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 ma- nipulating lists and typed lists which allow a natural symbolic representation of complicated math- ematical 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

Upload: vuongdiep

Post on 23-Mar-2018

256 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

CHAPTER 1

Introduction to Scilab

Scilab is a software package (more less same as matlab) that provides an environment which usesmatrices (both full and sparse) as it basic data type. Algorithms are available for the numerical solutionof 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 excellenttwo 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 forall standard operating system such as Windows, Macs, LINUX and UNIX. This chapter gives a basicidea 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 threedistinct parts: an interpreter, libraries of functions (Scilab procedures) and libraries of FORTRAN andC routines. These routines (which, strictly speaking, do not belong to Scilab but are interactively calledby the interpreter) are of independent interest and most of them are available through Netlib. A few ofthem have been slightly modified for better compatibility with Scilab’s interpreter. A key feature of theScilab syntax is its ability to handle matrices: basic matrix manipulations such as concatenation, extrac-tion or transpose are immediately performed as well as basic operations such as addition or multipli-cation. 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 ma-nipulating lists and typed lists which allow a natural symbolic representation of complicated math-ematical objects such as transfer functions, linear systems or graphs. Polynomials, polynomial matricesand transfer matrices are also defined and handled by the scilab. The syntax used for manipulating thesematrices 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 scicostoolbox allows the graphic definition and simulation of complex interconnected hybrid systems. Therealso exist numerical optimization facilities for non linear optimization (including non differentiableoptimization), quadratic optimization and linear optimization.

Scilab has an open programming environment where the creation of functions and libraries of functionsis completely in the hands of the user. Functions are recognized as data objects in Scilab and, thus it can

Page 2: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

2 Programming in Scilab 4.1

be manipulated or created as other data objects. For example, functions can be defined or called insideScilab 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 standardizedpackages 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 inter-face programs to add new primitives, i.e., to add new modules of FORTRAN or C code intoScilab.

• To support library development through “toolboxes” of functions devoted to specific applica-tions (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 filescilab.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 scilaband 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 alsocontains 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 berun by clicking the “Demos” button in front menu panel. This directory contains the codescorresponding to various demos. They are often useful for beginners. Most of plot commandsare illustrated by simple demo examples.

• examples contains useful examples of how to link external programs to scilab, using dynamiclink 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 man-ager created in order to manage remote executions of software and allow exchanges of mes-sages between those programs. It offers the possibility to exploit numerous machines on anetwork, as a virtual computer, by creating a distributed group of independent software (helpcommunications 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 interactivecommunication 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

Page 3: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

Introduction to Scilab 3

contain “Toolboxes” for control, signal processing, etc... Strictly speaking Scilab is not orga-nized 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 tosignal processing.

• man is the directory containing the manual, which divided into sub-manuals. The LATEX codeis 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 helpwindow 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 key-words known by the help and apropos commands are in .cat and whatis files located in the mansubdirectories.To add new items to the help and apropos commands the user can extend the list of directoriesavailable 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 thetransfer of Maple objects into Scilab functions. For efficiency, the transfer is made throughFORTRAN code generation which is dynamically linked to Scilab.

• routines is a directory which contains the source code of all the numerical routines. Thesubdirectory default is important since it contains the source code of routines which are neces-sary to customize Scilab. In particular user’s C or FORTRAN routines for ODE/DAE simula-tion or optimization can be included here (they can be also dynamically linked).

• intersci contains the program provided for building interface programs necessary to add newFortran 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 ofprinter’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 docu-

mentation.• 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 severalpopular Unix/Linux-XWindow systems such as: Dec Alpha (OSF V4), Dec Mips (ULTRIX 4.2), SunSparc stations (Sun OS), Sun Sparc stations (Sun Solaris), HP9000 (HP-UX V10), SGI Mips Irix, PCLinux. 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 wantto install Scilab (<scilab-path>)

2. Launch the following commands :[$SHELL] cd <scilab-path>

Page 4: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

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-path>/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 enlargedby the stacksize command. The default dimension of the internal stack can be adapted by modifying thevariable 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 thedirectory where Scilab is installed). This shell script runs Scilab in an Xwindow environment (this scriptfile can be invoked with specific parameters such as -nw for “no-window”). Immediatly the Scilabwindow with the following banner and prompt represented by the —>. Fig 1.1 shows the screen shotof 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 thescilab 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 awindow and copy it at the prompt in the Scilab window. The usual Emacs commands are at your

Page 5: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

Introduction to Scilab 5

disposal for modifying a command (Ctrl+<chr> means hold the CONTROL key while typing thecharacter <chr>), 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 yourcommands in an editor. Another way to “load” files containing Scilab statements is available with theFile/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 <item> 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 -nwinvokes 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 doingthat is to edit the files contained in the directory X11-defaults. The first possibility is to directly custom-ize these files. Another way is to copy the right lines with the modifications in the .Xdefaults file of thehome directory. These modifications are activated by starting again Xwindow or with the commandxrdb .Xdefaults. Scilab will read the .Xdefaults file: the lines of this file will cancel and replace thecorresponding lines of X11-defaults.

Page 6: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

6 Programming in Scilab 4.1

A simple example:

Xscilab.color*Scrollbar.background: redXscilab*vpane.height: 500Xscilab*vpane.width: 500in .Xdefaults will change the 500x650 window to a square window of 500x500 and thescrollbar 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 discussionsof all the topics are follows. Let me start discussing some simple commands used in scilab. At the endof the every command (press <ENTER> 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 statementissued and will show the answer. If there is a semicolon at the end of the statement, it will not look formanipulation 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

Page 7: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

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 pro-cessed and the second result is displayed because it is not followed by a semi-colon. The last commandshows how to write a command on several lines by using “...”. This sign is only needed in the on-linetyping for avoiding the effect of the carriage return. The chain of characters that follows the // is notinterpreted (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 envi-ronment 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 simplytyping, at the Scilab prompt:

—>a = [1,10,20; 5,6,7; 12,11,45] a =

1. 10. 20.

Page 8: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

8 Programming in Scilab 4.1

5. 6. 7. 12. 11. 45.

—>//It’s easy to get the transposed matrix:-->a’ans =

1. 5. 12. 10. 6. 11. 20. 7. 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 indexingprocedure. Writing a(1,2) would yield the element at row 1 and column 2 (note that the index starts at1 not the 0). Indexing a matrix beyond its bound will result in an error. Writing to a non-existent indexwill result in the matrix growing dynamically.

—>//To place the data (3) in 3x4 position of the matrix—>a(3,4) = 3 a =

1. 10. 20. 0. 5. 6. 7. 0. 12. 11. 45. 3.

We can create a vector of numbers 1,2,3, ... 10 by just by using a ‘colon’ operator. That is 1:10 meansstart from 1 to 10 by incrementing 1.

Page 9: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

Introduction to Scilab 9

—>a = 1:10 a = 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

—>1:2:10 ans = 1. 3. 5. 7. 9.

Note that 1:2:10 means create a vector starting from 1, each successive element being computed byadding 2, until the value becomes greater than 10. The example given below is an expression whichmixes 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

—>W(:,I) ans =

0.2113249 0.0002211 0.6653811 0.7560439 0.3303271 0.6283918

—>W($,$-1) ans =

0.6283918

First we have defined a vector of indices I, and W, which is a random 2 × 4 matrix. Other commandswill show us how to extract sub-matrices from W. The colon symbol stands for “all rows” or “allcolumns”. The $ symbol stands for the last row or last column index of a matrix or vector. The functionsqrt will help us to find the square root of any numbers.

—>sqrt([4 -4])

ans =

2. 2.i

Above command is calling a function (or primitive) with a vector argument. The response is a complexvector.

Page 10: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

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 createa vector containing all the angle values in this range and then we plot it (%pi is a constant standing forthe 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

column 10 to 13

0.2356194 0.2617994 0.2879793 0.3141593

column 14 to 17

0.3403392 0.3665191 0.3926991 0.4188790[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’ loopwhich can be entered at the Scilab prompt itself:

Page 11: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

Introduction to Scilab 11

—>s = 0 s =

0.

—>for i=1:3:10—> s = s + i—>end s =

1. s =

5. s =

12. s =

22.[More (y or n ) ?]

Such kind of all the control structures, loops, and other programming structures will be discussed in thethird chapter.

1.5.4. Defining Functions

Functions can also be defined in scilab by entered at the Scilab prompt. The syntax of the functiondefinition 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’ valuewill be ‘returned’ by the function. The argument ‘x’ is the input argument to the function. The functionreturns 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 Scilabprompt:

—>function [r1, r2] = foo (x, y)—> r1 = x + y;r2 = x - y—>endfunction

—>[p, q] = foo(10, 20)

Page 12: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

12 Programming in Scilab 4.1

q =

- 10. p =

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 =

0. 1. p =

2. 3.—>[p, q] = foo([1,2], [3,4,5]) !—error 8inconsistent additionat line 2 of function foo called by :[p, q] = foo([1,2], [3,4,5])

—>

It is possible to store function definitions in a file and load them at a later time. Suppose the abovefunction definition is stored in a file called ‘fun.sci’. We need to simply invoke file name, at the Scilabprompt 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 tovibrations. We see objects around us because these objects bounce back light signals to our eyes. OurTV and radio receive electromagnetic signals. We are immersed in a ‘sea of signals’! Analysis of signalsis therefore of central importance in most branches of science and engineering. It seems that mostcomplex things in this world can be explained on the basis of simpler things. Joseph Fourier’s insightwas that complex time varying signals can be expressed as a combination of simple sin/cos curves ofvarying frequency and amplitude. This section verifies the assumption by plotting a few simple equa-tions 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 sumof two ‘sin’ signals.

—>delta = (2*%pi)/240

Page 13: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

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 willhave to write a function to do this for you):

Fig. 1.4

Page 14: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

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 complexwaveform is given?

Let’s first write a function which performs simple numerical ‘integration’ over the range 0 to 2*PI. Wedivide 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 isthe idea behind the integration function, which can be typed at the Scilab prompt. The argument tointegrate is a vector of sin values in the range 0 to 2*PI-delta, where delta is (2*PI)/240. The differencebetween 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.5is what we get when we try to plot sin(x).*(-sin(x)) (Note that the .* operator performs member wisemultiplication 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 nowmove to a non-zero area.

—>integrate(sin(x).*(-sin(x))) ans =

Page 15: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

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 complexsignals. Multiplying a ‘sin’ with negative of a sine of a different frequency gives us zero – we get non-zero 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 valuetells us that sin(x) is present in the signal. Now we multiply the signal with -sin(2*x). If we get a non-zero result, that means that sin(2*x) is present in the signal. We repeat this process as many times as wewish.

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

Page 16: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

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

Page 17: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

Introduction to Scilab 17

Definition of a polynomial matrix. The syntax for polynomial matrices is the same as for constantmatrices. Calculation of the determinant of the polynomial matrix by the det function.

—>F=[1/s ,(s+1)/(1-s), s/p , s^2 ] F =

2

2

1 1+s s s

s 1-s 11+2s+s

—>F=[1/s ,(s+1)/(1-s)—> s/p , s^2 ] F =

1

s

1+s

1-s

2

s

1+2s+s

2s

1

—>//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 theform tlist(‘the type’,num,den) where num and den are two matrix polynomials). Retriev-ing the numerator and denominator matrices of F by extraction operations in a typed list. Last commandin the above section is the direct extraction of entry 1,2 of the numerator matrix F(‘num’).

—>pause

Page 18: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

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 thefirst environment are also available in the new environment. Variables created in the new environmentcan be returned to the original environment by using return. Use of return without an argumentdestroys all the variables created in the new environment before returning to the old environment. Thepause 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’);

Fig. 1.7

radians

magnitude

Page 19: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

Introduction to Scilab 19

Definition of a rational polynomial by extraction of an entry of the matrix F defined above. This isfollowed by the evaluation of the rational polynomial at the vector of complex frequency values definedby 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 therational polynomial F12. Note that the polynomial F12(‘den’) can be also obtained by extractionfrom the matrix F using the syntax F(‘num’)(1,2). The visualization of the resulting evaluation ismade by using the basic plot command plot2d (see Figure 1.7).

—>w=(1-s)/(1+s);f=1/p f =

2

1

1+2s+s

—>horner(f,w)

ans =

21+2s+s

4

The function horner performs a (possibly symbolic) change of variables for a polynomial (for ex-ample, 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 2

1+s 1+s

Definition of a linear system in state-space representation. The function syslin defines here thecontinuous time (‘c’) system Sl with state-space matrices (A,B,C). The function ss2tf transformsSl into transfer matrix representation.

—>s=poly(0,’s’);

—>R=[1/s,s/(1+s),s^2] R =

21 s s

s 1+s 1

—>Sl=syslin(‘c’,R);

—>tf2ss(Sl) ans =

Page 20: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

20 Programming in Scilab 4.1

ans(1) (state-space system:)

lss A B C D X0 dt

ans(2) = A matrix =

- 0.5 - 0.5 - 0.5 - 0.5

ans(3) = B matrix =

- 1. 1. 0. 1. 1. 0.

ans(4) = C matrix =

- 1. 0.

ans(5) = D matrix =

0 1 s2

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) transfermatrix R. tf2ss puts Sl in state-space representation with a polynomial D matrix. Note that linearsystems are represented by specific typed lists (with 7 entries).

—>sl1=[Sl;2*Sl+eye()] sl1 =

21 s s

s 1+s 1

22+s 2s 2s

s 1+s 1

—>size(sl1) ans =

2. 3.

—>size(tf2ss(sl1)) ans =

2. 3.

Page 21: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

Introduction to Scilab 21

sl1 is the linear system in transfer matrix representation obtained by the parallel inter-connection ofSl 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) ofa linear system (Sl) controlled by an observer with gain Ko and a controller with gain Kr. Note thatmatrices 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. 0. 0. - 4. - 3. 4. 4. 0. 0. - 3. 1. 0. 0. - 5. 1. ans =

- 1. - 1. - 1. + i - 1. - i

Call to the function compen defined above where the gains were calculated by a call to the primitiveppol which performs pole placement. The resulting Aclosed matrix is displayed and the placementof its poles is checked using the primitive spec which calculates the eigenvalues of a matrix. (Thefunction compen is defined here on-line by deff as an example of function which receive a linearsystem (Sl) as input and returns a linear system (Cl) as output. In general Scilab functions are definedin 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

Page 22: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

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 iscompiled (needs a compiler), dynamically linked to Scilab by the link command, and interactivelycalled 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 bythe definition of the constant a used in the function. The primitive ode then integrates the differentialequation defined by the Scilab function f(t,y) for y0=[1;0] at t=0 and where the solution isgiven at the time values.

=0,.02,.04,…,20t

(Function f can be defined as a C or FORTRAN program). The result is plotted in Figure 1.8 where thefirst element of the integrated vector is plotted against the second element of this vector.

Page 23: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

Introduction to Scilab 23

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)

Van der Pol

3

II

�3

�3 II 3

Page 24: Introduction to Scilab - newagepublishers.comnewagepublishers.com/samplechapter/001662.pdf · Introduction to Scilab3 contain “Toolboxes” for control, signal processing, etc

24 Programming in Scilab 4.1

Definition of a matrix containing character strings. By default, the operation of symbolic multiplicationof two matrices of character strings is not defined in Scilab. However, the (on-line) function definitionfor %cmc defines the multiplication of matrices of character strings (note that the double quote isnecessary because the body of the deff contains quotes inside of quotes). The % which begins thefunction definition for %cmc allows the definition of an operation which did not previously exist inScilab, and the name cmc means “chain multiply chain”. This example is not very useful: it is simplygiven to show how operations such as * can be defined on complex data structures by mean of scpecificScilab 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 =

− − 2 36+11x 6x +x

—>calcul([1,2,3],meth2)

ans =

− − 2 348+44x 12x +x

A simple example which illustrates the passing of a function as an argument to another function. Scilabfunctions are objects which may be defined, loaded, or manipulated as other objects such as matricesor lists.

—>quit

Exit from Scilab.