SCILAB Tutorial For DSP PDF
SCILAB Tutorial For DSP PDF
BY:
$
=
\
2010
Abstract
In this tutorial, Scilab is used for signal processing. The several
tools needed for completing the Practice of Discrete-Time Signal Pro-
cessing are described hereunder. Keep it for reference and use it at
your convenience.
1 About Scilab
Scilab is an open source, numerical computational package and a high-level,
numerically oriented programming language. Scilab provides an interpreted
programming environment, with matrices as the main data type. By util-
ising matrix-based computation, dynamic typing, and automatic memory
management, many numerical problems may be expressed in a reduced
number of code lines, as compared to similar solutions using traditional
programming languages.
Scilab binaries for GNU/Linux, Windows and Mac OS X platforms can
be downloaded directly from the Scilab homepage:
http://www.scilab.org
1
The homepage already detects the computers platform and shows a Down-
load Scilab banner to ease the download process. Then the installation
instructions must be followed. They are available in the Support / Docu-
mentation / Tutorials section (Introduction to Scilab) or in the README
files bundled with the downloaded tarball.
Scilab was created in 1990 by researchers from Institut National de
Recherche en Informatique et en Automatique (INRIA) and Ecole Nationale
des Ponts et Chaussees (ENPC). The Scilab Consortium was formed in May
2003 to broaden contributions and promote Scilab as worldwide reference
software in academia and industry. In July 2008, the Scilab Consortium
joined the Digiteo Foundation. Scilab is in continuous development; it is an
ongoing project in the Google Summer of Code.
2 Scilab environment
Once Scilab is launched, it provides a Command Line Interface on a console
to introduce the commands, and interprets them interactively after each
carriage return. The syntax interpreted by Scilab and some specific signal
processing functions are presented with a set of examples.
2.1 Variables
Variables are defined by case-sensitive alphanumeric identifiers (underscores
are also allowed). For example, to represent an integer number like a = 1 in
Scilab:
> a = 1
a =
1.
or a more general complex number like a = 1 + 3j:
> a = 1 + 3 * %i
a =
1. + 3.i
Note that Scilab uses the mathematical notation of i to refer to 1
instead of the common j used in the Theory. The % character before i is
used to escape the alphanumeric character of i that would generally refer
to a (non-predefined) variable.
2.2 Functions
Some useful functions for operating with a complex number x are:
2
The absolute value/magnitude abs(x)
3
The convolution convol(h,x)
2.3 Matrices
In the end, every variable refers to a matrix. In the former examples, number
a was stored in a 1 1 matrix. Row vectors (1 N matrices) may also be
defined in Scilab with the square brackets:
4
> rv = [ 1 2 3 4 ]
rv =
1. 2. 3. 4.
where N is the length of the vector (N = 4 in this example). For vectors,
there exists a function called length(x) that yields N .
In order to obtain a column vector (N 1 matrix), the rows are separated
with the semicolon:
> cv = [ 1; 2; 3; 4 ]
cv =
1.
2.
3.
4.
In order to access and use the content of a vector, the brackets are used
as dereference operators, bearing in mind that vectors are indexed following
[1 2 ... N-1]:
> cv(3)
ans =
3.
Note that when the result of a command is not assigned to a variable,
Scilab assigns its to the default answer (ans) variable. ans contains the
last unassigned evaluated expression.
Matrices are defined using both the row vector and column vector syntax:
> m = [ 11 12 13; 21 22 23 ]
m =
11. 12. 13.
21. 22. 23.
The numbers contained in this matrix example also indicate their index, so
that:
> m(1,2)
ans =
12.
The colon mark is of use to indicate all the elements in a row or column:
> m(1,:)
ans =
11. 12. 13.
where all the elements in the first row are displayed.
More enhanced dereferencing would include sequences. For example:
> 1:3
ans =
5
1. 2. 3.
indicates a sequence from 1 to 3, with a default increment of 1 unit, which
result would be equal to > 1:1:3. Alternatively,
> 1:2:3
ans =
1. 3.
indicates a sequence from 1 to 3, with an increment of 2 units, thus resulting
in 1 and 3. If this trick is applied on dereferencing a matrix variable:
> m(1,1:2:3)
ans =
11. 13.
Increments may also be negative, thus resulting in decreasing sequences:
> 3:-2:1
ans =
3. 1.
In order to retrieve the size of a matrix, the function size(x) is of use:
> size(m)
ans =
2. 3.
where the first number indicates the number of rows and the second the
number of columns.
Operation among elements (scalars, vectors and matrices) include the
dot/scalar product (*), the matrix addition (+), the matrix subtraction (),
the matrix multiplication (*), the matrix left division (\), the matrix right
division (/), the transpose () and the power (). Term-by-term multiplica-
tion (.*) and division (./) are also allowed.
Finally, to list the variables used in a session, the whos function displays
their names, types, sizes and number of bytes. And in order to prevent the
console from being too verbose, by appending a a semicolon at the end of a
command, the result is just not displayed.
2.4 Signals
In general, signals are represented by vectors, i.e. arrays of (not yet quan-
tised) samples. Inherently, the temporal difference that exists between two
consecutive samples (positions i and i + 1 in the vector) equals to one sam-
pling period.
For practical purposes, the signals generally refer to audio signals, and
the WAV format is of use for their portability. Therefore, in order to load
a WAV sound file into a y variable: y = wavread("file.wav");. More
6
information may be obtained from the WAV metadata through: [ y, fs,
bit ] = wavread("file.wav");, where fs keeps the sampling frequency
and bit keeps the number of bits used to encode each sample.
After the samples of a sound file are loaded into a variable, they can
be then reproduced by the computers soundcard through the sound(y,fs)
command. And in order to save the signal in a WAV file, the command
wavwrite(y,fs,bit,"file.wav") is of use. Note that Scilab always au-
toscales the signal in order to use the maximum dynamic range available,
therefore there is no need to multiply the signal by a constant in order to
raise the volume.
The following sections present common instructions to deal with signals
in Scilab.
x[n] = x(t) = sin 2 10 T n + 2
t = nT
7
Figure 1: Plot of x[n] vs. its sample indices.
x Base signal
fs Sampling frequency
which implies that T [k] is always positive (a delay always goes after the base
signal, it is like a kind of echo).
For example, taking the former sampled signal x[n] shown in Figure 1 as
the base signal x (this signal lasts 90.70ms), with y = delay(x,1e-1*[0 2
5],[1 0.5 -2],11025); a new signal y[n] would be obtained as a sampled
version of y(t) = x(t) + 0.5 x(t 200ms) 2 x(t 500ms), shown in Figure
2.
8
Figure 2: Example delay of x[n].
9
To this purpose, the function [h,H,ft] = h filter(G,N,fc1,fc2,fs) is
of use, where:
G Gain of the filters bandpass
10
Figure 3: Example magnitude frequency response |H(ej )|.
x Input signal
In case the designed filter has a FIR (e.g. produced with the h filter
function), then den = 1, and the coefficients of the impulse response directly
define the numerator of the transfer function, therefore filter(h,1,x).
It should be allowed to use the convol function (convolution) to attain
the same result as with the filter function, but for practical purposes the
latter is preferred (it is implemented with the Direct Form II Transposed in-
stead of the Fast Fourier Transform, refer to [Oppenheim and Schafer, 2009]
for further details).
3 Xcos
Xcos is a Scilab toolbox for the modelling and simulation of dynamical
systems. Xcos is particularly useful for modelling systems where continuous-
time and discrete-time components are interconnected.
Xcos provides a Graphical User Interface to construct complex dynamical
systems using a block diagram editor. These systems can in turn be reused
following a modular structure.
11
Figure 4: Example impulse response h[n].
under the Scilab menus. Once Xcos is loaded, it displays the Palette browser
and an empty diagram, see Figure 5.
3.2.1 Blocks
Xcos provides many elementary blocks organised in different palettes that
can be accessed using the operation View / Palette browser. Blocks from
palettes can be copied into the main Xcos diagram editor window by right-
clicking (context-menu button) first on the desired block and then clicking
the Add to option, or just by dragging and dropping them into the diagram
editor.
The behaviour of a Xcos block may depend on parameters that can be
modified. These parameters can be changed by double-clicking on the block.
This action opens up a dialogue box showing the current values of the block
parameters, and allowing the user to change them.
Often it is useful to use symbolic parameters to define block parameters.
This is particularly the case if the same parameter is used in more than one
12
Figure 5: Xcos loaded. The Palette browser and an empty diagram are
displayed.
3.2.2 Links
In order to interconnect the blocks in the diagram window, their input/output
ports (i.e. the arrows) have to be linked by dragging them from one to an-
other. Splits on links can also be created by dragging the existing links to
13
the new ports.
Xcos diagrams contain two different types of links. The regular links
transmit signals and the activation links transmit activation timing infor-
mation (synchronism), i.e., system events. By default, the activation links
are drawn in red and the regular links in black. And by convention, regu-
lar ports are placed on the sides of the blocks whereas activation ports are
respectively on the top and at the bottom of the blocks.
3.3.1 Setup
Simulation parameters can be set by the Simulation / Setup operation.
For example, one useful parameter to adjust is the final simulation time (in
14
seconds), otherwise the simulation goes on for a very long period of time
(100000 seconds by default). In order to do so, in the Set Parameters
window that pops up, adjust the Final integration time to the number of
samples that are to be simulated.
3.3.2 Start
To start a simulation, click on the Simulation / Start option, or the cor-
responding icon shortcut.
Running the simulation for a diagram leads to the opening of convenient
graphics windows to display the output signal of the simulation and/or any
other signals of interest set to be displayed (windows are opened and updated
by the scope block, see Section 3.4.2). A simulation can be stopped using the
Simulation / Stop option or the corresponding icon shortcut, subsequent
to which the user has the option of continuing the simulation, ending the
simulation, or restarting it.
3.4.1 Signals
Signal blocks are output systems, aka sources. They provide the input sig-
nals to the diagrams.
Unit step Given the Step time, the Initial value (0 by default) and the
Final value (1 by default), it outputs a step function at the specified
time. It is directly implemented in the Sources / STEP FUNCTION
block.
Unit rectangular pulse Defined by the duration of the pulse dp and the
time shift ts (initial time, when the pulse begins to rise). It may be
15
implemented with the difference between two unit step blocks and one
addition block Mathematical Operations / SUMMATION. The first
unit step is adjusted to rise at ts and the second at ts + dp, see Figure
6.
Unit triangular pulse Defined by the same parameters as the unit step
plus the duration of the pulse. It may be implemented by firstly sum-
ming three step function blocks with an addition block Mathematical
Operations / BIGSOM f, and then integrating the sum with one in-
tegral block Continuous time systems / INTEGRAL m. The first
2
step block begins at ts and has a final value of = dp , the second
step begins at ts + dp
2 and has a final value of 2, and the third step
begins at ts + dp and has a final value of . Also, the addition block
Inputs ports signs/gains parameter needs to be set to [1;1;1] in
order to define three input ports, see Figure 7.
Square wave Given the Amplitude M parameter, for every input event
it outputs M and M alternatively. It is directly implemented in the
Sources / GENSQR f block.
The needed activation events may be generated with an activation
clock block Sources / CLOCK c, given the desired Period and
Init time. And with an adequate delay of synchronism, a rectangular
pulse train may be obtained.
16
Figure 7: Xcos diagram of a unit triangular pulse.
17
Figure 8: Xcos diagram of a chirp signal.
Dirac comb Defined by the period T of the impulse train. Note that the
Dirac delta function does not exist in reality, hence it is approximated
by a triangular function of total integral 1 and a pulse duration of
18
Figure 10: Xcos diagram of a rectangular pulse train.
With the knowledge acquired to develop the previous basic signals, many
(other) arbitrary signals may be easily built.
19
Derivation Derives the input signal. It is implemented in the Continuous
time systems / DERIV block.
Sign Calculates the sign of the input signal value x, i.e., it outputs -1
for x < 0, 0 for x = 0 and 1 for x > 0. It is implemented in the
Mathematical Operations / SIGNUM block.
Mathematical expression Given the number of inputs (i.e., u1, u2, ...)
and a scilab expression, it permits evaluation a mathematical expres-
sion (using addition/subtraction, product/division and power raising).
It is implemented in the User-Defined Functions / EXPRESSION
block.
Filter Given the Numerator and the Denominator of the desired filter
in Laplace domain (obtained with any design method), it filters the
input signal. It is implemented in the Continuous time systems /
CLR block.
Sample and Hold Each time an activation event is received, it copies the
signal value of its input on its output, and holds it until a new activa-
tion event is received. It is implemented in the Signal Processing /
SAMPHOLD m block.
Quantisation Given a Step size (in amplitude units), it outputs the in-
put signal (with continuous amplitude) with discrete amplitude values.
It is implemented in the Signal Processing / QUANT f block.
20
Scope Given an activation event, it plots the present input signal value
onto a graphic window display. Therefore, the scope permits the vi-
sualisation of a given signal during the simulation. It is implemented
in the Sinks / CSCOPE for a single input signal, or in the Sinks /
CMSCOPE for multiple input signals.
References
[Campbell et al., 2005] Campbell, S. L., Chancelier, J.-P., and Nikoukhah,
R. (2005). Modeling and Simulation in Scilab/Scicos with ScicosLab 4.4.
Springer, New York, NY, USA, first edition.
[Trilla and Sevillano, 2010] Trilla, A. and Sevillano, X. (2010). Filter anal-
ysis and design. (Web-Available).
21