Sei sulla pagina 1di 21

Chapter

1 Scilab Basics
Fun, free, yet challenging. That's how I'd describe Scilab. Recalling those years in
the past when I was so clumsy with this open-source software, nowadays I simply
cannot live without it. I am often amazed to see the results come out professionally,
from basic feedback control analysis to advanced system simulation and design.
Thanks to the developers at Scilab Enterprise and elsewhere, who are working
relentlessly to improve the features and user-friendliness of Scilab.

No need to say more. If you have not yet tried it, go to www.scilab.org. A download
link, tailored to your choice of computer and operating system, is right there at the
top. Click on it to download and install. At the time this book is written, the current
version is Scilab 5.5.2, with Scilab 6.0 in Beta version. Both have similar interface.

The installation process is simple enough. I am happy with the default selection. If
you feel the need to change anything, feel free to do so. For the explanation in this
book, I will refer to Windows operating system unless stated otherwise.

After Scilab is installed, you 'll see Scilab icon on the desktop . Click on
it to launch. The first window that appears is the Scilab console as
shown in Figure 1.1. This is where variables can be created and
computed interactively by simply typing the initialization or expression
right after the --> prompt and press [Enter].

Figure 1.1 Scilab console


Chapter 1 Scilab Basics

As your first example, create a 2 x 2 matrix A


-->A=[1 2;-1 1]
A =

1. 2.
- 1. 1.

Well, to make it a little more interesting, let's say we have two linear equations with
2 unknowns x1 and x2
x1 + 2*x2 = 3
-x1 + x2 = -4

This can be formed into a matrix equation A*x = y, with A as above and y
constructed as follows
-->y = [3; -4]
y =
3.
- 4.

We know from linear algebra that x = [x1; x2] can be solved from x = A-1 y , or
in Scilab
-->x = inv(A)*y
x =
3.6666667
- 0.3333333

So far, so good. Of course, we can easily solve this by hand without Scilab, but how
about 10 equations with 10 unknowns?
For a more complicated problem, it is impractical to carry out the computation
interactively like this. Instead, we prefer to write a script or function. More on that
later.

1.1 Commonly-used Scilab Functions in Control Engineering


First and foremost, matrices and matrix operations play an important role in many
engineering disciplines, including control systems. So we discuss this topic first.

2
Feedback Control with Scilab and Arduino

1.1.1 Matrix Operations

A matrix with one row (column) is called a row (column) vector, or array. For
example, a row vector with index starts from 1 to 10 can be constructed easily as
follows
--> a = 1:10

a =

1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

We can also specify a step increment. This command creates a time sequence from 0
to 1 second, with period 0.1 sec between samples.
--> t = 0:0.1:1

t =

0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.

To extract a member (members) from an array, just specify the index (indices).
Remember that an array index in Scilab starts from 1.
--> t(2)

ans =

0.1

--> t(3:6)

ans =

0.2 0.3 0.4 0.5

Similar operations apply to a matrix.


--> A = [1 2 3;4 5 6;7 8 9]

A =

1. 2. 3.

4. 5. 6.

7. 8. 9.

--> A(:,1)

3
Chapter 1 Scilab Basics

ans =

1.

4.

7.

--> A(2,:)

ans =

4. 5. 6.

--> A(2:3,2:3)

ans =

5. 6.

8. 9

In contrast to extraction, we can augment members to the matrix A above. The row
and column numbers must be consistent, of course
--> B = [10 11 12]
B =
10. 11. 12.
--> [A; B]
ans =
1. 2. 3.
4. 5. 6.
7. 8. 9.
10. 11. 12.
One useful technique for array or matrix creation is by using a for or while loop.
Suppose we want to have a 10-element array of random data. Start from a variable
of nothing
--> V=[]
V =

[]
Then do this iteration
--> for i=1:10, V = [V rand()]; end
4
Feedback Control with Scilab and Arduino

The result is
--> V

V =
column 1 to 5
0.7560439 0.0002211 0.3303271 0.6653811 0.6283918

column 6 to 10
0.8497452 0.685731 0.8782165 0.068374 0.5608486

There are a lot more of matrix operations for you to experiment. Refer to the Scilab
help for information. Below is a list of some commonly used commands.

size(A) : return the size of an m x n matrix


length(A) : return number of elements in a matrix
eye(m,n) : construct an identity matrix
ones(m,n) : construct a matrix with all elements equal 1
inv(A) : matrix inversion
spec(A) : compute eigenvalues of a matrix

1.1.2 Complex Numbers

Certain control engineering subjects involve complex numbers, particularly in


chapter 3 when we discuss frequency responses of linear systems. So it might be
helpful to introduce complex number operations in this chapter.

Scilab uses %i to represent imaginary number; i.e., %i equals square root of -1.

Tips: Predefined constants in Scilab start with % sign. For example, %i, %pi

So, to create a complex number x = 2 + 0.5i


--> x = 2+0.5*%i

x =

2. +0.5i

whose real or imaginary parts can be easily extracted


--> real(x)

ans =

2.

5
Chapter 1 Scilab Basics

--> imag(x)

ans =

0.5

The above x is known as a rectangular form. We can convert it to a polar form as


follows
--> [r, th]=polar(x)
th =
0.2449787 -1.978D-16i
r =
2.0615528

Note that it is quite common for a computation result to have negligible imaginary
part, such as shown in the th value above. Unfortunately, sometimes this could
cause undesirable error in a script when the variable is passed to another function
that expects a real number. A quick fix is to use clean() function
--> clean(th)
ans =
0.2449787

A complex conjugate of x can be computed with the ' operation


--> x'
ans =
2. -0.5i

1.1.3 Polynomials and Rational Functions

An algebraic expression that contains polynomial of certain degree is quite common


in engineering. Polynomial creation and manipulation in Scilab is straightforward.
To create a polynomial, say D(q ) q 2 2q 1 , first a variable seed q is made.
--> q=poly(0,'q')
q =

Then we just form the equation

6
Feedback Control with Scilab and Arduino

--> D = q^2+2*q-1
D =
2
-1 +2q +q

Notice in the response that the polynomial is shown in reverse order. Thats a Scilab
behavior that might be different from some other software. Then we can do further
computation such as finding the roots
--> roots(D)
ans =
-2.4142136
0.4142136

To extract coefficients of a polynomial, use coeff() function


--> coeff(D)
ans =
-1. 2. 1.

Always remember that the coefficients start from lowest to highest order.

A rational function has polynomials as its numerator and denominator. To create one
such as
q 2 0.5q 3
H (i ) 3 (1.1)
3q 2q 2 q 1
simply type
--> H = (q^2+0.5*q+3)/(3*q^3-2*q^2+q-1)
H =
2
3 + 0.5q + q
-----------------
2 3
-1 + q - 2q + 3q

Numerator and denominator can be extracted from a rational function by using .num
and .den methods
--> H.num
ans =

7
Chapter 1 Scilab Basics

2
3 +0.5q +q
--> H.den
ans =
2 3
-1 +q -2q +3q

This will be handy when we discuss transfer functions in Chapter 3.

Before we pass this section, one last function worth mentioning is horner(). It is
useful when we want to substitute the polynomial variable as a function of another
variable. As an example, for the H(q) in (1.1), suppose we want to substitute

p 1
q
p
This can be done as follows
--> p=poly(0,'p');
--> horner(H,(p-1)/p)
ans =
2 3
p - 2.5p + 4.5p
-----------------
2 3
-3 + 7p - 6p + p

1.1.4 Plotting Functions

There are a couple of Scilab commands that can be used to display graphical data.
The simplest one is plot() function. Lets say we want to compare sine and cosine
signals of same frequency. This chunk of code
--> t=0:0.01:5;
--> x=sin(2*%pi*t);
--> y=cos(2*%pi*t);
--> plot(t,x,'r-',t,y,'b-');
--> legend('$sin(2\pi t)$','$cos(2\pi t)$');
-->xlabel('time (sec)');
results in the plot shown in Figure 1.2. Note in the plot command how we specify
line color and type. Also, the legend() function accepts LaTex format. Thats a
nice feature to display mathematical expression.
8
Feedback Control with Scilab and Arduino

Figure 1.2 sine and cosine comparison


Ex 1.1 Frequency response of a low-pass filter is expressed by
1
H (i ) (1.2)
0.1i 1
obtain a magnitude versus phase plot within frequency range 0.01 1000 rad/s
Though there exist Scilab commands to help you plot this easily, in this example we
will do it the straightforward way. First create 1000 frequency points in logarithmic
scale using logspace() function
--> w = logspace(-2,3,1000);
Then compute frequency response with the following lines of code
--> h_mag = [];
--> h_ph = [];
--> for k=1:length(w),
> h_w = 1/(0.1*%i*w(k)+1);
> [hm,hp]=polar(h_w);
> h_mag = [h_mag hm];
> h_ph = [h_ph clean(hp)];
> end

Use the plot2d() with the subplot() functions to achieve the frequency response
in Figure 1.3

9
Chapter 1 Scilab Basics

--> subplot(211),plot2d('ln',w,h_mag);
--> xlabel('Frequency (rad/s)');
--> ylabel('$|H(i\omega)|$');
--> xgrid
--> subplot(212),plot2d('ln',w,h_ph);
--> xlabel('Frequency (rad/s)');
--> ylabel('$\angle H(i\omega) (rad)$');
--> xgrid
Remarks:
subplot() divides the plot into panes, corresponding to the digits you put as
argument. The format is subplot(m,n,i) where m,n,i are number of rows,
number of columns, and plot index, respectively. For example
subplot(2,1,1), or briefly subplot(211), creates a 2-row,1-column plot,
with current plot set to the upper one. See help for more details.
'ln' argument in plot2d() sets the horizontal scale to logarithmic and
vertical scale to linear, a common setup for frequency response plot.
Color as well as other attributes can be passed as arguments.
The magnitude is shown in absolute value, while the phase is in radian.
This type of frequency response has a name Bode plot, more details in
Chapter 3.

Figure 1.3 frequency response plot of LPF in Ex 1.1

10
Feedback Control with Scilab and Arduino

1.2 Writing Scripts and Functions


It is not unusual if you try typing the chunk of code in Ex 1.1 and make some typos
that results in error. To fix it you need to retrieve the erroneous command (has
anyone told you about pressing the [up arrow] key to do so?), correct the mistake,
and run that line again as well as all the rest that depend on the result from that line.
Well, this could be problematic for a long and complex code. Thats why we prefer
to write it as a Scilab scripts or functions.
A Scilab script is a direct alternative to typing long command lines in console. So
lets talk about it first.
Though any text editor can be used, the
easiest way is to use SciNotes application
that comes with Scilab. On the menu,
click Applications -> SciNotes to launch
the editor. A black window Untitled 1
should appear. This is where you type all
the commands to compose the script file.
As an example, type all the commands in Ex 1.1. Comments can be added after two
slash characters //. It is always a good practice to leave meaningful comments
throughout the script file.
Figure 1.4 shows the script window containing commands from Ex 1.1 and added
comments. Save the file under any name, say, ex1p1.sce.

Fig 1.4 composing a Scilab script in SciNotes

11
Chapter 1 Scilab Basics

Tips: Default extension assigned by Scilab is .sce and .sci for script and function
file, respectively, though you can use any extension. Here we stick with the defaults.
To run the script, click the play button on the icon bar, or issue this command in
Scilab (make sure you are in the same directory where the script resides)
--> exec('ex1p1.sce',-1);
The -1 argument is optional. It just tells Scilab not to litter the console with
printouts. If there is no error in typing the command, youd see Figure 1.3 displayed
on screen. Now you can plot frequency response of another transfer function by
changing just h_w on line 7 leaving the rest of the code intact and re-executing the
script.
You can see that Scilab script is quite straightforward to compose. Whatever
command you type in the console, just put it in a file. Thats it. This programming
approach has some disadvantages
What if you want to change something frequently? The script has to be
edited, saved, and re-launched for each change. This could be inconvenient.
After a script is executed, all variables in that script remain in Scilab
workspace. They consume memory even though might not be used anymore.
Worse, variable name conflict could happen afterwards. That could cause a
bug difficult to trace.
We can fix this by writing a Scilab function instead. Any variable subjected to
change often can be made an argument of the function. Variables in a function are
defaulted to local, which mean they cease to exist after that function returns.
A function is composed between two keywords function and endfunction. You
can embed in any file; i.e., the filename does not have to match function name, and
several functions may be included in a file. When the file is executed, all functions
contained in that file are loaded to Scilab workspace and ready to be called from
other function, script, or command line at anytime until you exit Scilab.

Ex 1.2 From the script outline of Ex 1.1, we want to convert to a Scilab function
named frsp(), with input arguments H, wmin, wmax, wpts representing the
frequency response function, minimum, maximum frequency (in rad/s), and number
of frequency points, respectively. In addition to plotting, the function returns
magnitude, phase, and frequency arrays to Scilab workspace. The function syntax is
[mag, ph, wvec] = frsp(H, wmin, wmax, wpts)
Start by clicking File->New on SciNotes to open a new edit window. Add the
following skeleton
function [mag, ph, wvec]=frsp(H, wmin, wmax, wpts)

endfunction

12
Feedback Control with Scilab and Arduino

Now you have to figure out how to modify the script in Ex 1.1. One solution is
provided below.
//EX1P2.SCI
// scilab function for EX1.2
function [mag, ph, wvec]=frsp(H, wmin, wmax, wpts)
wvec = logspace(log10(wmin),log10(wmax),wpts);
mag = [];
ph = [];
for k=1:length(wvec);
h_w = horner(H,wvec(k)); // use horner() to evaluate H
[hm,hp]=polar(h_w); // compute magnitude and phase
mag = [mag hm]; // append to create magnitude array
ph = [ph clean(hp)]; // phase is cleaned to get rid of
// small imaginary parts
end
subplot(211),plot2d('ln',wvec,mag); // semi-log X format
xlabel('Frequency (rad/s)');
ylabel('$|H(i\omega)|$');
xgrid
subplot(212),plot2d('ln',wvec,ph); // plot phase response
xlabel('Frequency (rad/s)');
ylabel('$\angle H(i\omega) (rad)$');
xgrid
endfunction

Save the file as ex1p2.sci and then load the function to workspace
--> exec('ex1p2.sci',-1);
Now the function is available in workspace ready to be executed. To use it, first you
have to create a frequency response function. For example,
--> w=poly(0,'w');
--> H = 1/(1-w^2+0.1*%i*w)
H =
1
-----------------
2
1 + i*0.1w - w

13
Chapter 1 Scilab Basics

Then invoke the function frsp()


--> [h_mag,h_ph,wvec]=frsp(H,0.01,100,1000);
The result is the plot shown in Figure 1.5. Also observe the output vectors returned
from the function. Other local variables such as h_w, hm, hp are cleared after
frsp() returns.

Figure 1.5 frequency response plot from frsp() function


Tips: the function frsp() written as above is not quite flexible. It requires the user
to type all the 4 arguments. In fact, only the frequency response function is essential.
The rest can be omitted and the function assigns some default values. We can do so
by using varargin function, which allows variable number of arguments.
Modify the previous function and give it a new name, say, frspv(). Change the
function head and add some top lines as follows
function [mag, ph, wvec]=frspv(H, varargin)
wmin = 0.001; // assign default values first
wmax = 1000;
wpts = 1000;
numargs = length(varargin); // find number of arguments
if numargs==2,
wmin = eval(varargin(2)); // wmin is provided

14
Feedback Control with Scilab and Arduino

elseif numargs == 3,
wmax = eval(varargin(3)); // wmax is provided
elseif numargs == 4,
wpts = eval(varargin(4)); // wpts is provided
end
wvec = logspace(log10(wmin),log10(wmax),wpts);
// the rest of code remains the same
// :

Note: number of arguments is also contained in argn(2)


Now we can run the function with only frspv(H) with default frequency range and
points.

1.3 Simulation with Xcos


Simulation is an essential step to verify that the design conforms to the
specifications, and to learn system behavior in time-domain. When we install Scilab,
the package includes the simulation engine called Xcos (previously Scicos). If you
already have a model file (with extension .zcos)in the File Browser window, click
on the file to open that model. For a fresh start, type xcos in Scilab console to open
a blank new model.
Here we demonstrate with a simple PID feedback loop. Open the Palette browser
and drag blocks you need from groups of palettes to the Untitled window as shown
in Figure 1.6. What we need are the following blocks: CLOCK_c and
STEP_FUNCTION (from Sources palette), CSCOPE (from Sinks palette),
BIGSOM_f (from Mathematical Operations), CLR and PID (Continuous time
systems). Arrange the blocks naturally just like when we draw a block diagram on a
paper. The forward path flows from left to right, and feedback path goes the
opposite way.
After we have all the blocks, the next step is to connect them to become a feedback
system as in Figure 1.7. When you click on a port of one block, a line is drawn from
that port to the current mouse curser, where you place it on a port of another block.
Click when you see the green color to make solid connection. Note that output ports
cannot be connected. The red output port of the clock must connect to the red input
port of the scope.
After all the connections are done, click on each of the block to adjust its parameters
as shown in Figure 1.8. In this example we want to simulate a PID controller with a
third-order lag plant 1/(s+1)3. So click the CLR bock and input the numerator and
denominator accordingly as shown in Figure 1.8. Dont worry if you do not
understand this transfer function representation. It will be made clear in Chapter 3.

15
Chapter 1 Scilab Basics

Figure 1.6 dragging blocks from Palette browser to create a model

Figure 1.7 connect signal paths


Also make sure to adjust simulation parameters by choosing Simulation ->Setup
from the menu. The parameter window like in Figure 1.9 appears. For this simple
model, the only field that needs change is the topmost Final Integration Time. The
default value is a very large number that causes the simulation to run indefinitely.
Put in some final time that you want the simulation to stop, say, 10 seconds. You
need to click on the scope and adjust Refresh Period to the same value like shown in
Figure 1.10.
16
Feedback Control with Scilab and Arduino

Figure 1.8 change block parameters

Figure 1.9 simulation parameter setup

17
Chapter 1 Scilab Basics

Figure 1.10 adjust refresh period of scope


Figure 1.11 shows the complete model of PID feedback. Texts can be added for user
information, though they dont affect the simulation. You can download
pid_control1.zcos from our website and click on the play button to start the
simulation. Try adjusting three PID parameters arbitrarily. Putting in too large
values may cause instability. Figure 1.12 shows some simulation result.
At this point you may not have much knowledge about how to tune the PID
parameters properly. This topic will be covered in Chapter 4.
Note from the simulation result of Figure 1.12 that only plant output is plotted. We
can make the plot more informative by adding the command, in this case the step
input. Select the MUX block from Signal Routing palette and drag it to the model.
Place it near the scope input and make some signal routing modification as shown in
Figure 1.13, so that the step input and plant output are connected to the MUX inputs.
This setup results in both the command and plant response appear on the same plot
as shown in Figure 1.14.

Figure 1.11 pid_control1.zcos simple PID feedback model

18
Feedback Control with Scilab and Arduino

Figure 1.12 simulation result from pid_control1.zcos

Figure 1.13 pid_control2.zcos PID feedback model with multiplexed scope input

Figure 1.14 simulation result from pid_control2.zcos


This demonstration covers the basics of Xcos simulation. More features will be
discussed later in this book.

19
Chapter 1 Scilab Basics

1.4 Scilab GUI


In this section we briefly mention the GUI (Graphical User Interface) features of
Scilab, though this topic is quite rich in details. The developer should rely on Scilab
Help window for each particular function.
Figure 1.15 shows a Scilab GUI window I develop for a customized controller
board. This window facilitates communication with the target board via the serial
port. Essential controller parameter setup, analysis and synthesis are implemented.
Due to the limited resource of Arduino board, we may not be able to build advanced

Figure 1.15 an example of Scilab GUI window


GUI such as this, though it is possible to simplify the GUI to include only some
basic functionality such as PID parameter setup, for example.
As we see from Figure 1.15, Scilab GUI comprises various control objects such as
sliders, buttons, radios, edit boxes, etc. The skeleton for a GUI that applies to each
object consists of 2 parts: object creation, and functionality.

20
Feedback Control with Scilab and Arduino

The first is about appearance of the object such as size, location, font color, etc. We
design the GUI by populating all required objects onto the window, which can be
divided into sections. In Figure 1.15, the plot on the right consumes its own sub-
pane, which is a child of the main window, or parent. Each object is created by
uicontrol command. To adjust its appearance and location, desirable values are
assigned to the corresponding fields.
The second concerns what the object does when the user interacts with it. The
objects callback function takes care of this part. For example, when a button labeled
Plot is clicked, its callback function is invoked, which executes the plot command
for some data of interest.
We will create a simple GUI to communicate with Arduino in Chapter 2.

1.5 Conclusion
In this introductory chapter we discuss the basic features of Scilab and its simulation
engine Xcos. Instead of overwhelming the reader with too many details, only a few
essential topics are chosen. More advanced topics may be fulfilled later on in the
book where applicable. Our goal is allowing the learning process to progress
smoothly from the examples in this chapter to the more complex ones later on.
All examples in this book are guaranteed to work with Scilab 5.5.2.

21

Potrebbero piacerti anche