Intro Scilab
Intro Scilab
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].
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.
2
Feedback Control with Scilab and Arduino
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 =
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 =
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.
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
x =
2. +0.5i
ans =
2.
5
Chapter 1 Scilab Basics
--> imag(x)
ans =
0.5
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
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
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
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
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
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.
10
Feedback Control with Scilab and Arduino
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
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
// :
15
Chapter 1 Scilab Basics
17
Chapter 1 Scilab Basics
18
Feedback Control with Scilab and Arduino
Figure 1.13 pid_control2.zcos PID feedback model with multiplexed scope input
19
Chapter 1 Scilab Basics
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