Scilab
Scilab
E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Introducing an Open-Source
Alternative to Matlab
v1.0 / Scilab 5.3.2 (5.3.3)
Johnny Heikell
"It is a mistake often made in this country to measure things by the amount of money they
cost." Albert Einstein
About this
presentation
I compiled this presentation while familiarizing myself with
Scilab for basic engineering applications. The exercise taught
that a reason to the limited spread of Scilab is lack of good
tutorials in English, which makes learning Scilab a frustrating
experience for programming newbies. Its a pity because Scilab
deserves better recognition. Hopefully this presentation can be
of use to at least some Scilab aspirants.
The text no doubt has shortcomings and errors. I hope to come
up with an improved version in a not too distant future (with
Scilab 6). Please post comments & suggestions at:
Espoo in August 2011
Johnny Heikell
www.heikell.f
LinkedIn
The best Scilab tutorials are non-English. The following are the
ones that I have consulted most for this work:
Timo Mkels Scilab/Xcos tutorials (3 parts) in Finnish
<http://sites.
google.com/site/tjmakela/home>. Heavy on mathematical
formalism,
standard dull LaTeX typesetting, but the best one I know
Jean-Marie Zoggs Arbeiten mit Scilab und Scicos in German
<http://www.fhhtwchur.ch/uploads/media/Arbeiten_mit_Scilab_und_
Scicos_v1_01.pdf>. Its good and informal, and contains details
that
Mkel has omitted. Needs updating
Wolfgang Kubitzkis mixed tutorials in German that can be found
atTo copy from one is plagiarism, to copy from many is research. Unknown
<http://www.mst.fh-kl.de/~kubitzki/>. Quite good, a lot of
details, few
practical examples (scripts in separate .zip fles)
Why I did it
the way I did
it
As a grad student at KU in 1990-91, I needed to quickly learn
With that teaching I got started and was able to use MathCAD
for my MS thesis.
Lessons learned: Show examples and skip the academic trivia.
I am deeply grateful to Jim for his lesson. Well repeat it as
soon as Scilab is installed and opened.
Why PowerPoint?
Why simulate?
Contents
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
Introduction
A frst peek at Scilab
The Console & Editor
Examples, Set 1
Matrices, functions & ope
rators
Examples, Set 2
Graphics & plotting
Examples, Set 3
Converting Matlab fles
Subroutines
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
Flow control
Examples, Set 4
Doing math on Scilab
Examples, Set 5
Working with GUIs
File handling
Animation
Miscellaneous
Examples, Set 6
Adieu
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
1. Introduction
What is and why use Scilab?
Return to Contents
An interpreter
Libraries of functions (procedures, macros)
Interfaces for Fortran, Tcl/Tk, C, C++, Java, Modelica, and
LabVIEWbut not for Python and/or Ruby
Matlab 6.5 (R13) was not compatible with my new Windows Vista
laptop. MatWorks, Inc., recommended to buy a new version
I refused to pay another license fee for Matlab and went looking
for open-source alternatives:
Would I still select Scilab? Yes, I am impressed by Scilab and believe that the
competitors cause you gray hair as wellone way or another.
Scilab advantages
Scilab disadvantages
*) Scilab is not alone. The open-source community has a poor track record in
documentation because paperwork does not bring recognition.
Terminology:
function
The C programming language brought confusion with its
unrestricted use of the term function and this is repeated
in Scilab. The term refers to (at least):
Mathematical functions in general
Scilabs built-in functions
User defned functions (UDF)
Intro to problems
(1/3): crashes &
lockups
Processor loads of this
magnitude are normal
during computer startup.
However, this is the
situation after Scilab had
crashed and I had closed it.
WScilex.exe had another
of its lockups and required
to be closed with the Task
Manager (or by rebooting
the computer).
Intro to problems
(2/3): new releases*
With Scilab 5.2 came a problem that I did not experience with
version 5.1.1: Copy-pasting from Scilabs Editor to PowerPoint
frequently caused the latter to crash. The bug has been fxed
With Scilab 5.3.0 I found that the paths File/Open file in... and
File/Save file in... on the Editor were unresponsive
Some scripts that I originally wrote using Scilab 5.1.1 did not work
with Scilab 5.3.0, and GUIs on 5.3.2 are a real pain down there
Typically larger updates come with bugs and are quickly followed
by minor bug fx updates (a.k.a. patches). Scilab 5.3.1 emerged
within three months of 5.3.0. This is universal in the software
business
It is wise to keep an old Scilab version until you know that the
new release can be trusted (I was happy I had kept version 5.1.1
when GUIs on 5.3.1 & 5.3.2 gave me problems)
*) Various Scilab versions are mentioned. I have worked with Scilab 5.1.1 5.3.2. Scilab 5.3.3 came too late to be considered.
Intro to problems
(3/3): ATOMS and
nerds
Embedded information
Information on the
Web (1/2)
Information on the
Web (2/2)
YouTube has some video clips on Scilab, but nothing really valuable
Equalis <http://www.equalis.com>. By registering you gain free
access to the discussion forum
<http://usingscilab.blogspot.com/> used to be a very good blog but
is now terminally ill. Worth checking the material that is still there
Scilab India <http://scilab.in/> is basically a mirror of Scilab Wiki,
with added obsolete material and a less active discussion forum
Books
On updates &
literature
Scilab evolves rapidly and one frequently encounters
obsolete features. Functions are often declared obsolete,
although Scilab still may support them, and other functions
are removed altogether. There is obviously no collection of
obsolete/removed functions and their current equivalents (if
any).
The Scilab team is slow with information on major updates.
For instance, the GUI interface is said to have been
completely renewed with version 5.x, but so far the only
(poor) GUI description that I have seen is for version 4.x. Its
almost three years now...
Rapid development is a reason to why the limited literature
on Scilab is mostly obsolete, sometimes outright misleading.
I got a hands-on experience with all the changes that had to
be made to 5.1.1 scripts before they agreed to run on
version 5.3.x (and not all do)
Scilab learning
obstacles
Learning Scilab can be frustrating to a person with limited
previous programming experience. The biggest hurdles are:
*) Scilab is released under the French CeCILL license. The question is, is it
really a Free and Open-Source license that allows you to release a Scilab copy
under a new name, the way OpenOffice was turned into LibreOffice?
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
2. A first peek at
Scilab
What you face when trying to
get startedincluding Scilab
in 15 minutes
Return to Contents
Windows installation
(1/3)
1. Download Scilab
from www.scilab.org
(Windows on the top,
other OSs below)
Windows installation
(2/3)
Inside the
Downloads
fle
3. Scan the
downloaded fle for
viruses
4. Double-click on
the fle to install
Scilab, follow the
prompts
Windows installation
(3/3)
5. Scilab suggests
that it should install
all toolboxes
(modules). Go for it
unless you are really
short of memory
6. Accept Scilab
license terms (you
have no option so
why do they ask?).
Click Next as many
times as needed
7. Youre all set to
use Scilab (no need
to reboot the
computer)
Linux installation
This discussion is valid for
Ubuntu 10.04 LTS with the
GNOME desktop*
Click: Applications/Ubuntu
Software Center/Science &
Engineering and scroll down to
Scilab; then just Click Install
The Console
Click on Scilabs
shortcut icon to open
the Console (Command
Window in Matlab*):
Menu bar
Toolbar
Command prompt
If no shortcut icon has been
created: Click: Start\All
Programs\scilab\scilab
(do not select Scilab
Console)
*) The Console has other names as well: Workspace, Startup/Main Window, etc.
Folks:
Scilab in 15 minutes
(1/3): write a script
Recall how Jim taught me MathCAD in 15 minutes? Now well
repeat that lesson in Scilab. We do it by using the Editor
(SciNotes):
Step 1: On the Console,
Click the leftmost icon on
the toolbar. The Editor pops
up
Step 2: Defne whatever
variables your function
needs (row 1). Note
comment (// )
Step 3: Next, defne the
(sine) function in case (row
2)
Step 4: Finally, write the
plot command (row 3)
Scilab in 15 minutes
(2/3): save and plot
Step 5: Save the script
by Clicking on the Save
icon and name it e.g.
foo.sce
Step 6: Finish by running
(executing) the script by
a Click the Execute icon
(a second one came with
5.3.2)
Step 7: Up pops the
Graphics Window with
the a plot of the defned
equation
Did you have problems or get an
error message on the Console?
Dont worry, well return to
everything later. Jump to
Examples 1-1 & 1-2 if you are in
a hurry.
Scilab in 15 minutes
(3/3): discussion
This exercise showed the essentials of Scilab in
engineering applications:
The recipe for using Scilab is the one that Jim taught me:
First you declare the variables that are needed
Then you defne the function that you want to plot
And fnally, plug in the plot instruction
Change visual
appearance of the
Console
Scilab
Web
Scilab Demonstrations: Shows resources
demos with few comments (same
command as the cogwheel in the
toolbar). At least the GUI/Uicontrols 2
demo causes Scilab to crash
Change Current
Directory: It can also be
found under File in the
menu bar. You need it to
point out from which
directory (folder) Scilab
should search for a script
that you want to execute
(run)
Editor toolbar
New... Opens a
second tab for a new
script to be edited
(the same command
can be found under
File)
The Save icon looks like
the Dutch tricolor, but
youll get used to it. The
next one is Save as...
The Undo/Redo
arrows are quite
normal
The Paste icon is a
bit unusual
(French?)
Ready to go
Console (command window)
Your desktop
should now
look something
like the one
here. As we
have seen,
both the Editor
and the
Console are
needed since
when the
scripts
created on the
Editorare
executed
numeric
outputs is
Editor (SciNotes)
le
o
s
n
o
C
r
Edito
le
o
s
n
o
C
ser
w
o
r
B
Help
r
Edito
dow
n
i
W
s
c
i
h
p
Gra
Each
window
part has
an arrow
in the
upper
righthand
corner, by
which you
can
release it
from
docking
On scripts and
functions
Built-in functions
Below is a list of common math functions in Scilab. A full list of
built-in functions can be found under Help\Elementary
Functions, which also explains requirements on arguments
(there are both mandatory and optional arguments).
sin(), cos(), tan(), cotg()
Arc functions
Hyperbolic functions
sqrt(), exp()
sum()
Sum
min(), max()
abs(), sign()
real(f), imag(f)
i = -1
Imaginary unit
%pi
= 3.1415927.
Pi
%e
e = 2.7182818.
Napiers constant e
%eps
= 2.22 10-16
%inf
%nan
Not a Number
%s
Polynomial variable
%z
Polynomial variable
%t, %T
true
Boolean variable
%f, %F
false
Boolean variable
'
.'
Non-conjugate transpose
[] , [] '
()
+, * , .*
*) Both simple (') and double (") quotes are allowed to define character strings
\ , .\
^ or ** , .^
.*.
./. , .\.
|
&
Logical AND
Logical NOT
Computing
terminology: a brief
introduction
On handles
You will often see Scilabs Help Browser refer to a
handle, but Help does not provide a helpful explanation
of the term. Here is a brief account:
Check handles
with gcf()
f =
Handle of type "Figure" with properties:
========================================
children: "Axes
figure_position = [567,485]
figure_size = [628,592]
axes_size = [610,460]
auto_resize = "on
viewport = [0,0]
figure_name = "Graphic window number %d
figure_id = 0
info_message = "
color_map= matrix 32x3
pixmap = "off
pixel_drawing_mode = "copy
anti_aliasing = "off
immediate_drawing = "on
background = -2
visible = "on
rotation_style = "unary
event_handler = "
event_handler_enable = "off
user_data = []
tag = ""
foo
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Return to Contents
Console keyboard
shortcuts
Keyboard shortcuts
allow speedier
execution of
commands, but require
frequent use to stay
memorized
In the Help Browser,
Click: Console/console
for a list of keyboard
shortcuts
The simplest ones to
memorize are:
F1 = Open Help Browser
F2 = Clear Console
Simple calculations
Entering numbers
Computing precision
(1/2)
Look at the two examples to
the left. In both cases we are
computing 1-5*0.2, but in two
different ways
In the frst case the answer is
correct (0)
In the second case the answer
is 5.55*10-17, which quite
obviously is incorrect
5.551D-17
b =
-->b = 1 - .2 - .2 - .2
Computing precision
(2/2)
Here are two more cases where fnite
precision shows up. The answers should
be 0 (zero) and T (True) respectively (Note
that 1.225D-15, 1.225e-16, 1.225*10^-16
and 1.225*10-16 express the same thing)
Assume that the mentioned variable a is
part of a script with an if...then...else...end
structure (conditional branching will be
covered in Chapter 11). The result is that
alternative 1 is never executed because a is
never exactly zero
We must test a with some fnite bounds,
e.g.:
if abs (a ) < 1e- 6 then
......
F
foo
if a == 0 then
alternative 1
ans
else =
alternative
2
-->0.1
== 1.0
end
0.9
1.225D-16
Displaying graphics
-->x = linspace(-%pi,
^
|
-->a = 2; b = sqt(a)
Press up
arrow
Correct
1.4142136
b =
-->a = 2; b = sqrt(a)
Editing demo
-->s=.5; log(s^2-2*s*cos(%pi/5)+1)
ans =
- 0.8187489
-->s=.95; log(s^2-2*s*cos(%pi/5)+1)
ans =
- 1.006851
-->s=1; log(s^2-2*s*cos(%pi/5)+1)
ans =
- 0.9624237
Complex numbers
Vectorized functions
0.8414710
-->p=1+2+3+4+5+6+7+8+9+10+11+12+...
-->13+14+15+16+17+18+18+19+21+22+23+24+25
p =
323.
2.1032107
11.
6.
12.
7.
13.
8.
14.
9.
15
10
Polynomials
-->s=%s;
-->num = poly([0,-1,-2],'s')
num =
2 3
2s + 3s + s
-->den=poly([-.5,-1.5,-2.5,-3.5],'s')
den =
2 3 4
6.5625 + 22s + 21.5s + 8s + s
-->fr=num/den
fr =
2 3
2s + 3s + s
---------------------------------------2
3 4
6.5625 + 22s + 21.5s + 8s + s
Roots of polynomials
- 2.
- 1.
0
x =
-->x=roots(2*s+3*s^2+s^
- 3.5
- 2.5
-->s=%s;
-->s=%s;
-->sys=syslin('c',((1+2*s)*(1+3*s))/(s*(s*s+s+1)));
-->plzr(sys)
Gadgets (1/2):
calendar
Among Scilabs built-in
gadgets is a calendar. The
command
-->calendar(2013,6)
ans =
ans(1)
Jun 2013
calendar()
returns the calendar for the
present month, the
command
calendar(y,m)
returns the calendar for the
year and month in case
(shown for June 2013)
ans(2)
M
Tu
Th
Sat
Sun
ans(3)
0.
3.
10.
17.
24.
0.
0.
4.
11.
18.
25.
0.
0.
5.
12.
19.
26.
0.
0.
6.
13.
20.
27.
0.
0.
1.
7.
8.
14. 15.
21. 22.
28. 29.
0.
0.
2.
9.
16.
23.
30.
0.
Sorry,
I could not copy-paste an extract because
PowerPoint crashed repeatedly (it
happens to Bill Gates as well Often.)
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
4. Examples, Set 1
Demonstration of basic
Scilab programs
Return to Contents
// plot1.sce
//
//
//
//
x = [0:.1:10];
A = 0.5*x;
y = A.*sin(2*x);
plot(y)
/
/
/
/
Ex 1-1: change
directory
Ex 1-1: comments
(1/4), command details
Editor contents will
from now on be shown
on light green
background
// plot1.sce
//
//
//
//
x = [0:.1:10];
A = 0.5*x;
y = A.*sin(2*x);
plot(y)
/
/
/
/
Ex 1-1: comments
(2/3), the plot
The plot is very basic as it
has no title, axis labels, or
grid. Well return to them
in the next example
The abscissa scale may
seem strange, the
maximum value for x was
10 but the scale goes to
100. The fgure 100 is
actually the number of
calculations, since they
were made in steps of 0.1
up to 10. Try to change t to
x=[0:0.2:10]; and youll
see that the scale ends at
50 (the modifed script
must be saved before it
can be run)
Ex 1-1: comments
(3/4), clf
Assume that we make a
change to the script, e.g.
increase the frequency to
sin(5*s), save it, and
execute it immediately
after a previous run
As a result Scilab plots the
new graph on top of the
previous one. To avoid this
we must either
Close the Graphics Window
clf;
x = [0:.1:10];
A = 0.5*x;
y = A.*sin(5*x);
plot(y)
Ex 1-1: comments
(4/4), cleaning trash
Some programmers prefer
to safeguard against
different forms of old junk
that may interfere with the
execution of the script. To
do this, three commands
are added at the beginning
of the script:
// plot1.sce
//
//
//
//
/
/
/
/
// f-modulation1.sce
/
// Plots a sinusoidal function of the type
/
// s = A(t)(sin(wt+x(t)+phi)), where w =
angular /
// velocity, x(t) = frequency modulation, phi =
/
// phase shift, and A(t) = amplitude
/
clear, clc, clf;
f = 1;
// Frequency
w = 2*%pi*f;
phi = %pi/4;
// Initial phase shift
fn = (4*%pi)/w;
// End of plot
t = linspace(0,fn,1000);
A = 2*exp(-t);
s
= A.*sin(w*t
10*t^2 as
+ phi);
Note:
fin is+ used
the end of
plot2d(t,s,5)
Ex 1-2: plot
The plot looks as
expected
including the
initial phase shift
but it lacks a
grid, title, and
axis labels
plot2d() is a
more versatile
function than
plot(), which is
similar to the
plot function in
Matlab
// f-modulation2.sce
//
//
//
//
Ex 1-2:
printing
Ex 1-2: checking
// f-modulation3.sce
Ex 1-2: discussion
dt=getdate() returns
function lotto
dd-mm-yyyy
rand(seed,n) sets
//-----------------------------------------------------------------/
// The function draws 7 Lotto numbers [1,39] by frst /
the random gene// creating a seed using current date and time
/
rator seed to n
// (second, millisecond) information
/
//----------------------------------------------------------------/
dt(9) returns a
number between
dt=getdate();
// Pick current date
rand('seed',1000*dt(9)+dt(10));
// Initialize random generato
00 and 59, dt(10)
numbers=floor(1+39*rand(1,7));
// Draw Lotto row
returns
while(length(unique(numbers))<7) // If number repeats in row,
numbers=floor(1+39*rand(1,7)); // then drawn a new row
milliseconds 000
end
999
numbers=gsort(numbers); // Sort numbers in decreasing orde
The while...end
disp(numbers(7:-1:1));
// Display in increasing order
endfunction
construct will be
covered under the
discussion below
Why the hassle with the seed? Without it Scilab generates the same sequence for
each session. The 1000*t(9)+ dt(10) argument improves randomness.
3.
37.
39.
Ex 1-3: task 1,
discussion
// lotto2.sce
//-----------------------------------------------------------------------/
// The script asks for the number of Lotto draws that we /
// wish to do, using a separate dialog box. It then calls
/
// the local UDF lottodraw()) that generates a row of N
/
// random Lotto numbers in the range [1,39]. It sorts the /
// numbers into a vector by adding one (1) to the relevant /
// vector element for each corresponding hit. The result
/
// is plotted after the entered number of draws.
/
//-----------------------------------------------------------------------/
clear,clc,clf;
// (SUBROUTINE) function lottodraw():
//----------------------------------------------------// The function draws N Lotto numbers [1,39], with
// N being defned through the input argument in.
// It delivers the drawn row to the calling script
// command through the output argument out. The
// randomness of the drawn numbers is improved by
// frst creating a seed using current date and
// time (second, millisecond) information.
/
/
/
/
/
/
/
function out=lottodraw(in)
dt=getdate(); // Pick current date
rand('seed',1000*dt(9)+dt(10)); // Initialize random
generator
out = floor(1+39*rand(1,in));
// Draw Lotto row (out
variable)
while(length(unique(out))<in) // If number repeats in
row,
out = floor(1+39*rand(1,in)); // then a new row is drawn
end
endfunction
// (MAIN) Call subroutine, update histogram, plot:
//------------------------------------------------------------------M = evstr(x_dialog('Enter # of...
// Open dialog box
lotto draws ',''));
N = 7;
// Lotto numbers to draw
columns = zeros(1,39);
// Initiate collecting vector
for k = 1:M
numbers = lottodraw(N);
// Call to subroutine
columns(numbers)=columns(numbers)+1;
// Add 1 for drawn number
end
x = linspace(1,39,39);
// Define x axis
plot2d2(x,columns,style=2)
// Plot as step functions
xtitle('RESULT OF LOTTO DRAWS') // Add title & labels
xlabel('Lotto numbers [1,39]')
ylabel('Hits')
Ex 1-3: task 2,
execution & plot
The dialog box pops up when
executing the script. Enter the
wanted number of Lotto draws
and Click OK
Examples 1-1 1-3 were also intended to stress the fact that
we are forced to think matrix-wise when working with
Scilab. For instance, Scilab immediately generates an error
message if we attempt to do ordinary multiplication (*) when
a parameter is in matrix form and requires Dot multiplication
(.*) (Recall Example 1-1?)
Ex 1-3: comments
(3/3), rounding
functions
The rounding function floor() is
one of four rounding functions
in Scilab: round(), fix() (or int()),
floor(), and ceil()
fix() or
int()
floor()
rounds down
ceil()
rounds up
-->round(-2.7), round(2.7)
ans =
- 3.
ans =
3.
-->fix(-2.7), fix(2.7)
ans =
- 2.
ans =
2.
-->floor(-2.7), floor(2.7)
ans =
- 3.
ans =
2.
-->ceil(-2.7), ceil(2.7)
ans =
- 2.
ans =
3.
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
5. Matrices, functions
& operators
An overview of basic
matrix operations,
functions, and operators
Return to Contents
Introduction
31.
21.
11.
32.
22.
12.
33.
23.
13.
A =
-->A = [11 12 13; 21 22 23; 31 32
31.
21.
11.
32.
22.
12.
33.
23.
13.
0.
0.2
0.4
-->column=[0:0.2:1]'
column =
row =
0.
-->row=[0:0.2:1]
0.2
0.4
0.6
0.8
1.
0.6
0.8
3x2 matrix
of ones
2x3 zero
matrix
0.2312237
0.2164633
0.8833888
0.6525135
-->rand(4,4,'normal')
ans =
- 1.3772844
0.7915156
- 0.1728369
0.7629083
Basic matrix
calculations
Addition
8. 10. 12.
2. 4. 6.
C =
1.
1.518D-16
-->A
= [1 2 1.
3; 4 5 6]; B = A; C = A + B
3.795D-15
C =
-->A = [1 2 3; 4 5 6]; B = A'; C = A * B
Inverse matrix
2. - 1.
- 2.5
1.5
Note 1: Rules for matrix operations must
of course
be
observed!
Note 2: Scilab returns D, not e, for the Hexponent
(1.518D-16);
=
the exact value is 0 but here we have-->A
a case
= [2of
3; limited
4 5]; H = inv(A)
2. 13.
11. 8.
7. 12.
14. 1.
-->M
ans =
16. 5.
3. 10.
2. 11.
13. 8.
-->diag(M)
ans =
16.
10.
7.
1.
9. 4.
6. 15.
7. 14.
12. 1.
24.
15.
prod()
-->A=[1 2 3; 4 5 6; 7 8 9]
A =
1.
4.
7.
2.
5.
8.
3.
6.
9.
-->prod(A, 'r')
ans =
28.
80.
-->prod(A, 'c')
ans =
6.
120.
504.
-->prod(A)
ans =
362880.
162.
min(), max()
-->A=[3 0 1; 2 2 7; 5 9 4]
A =
3.
2.
5.
0.
2.
9.
1.
7.
4.
-->min(A)
ans =
0.
-->max(A)
ans =
9.
-->min(A, 'r')
ans =
-->max(A, 'c')
ans =
2.
3.
7.
9.
0.
1.
6.
max_val =
mean()
5.
size()
2.
4.
1.
4.
ans =
-->size(A)
ans =
-->A = [1 2 3 4; 5
-->size(v2)
6 7 8];
2.
1. 4.
ans =
-->size(v1)
n =
3.
length()
3.
ans =
-->length([1.23;
456,7890; 9])
5. 4.
11. 6.
ans =
-->length(['Hello world' 'SCILAB';
find(condition)
-->X = [9 1 8; 2 7 3; 6 3 5];
-->find(X==3)
ans =
-->find(X<5)
ans =
2.
6.
4.
6.
8.
8.
-->find(X=3)
ans =
1.
-->find(X~=3)
ans =
1.
2.
3.
4.
5.
7.
9.
gsort()
4. - 2. 2.
0. - 3. 3.
5. 0. - 5.
-->s_matr = gsort(matr)
s_matr =
5.
4.
3.
2. 0. - 3.
1. - 1. - 4.
0. - 2. - 5.
testmatrix()
-->testmatrix('magi',4)
ans =
16.
5.
9.
4.
2.
11.
7.
14.
3.
10.
6.
15.
13.
8.
12.
1.
-->testmatrix('magi',5)
ans =
17.
23.
4.
10.
11.
24. 1.
5. 7.
6. 13.
12. 19.
18. 25.
8. 15.
14. 16.
20. 22.
21. 3.
2.
9.
0.
delete
13.
8.
12.
1.
-->m(2,:) = []
m =
16. 3. 13.
9.
6. 12.
4. 15. 1.
delete
m =
16.
9.
4.
3.
6.
15.
13.
12.
1.
-->m(2,:)=[0 0 0]
m =
16. 3. 13.
0. 0.
0.
4. 15. 1.
-->m(:,3)=[1 1 1]'
m =
16. 3.
1.
0. 0.
1.
4. 15. 1.
Addressing matrix
elements by linear
indexing
9.
7.
4.
-->M(14)
14.
5. 11.
16. 2.
6.
12.
15.
10.
3.
1.
8.
13.
8. =
M
-->M=testmatrix('magi',4)
ans
=
1.
6.
0.
14.
15.
Concatenation (1/2)
1.
2.
3.
C =
4. 5.
6.
4.
5.
6.
B =
-->A = [1 2 3]; B = [4 5 6], C = [
3. 6.
2. 5.
1. 4.
Concatenation (2/2)
22 23
32 33
E =
11.
21.
12.
22.
13.
23.
14.
24.
31.
41.
32.
42.
33.
43.
34.
44.
Operators (1/4):
the Colon Operator (:)
1.
2.
ans =
-->1:8
14.
3.
4.
5.
6.
7.
Operators (2/4):
more examples with (:)
7. 6.
11. 10.
15.
6.
4.
9.
14. 15. 1.
7. 6. 12.
Operators (3/4):
the $ Operator
-->M = testmatrix('magi',4)
M =
16. 2.
5. 11.
9. 7.
4. 14.
-->M($)
ans =
1.
-->M(1:$-1,$)
ans =
13.
8.
12.
9.
8.
7.
6.
5.
4.
3.
3. 13.
10. 8.
6. 12.
15. 1.
- 0.3846154
Duplicating an mx1
vector to an mxn
matrix
-->m = (2:2:6)';
-->n = 4;
-->A = m(:, ones(n,1))
A =
2.
4.
6.
2.
4.
6.
2.
4.
6.
2.
4.
6.
6 2
= 63 25 = 8 , it is therefore nonsingular
5 3
6 3
= 61 32 = 0 , meaning that it is singular
2 1
in action
LIFO
This is
in
action action', 'LIFO', 'This
-->disp('in
FIFO
is')
This is
-->mprintf(\nThis is \nFIFO
clear,clc;
write(%io(2),'This is an interactive demo.');
write(%io(2),'You will be asked to give the base length')
write(%io(2),'and height of a triangle. Scilab then');
write(%io(2),'computes the area.');
write(%io(2),' ');
// Empty row
b = input('Give length of triangle base: ');
h = input('Give height of triangle: ');
write(%io(2),' ');
// Empty row
disp(['triangle_area = ' string(b*h/2)])
This is an interactive demo.
Strings(5/6): other
useful commands
Some of the functions discussed earlier in this chapter can
have string matrices (below S) as arguments:
prod(), min(),
max(), mean()
size(S)
length(S)
Strings(6/6): demo
with find() & gsort()
Symbolic computing
!
!
v+w !
-->tsc = trianfml(sc)
tsc =
!z
!
!0
v+w
!
!
z*y-x*(v+w) !
Arrays: general
addition
subtraction
.*
multiplication
./
right division
.\
left division
.^
power
Arrays: building a
table
-->n = (0:9)';
-->powers = [n n.^2 2.^n]
powers =
0.
1.
2.
3.
4.
5.
6.
7.
8.
9.
0.
1.
4.
9.
16.
25.
36.
49.
64.
81.
1.
2.
4.
8.
16.
32.
64.
128.
256.
512.
-->p = powers(4:5,1:2)
p =
3.
4.
9.
16.
-->q = powers(3,2)*powers(4,3)
q =
32.
Element-by-element
multiplication and
division
Element-by-element
multiplication with the use of
the Dot Operator can also be
performed on two-dimensional
matrices
-->D = A*B
D =
-->E = A./B
E =
19.
43.
22.
50.
0.2
0.3333333
0.4285714 0.5
-->A = [1 2; 3 4]
A =
1.
3.
2.
4.
-->B = [5 6; 2 -3]
B =
5. 6.
2. - 3.
-->A.\B
ans =
5.
3.
0.6666667 - 0.75
-->A./B
ans =
0.2
0.3333333
1.5 - 1.3333333
-->B = 1./A
B =
0.0333333
0.0666667
0.1
0.1333333
-->C = (1)./A
C =
1.
0.5
0.3333333
-->D = 2.*A
D =
2.
4.
6.
8.
-->E = (2).*A
E =
2.
4.
6.
8.
0.25
-->modulo(3,2)
1.
ans =
1.
0.
-->xp=getdate();
-->xp(1),xp(2),xp(3),xp(4),xp(5),xp(6),xp(7)
ans =
2011.
ans =
3.
ans =
12.
ans =
83.
ans =
5.
ans =
24.
ans =
11.
A = [0 0 1 1;
0 1 1 1;
ans20 02=12 1;
2;
-->unique(M)
2 0 1 1;
0 0 1 1 ];
5. 2. rows
1. are:'])
5.
disp(['Unique
disp(unique(A,'r'))
round() was
up in Ex. 13
0 and 3
are absent
1.
2.
4.
5.
4.
M =
2.
0.
0.
2.
1.
2.
1.
2.
// rand_demo1.sce
clear,clc,clf;
u_fun=rand(1,2000);
subplot(121);
histplot([-4:0.1:4],u_fun,2,'073',' ',[-4,0,4,1.2],
[3,3,2,3]);
xtitle('Uniform')
G_fun=rand(1,2000,'n');
subplot(122);
histplot([-4:0.1:4],G_fun,2,'073',' ',[-4,0,4,1.2],
[3,3,2,3]);
xtitle('Gaussian')
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
6. Examples, Set 2
Adds to what we have
learned so far
Return to Contents
1
-2
-1
2
6
3
1
4
3
b =
1
-2
1
-1
= 2
2
algebra1.sce has to be
run from the Console
since the script
contains no disp()
command
-->exec algebra1.sce
-->// algebra1.sce
/
-->//
-->// Find the solution x in /
-->// Ax = b
/
-->//
-->A = [1 2 -1; -2 -6 4; -1 -3 3];
-->b = [1; -2; 1];
-->x = A\b
x =
- 1.
2.
2.
A = [1 2 -1; -2 -6 4; -1 -3 3];
b = [1; -2; 1];
x = A\b
// algebra1_check.sce
/
// Make sure that b - Ax = 0 /
x =
residual = b - A*x
0.
Problem: The
determinant of the
coefficient matrix A
must be non-zero
- 2.
ans =
-->det(A)
Ex 2-2: mesh-currents
Instead, superposition
of currents with meshcurrent equations can
be used. Along the
current loops the
diagonal term
resistances are:
R11 = 10
R22 = 12
R33 = 18
The common (offdiagonal) resistances
are:
R12 = -8 , R13 = -2 , R21 = -8 , R23 = -4 , R31 =
-2 , R32 = -4 (You should be able to figure out the
logic)
Ex 2-2: solution
These values allow us to write
the following mesh-current
equations:
10 -8
-2
i_1
-8
12 -4
i_2 =
-2
-4
18
i_3
We execute the script in the
Console and compute manually
the current values that we are
looking for:
i1
i2
i3
i4
=
=
=
=
// circuit1.sce
5
3
4
Ex 2-2: comments
Example 2-3:
continuous-time statespace model
where
A = system matrix
B = input matrix
C = output matrix
D = feedforward matrix
x = state vector
x= dx/dt
u = input vector
y = output vector
0
-1
C =
1
0.5
0
B =
D =
Ex 2-3: script
// state_space.sce
Ex 2-3: plots
State-space
External description
Internal description
Input/Output descriptions
State descriptions
Laplace transform
Matrix
In common are block diagrams and their manipulations, poles and zer
//
//
//
//
String as input()
argument
clear,clc;
time = input("Give time in seconds: ");
if time < 0
// Check if time >= 0
disp("ERROR, negative number")
// Display error
message
abort
// and abort
execution
else
minut = floor(time/60);
// Convert to
minutes
seconds = modulo(time,60);
// Remaining
seconds
hours = floor(minut/60);
// Convert to hours
minutes = modulo(minut,60);
// Remaining
minutes
disp(string(hours)+" hour(s) "...
// Display answer
+string(minutes)+" minute(s)
+string(seconds)+" second(s) ")
end
The if...else...end
construct will be
discussed in
Chapter 11
Note interplay
between floor() and
modulo()
Strings as disp()
arguments
Ex 2-4: string
functions, execution &
In the script, the initial cleaning
comments
Below is the result
command is clear,clc;. If clf was
of three different
runs
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
7. Graphics &
plotting
2D & 3D plots, subplots &
other types of plots; editing
plots
Return to Contents
getcolor()
grayplot()
errbar()
plot3d()
fplot3d1()
Axes Editor
The most useful
editing objects
are Axes() and
Polyline(). Here
the Axes window
is open
There are seven
object properties
that can be
played with, the
one for the xaxis is shown
-->plot2d(t,[sin(t),cos(t)])
-->t=(-2*%pi:0.01:2*%pi)';
Graphics Window
commands
Windows-related clear/
delete commands are e.g.:
clf()
xdel()
delete()
obsolete are:
xclear()
xselect()
xbasc()
(Removed)
// multiple_plot.sce
// Demonstrates one alternative offered /
// by the plot2d() function
/
clear,clc,clf;
x = [0:0.01:2*%pi]';
plot2d(x,[sin(x) sin(2^x)
sin(3*x)],rect=[0,0,6,1])
legend('sin(x)','sin(2^x)','sin(3*x)')
plot2d(): syntax
Note: plot2d() h
as
also a slightly
different old sy
ntax
// x axis definition
// Function 1
// Function 2
style1 = 5;
// style for sin
strf1 = '174';
// strf
rect = [0,-1.2,2*%pi,1.2];
// rect
nax = [4,%pi,4,7];
// nax
plot2d(x,y1,style1,strf1,' ',rect,nax)
style2 = -9;
// style for cos
strf2 = 000;
// No axes
changes
leg = sin@cos;
// Legend
definition
plot2d(x,y2,style2,strf2,leg)
We have several times come across number codes for graph colors
(style, the number after the x and y arguments in plot2d())
Color codes are those that can be found with the getcolor()
command on the Console. The most important ones are 1=black,
2=blue (9=dark blue), 3=green (13=dark green), 5=red, 8=white,
and 25=brown
On the previous slide we saw that the code -9 creates circles. Plug
in getmark() on the Console to see the whole list, including codes
for mark sizes that you can use with handle commands. There are
in all 15 of these marks (always black):
0
-1
-2
-3
-4
-5
-6
-7
-8
-9
10
11
12
13
14
fplot2d()
x = linspace(-10,10,100)
f = Scilabs in-built sinc function
style=5 is an optional argument
-->fplot2d(linspace(10,10,100),sinc,style=5)
opt arg
// plot()_demo.sce
// Demonstration of plot() syntax /
clf();
t=0:0.1:2*%pi;
plot(t,sin(t),'o',..
// Plot with 'o'
t,cos(t),'x',..
// Plot with 'x'
t,abs(sin(t+%pi/4)),'<') // Plot with
'<
Cross
--
Dashed line
'square' or 's'
Square
Dotted line
'diamond' or 'd'
Diamond
-.
Dash-dotted line
Upward-pointing triangle
Plus sign
Downward-pointing triangle
Circle
>
Right-pointing triangle
Asterisk
<
Left-pointing triangle
Point
'pentagram'
Five-armed star
3D graphs: plot3d()
3D graphs: plot3d(),
script & plot for 3D
sinc()
Pay
attention to [X,Y] = ndgrid(x,y)
// sinc3D.sce
3D graphs: surf(),
task & script
// surf_ex1.sce
// Plot the function
/
// z=(2x^2 - y^2)exp(-x^2 - 0.5y^2)
/
// for -2<x<2, -3<y<3, where <
indicates /
// "less than or equal to"
/
clear,clc,clf;
x=linspace(-2,2,30); // Linear
spacing
y=linspace(-3,3,30);
[X,Y]=meshgrid(x,y); // Surface
mesh
Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2);
surf(X,Y,Z)
// Plot 3D
Contour plots:
contour()
// contour.sce
// Plot the 2D height curves for the
/
// function
/
// z=(2x^2 - y^2)exp(-x^2 - 0.5y^2)
/
// for -2<x<2, -3<y<3, where <
indicates /
// "less than or equal to"
/
clear,clc,clf;
x=linspace(-2,2,30);
y=linspace(-3,3,30);
[X,Y]=meshgrid(x,y);
Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2);
// vector_feld.sce
// Plot the 2D vector felds for the
function /
// z=(2x^2 - y^2)exp(-x^2 - 0.5y^2)
/
// for -2<x<2, -3<y<3, where <
indicates /
// "less than or equal to"
/
clear,clc,clf;
x=linspace(-2,2,10);
y=linspace(-3,3,10);
[X,Y]=meshgrid(x,y);
Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2);
champ(x,y,X,Y)
Vector felds are not very informative per se, but the situation
improves when they are fused with contours
In the previous case, just insert the champ() and contour()
commands into the same script and you get them in one plot:
// contour-vector.sce
// Plot the combined contour and vector
/
// felds for the function
/
// z=(2x^2 - y^2)exp(-x^2 - 0.5y^2),
/
// for -2<=x<=2, -3<=y<=3
/
clf;
x=linspace(-2,2,15);
y=linspace(-3,3,15);
[X,Y]=meshgrid(x,y);
Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2);
Cutting a 3D surface
We can see the outline of the 3D surface z = (2*x2 y2)exp(-x2 0.5*y2) at a certain plane by defning the plane in case
(below y = -1) and by returning to 2D plotting:
// cutting.sce
// Cut the the function
/
// z=(2*x^2 - y^2)exp(-x^2 - 0.5*y^2)
/
// along the plane y = -1
/
clf;
x=linspace(-2,2,50);
y=linspace(-1,-1,0);
[X,Y]=meshgrid(x,y);
Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2);
plot2d(X,Z,5)
// plot3d-contour.sce
//
//
//
//
clear,clc,clf;
x=linspace(-2,2,30);
y=linspace(-3,3,30);
[X,Y]=meshgrid(x,y);
Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2); // Same as
before
contour(x,y,Z,10,flag=[0,0,0]);
// First flag[]
argument
plot3d(x,y,Z,theta=60,alpha=80); // Turn 60 and 80
deg
subplot()
p=1
p=2
p=3
p=4
clear,clc,clf;
x=linspace(-2,2,30);
y=linspace(-3,3,30);
[X,Y]=meshgrid(x,y);
Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2);
subplot(221)
surf(X,Y,Z)
subplot(222)
contour(x,y,Z,10)
x=linspace(-2,2,10);
y=linspace(-3,3,10);
[X,Y]=meshgrid(x,y);
Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2);
subplot(223)
champ(x,y,X,Y)
x=linspace(-2,2,50);
y=linspace(-1,1,0);
[X,Y]=meshgrid(x,y);
Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2);
subplot(224)
plot2d(X,Z,5)
There is
another
function for
subplots:
xsetech().
Check with
Help for
details
plot2d2(), plot2d3(),
plot2d4(): demo, script
// plot2dx.sce
plot2d2(), plot2d3(),
plot2d4(): demo, plot
Note: You
can still see
the
obsolete
plot2d1() in
manuals.
plot2d()
should be
used
instead (In
contrast,
plot3d1() is
not
declared
obsolete)
Histograms: functions
to create them with
Histograms: demo,
script
subplot(223)
hist3d(5*rand(8,4)) // 3D histogram
subplot(224)
z=10*rand(3,4);
x=[1 3 5 6];
y=[1 2 7 11 20];
hist3d(list(z,x,y))
vectors
Histograms: demo,
plot
// multiple_plots2.sce
//
//
//
//
clear,clc,clf;
x1 = linspace(0,1,61);
x2 = linspace(0,1,31);
x3 = linspace(0.1,0.9,12);
y1 = x1.*(1-x1).*cos(2*%pi*x1);
// First graph
y2 = x2.*(1-x2);
// Second graph
y3 = x3.*(1-x3) + 0.1*(rand(x3)-0.5); // Third, as y2 with
disturbance
ymin = min([y1,y2,y3]);
// Select minimum to define frame
bottom
ymax = max([y1,y2,y3]); // Select maximum to define frame
top
dy = (ymax - ymin)*0.1;
// Border for min/max
rect = [0,ymin - dy,1,ymax+dy];
// Frame limits, start at 0
plot2d(x1,y1,5,"011"," ",rect)
definitions
y3
y2
y1
Rotation surfaces
// rotation_surface.sce
The
rotation
surface is
created by
multiplyin
g the
original
function,
which is
redefned
as
2+sin(T),
by
.*sin(PHI)
and
.*cos(PHI)
Logarithmic scale:
task & script
G(s) =
100
(s-10)(s-90)
// log_plot.sce
//
//
//
//
clear,clc,clf;
w = logspace(-1,3,100);
// Define log scale for w
s = %i*w;
// Define imaginary s
G = 100../((s-10).*(s-90)); // Define G(s)
y = 20*log10(abs(G));
// Define dB scale for y
plot2d(w,y,5,logflag='ln') // Plot y=f(w)
xtitle("Bode plot for G(s)=100/((s-10)(s-90))","w,...
log scale","y, dB scale")
xgrid()
// Add grid
Logarithmic scale:
the plot
The graph has been
edited after plotting
We have not before
mentioned the
argument logflag ln in
plot2d(). Change ln to
nn (ll is not possible
here) and see how the
plot changes
(n=normal,
l=logarithmic)
Note: Scilab has a
special function for
Bode plots, bode(). See
Example 3-1
Polar coordinates
//cardioid.sce
Exporting plots
export to PNG
export to PDF
export to SVG
export to EPS
export to Postscript
export to EMF (Windows)
xs2fig()
export to FIG
xs2gif()
export to GIF
xs2jpg()
export to JPG
xs2bmp() export to BMP
xs2ppm() export to PPM
Handles (1/12):
introduction*
Handles (2/12):
introduction*
Figure
Axes
y_label
z_label
title
t = a.title
compound
etc.
Editors Object
Browser that we
have used to
edit plots
legend
polyline
Lessons learned:
1) You have to be systematic when working with handles
2) The existing literature is not always correct. For instance,
the
method suggested by Steer for changing axes ticks &
marks simply
children: "Compound
parent: Figure
=================================
A check with gce() reveals
Handle
of type
"Axes" with
properties:
that
Compound
in turn
has a child, Polyline. This
the hierarchy
ans matches
=
that we have seen on the
Figure Editor
user_data = []
// handles_demo1.sce
// Basic script to demonstrate handles /
clear,clc,clf;
x = linspace(0, 4*%pi, 100);
plot2d(x, 0.5*cos(x))
f=gcf(); // Get Figure (window) handle
f.fgure_size = [500,400]; // Adjust window size
f.background = 12;
// Add background color
f.fgure_name= "cosine"; // Name window
a=gca();
// Get Axes handle
a.background = 9; // Change background
c=a.children;
// Get compound handle
p1=c.children; // Get polyline (plot) handle
p1.foreground = 8; // Change line color
p1.line_style = 7;
// Change line style
p1.thickness = 3;
// Line thickness
xtitle('COSINE PLOT',...
'X-axis','Y-axis');
t=a.title;
t.font_style = 5;
t.font_size = 3;
xL=a.x_label;
xL.font_style = 5;
xL.font_size = 2;
yL=a.y_label;
yL.font_style = 5;
yL.font_size = 2;
Handles (10/12):
demo, step 5
Add grid
Change x-axis ticks &
marks
Change y-axis ticks &
marks
Final plot:
xgrid(5);
// Add grid
Handles (11/12):
comments (1/2)
plot();
legend(alpha, beta);
a=gca();
a.children(1).foreground=5;
!--error 15
Submatrix incorrectly defined.
at line
6 of function %h_get called by :
at line
16 of function generic_i_h called by :
at line
2 of function %s_i_h called by :
children(1).foreground = 5; // Sum pattern re
at line
68 of exec file called by :
opulse_a-pattern.sce', -1
Handles (12/12):
comments (2/2)
!--error 999
This object has no auto_clear property.
at line
4 of function generic_i_h called by :
at line
Polylines (1/3):
xpoly(), script
// xpoly.sce
//
//
//
//
clear,clc,clf;
x = sin(2*%pi*(0:5)/6);
y = cos(2*%pi*(0:5)/6);
xpoly(x,y,'lines',1);
// Define hexagon
// - "
// Draw polygone
e=gca();
// Get Axes handle
e.parent.background =...
// Get Figure handle
color('grey');
// & set background
e.box='on';
// Switch frame on
e.foreground=5;
// Red frame color
e.data_bounds=[-2,-2;2,2]; // Frame size
e.children.foreground = 2; // Blue graph color
Polylines (2/3):
xpoly(), plot &
discussion
And this is the polygon
The unedited hexagon
that we have created:
It is left open if we do a
small change to the x/y
arguments:
x = sin(2*%pi*(0:5)/6);
y = cos(2*%pi*(0:5)/6);
plot2d(x,y,strf='011',rect=[-2,-2,2,2])
Polylines (3/3):
xpoly(), lessons
learned
Programming pitfalls:
dont forget clf;
// ptifalls_1.sce
// Clear commands /
Chang
e and
rerun
K = 100; a = 0; b = 0;
x = zeros(1,K); y =
zeros(1,K);
for k = 1:K
x(k) = a+k;
y(k) = b+k^(0.5);
end
plot2d3(x,y,style=-1)
// ptifalls_1.sce
// Clear commands /
K = 10; a = 0; b = 0;
x = zeros(1,K); y =
zeros(1,K);
for k = 1:K
x(k) = a+k;
y(k) = b-k^(0.5);
end
plot2d3(x,y,style=-1)
Plots are
superposed
without the
clf
command
What to do with
xset()?
1. Initial
script with
xset()
x=-1:0.1:2.6
plot2d(x,sin(2*x),5,rect=[-2,-2,3.6,2])
xset("color",2)
2. Modifed
script with Axes
handle
command
x=-1:0.1:2.6
plot2d(x,sin(2*x),5,rect=[-2,-2,3.6,2])
a=gca();
a.foreground=2
x=-1:0.1:2.6
plot2d(x,sin(2*x),5,rect=[-2,-2,3.6,2])
a=gca();
Modifed
set(a,"foreground",2)
3.
script with set()
and handle
argument
black
h.background = 1
xset(color,2)
blue fll
h.foreground = 2
xset(thickness,3)
thickness
line
h.thickness = 3
h.foreground = 5
xset(color,5)
red border
But frankly, it can be a pain and you want to throw the
computer out the window. If so, check if the gca() handle has
any children at all...
plot2d(x1,y1,style=5) // Function
!--error 999 plot2d:
first and second arguments have incompatible dimensions.
at line
16 of exec file called by :
exec("H:/Dr.EW/Writings/Scilab examples/derviative_2.sce");
while executing a callback
clc();
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
8. Examples, Set 3
On plotting, handles, control
engineering, and user defned
functions
Return to Contents
Example 2-3 and the log scale demo were typical control
engineering tasks. Recall also the pages on polynomials in
Chapter 3
Here well look at examples with Bode and Nyquist plots,
Nichols chart (Blacks diagram), and an Evans root locus plot
The frst cases use the second-order transfer functions
G2(s) =
s2 + 20s + 100
*
2
s + 6s + 100
s2 + 3s + 220
s2 + 25s + 225
G4(s) = 352 *
5+s
2000s2 + 200s3 + 25s4 + s5
Ex 3-1:
script
// control_eng.sce
// Plot Bode, Nyquist, Nichols & Black's, /
// and Evans for defned equations
/
clear,clc,clf;
// Definition of systems:
//------------------------------s = poly(0,'s'); // Polynomial seed
Gain1 = syslin('c',(s^2+20*s+100)/(s^2+6*s+100));
Gain2 = Gain1*syslin('c',(s^2+3*s+220)/
(s^2+25*s+225));
Gain3 = poly(-5,'s')/poly([0,0,2000,200,25,1],'s','c');
Gain4 = syslin('c',352*Gain3);
// Bode plot:
//--------------subplot(221)
gainplot([Gain2;Gain1],0.01,100) // Magnitude plot
// Nyquist plot:
//------------------subplot(222)
nyquist([Gain2;Gain1]) // Plot with Re and Im axes
// Nichols chart (Black's diagram + iso-plots):
//------------------------------------------------------------subplot(223)
black([Gain2;Gain1],0.01,100,[Gain2';Gain1'])
chart([-8 -6 -4],[20 50 80],list(1,0,5))
// Evans root locus:
//------------------------subplot(224)
evans(Gain4,100) // Evans root locus for sys4
Ex 3-1: plot
The plot has not
been edited,
everything
shown is the
result of the
script. Note the
red iso-curves
on the BodeNichols subplot
The next slide
looks at how
alternative Bode
plot commands
operate
Ex 3-1: alternative
Bode plot functions
// bode_comparison.sce
// Compare the how the bode() and gainplot() /
// functions operate in Example 7
/
clear,clc,clf;
s = poly(0,'s'); // Polynomial seed
Gain1 = syslin('c',(s^2+20*s+100)/(s^2+6*s+100));
Gain2 = Gain1*syslin('c',(s^2+3*s+220)/
(s^2+25*s+225));
// Plot with the bode() function:
//-----------------------------------------subplot(121)
bode([Gain2;Gain1],0.01,100)
legend(Gain1',Gain2')
xtitle('PLOTTED WITH bode()')
// Plot with the gainplot() function:
//----------------------------------------------subplot(122)
gainplot([Gain2;Gain1],0.01,100)
legend(Gain1',Gain2')
xtitle('PLOTTED WITH gainplot()')
This example
demonstrates the bode()
and gainplot() functions
when operating on the
earlier Gain1 and Gain2
expressions. bode() plots
also the phase
Ex 3-1: comments
The script was modifed after being copied from the Scilab
Group Users Manual and pasted into Editor. When copypasting, Editor tends to interpret citation marks (c,s, etc.)
wrongly and they have to be corrected manually
Scilab is strict with the arguments for polynomial expressions.
If, for instance, the c is left out from the expression
poly([0,0,2000,200,25,1],s,c), it will be translated into
10000000s2 - 10455000s3 + 455225s4 - 2226s5 + s6. Be careful!
There is an advantage in using self-documenting expressions,
here exemplifed by naming the polynomials Gain1, Gain2, etc.
The separate Bode plot demo showed that the bode() function
has an advantage in providing also the phase of the system of
interest
The difference between Blacks diagram and Nichols chart will
be demonstrated in Example 3-2
// black_nichols.sce
// Demonstration of black() and /
// chart() functions
/
clear,clc,clf;
s = %s;
Gain = (2+3*s+s^2)/(1+3*s+2.5*s^2+s^3);
system = syslin('c',Gain);
black(system,.01,100) // Plot Black's
diagram
chart([-8,-2,.5,3,6,12],
[5,25,60,120],list(1,1,2,5))
// chart() adds isographs
Ex 3-2: plots
black(sl,.01,100)
black(sl,.01,100)
chart ([-8,-2,.5,3,6,12],[5,25,60,120],list(1,1,2,5))
Example 3-3: an RC
circuit
G=
uout
=
uin
1
1 + i2 f RC
Ex 3-3: script
The logspace(1,6,60)
command means
starting point 101, end
point 106, in 60 steps
and logarithmic scale
Trigonometric phase
defnition and
conversion to degrees
The logflag = ln
argument defnes a
logarithmic x-scale and
linear (normal) y-scale
Different styles and
xgrid() arguments have
been used to
demonstrate their
effect
// bode_RC.sce
// Bode diagram for an RC circuit /
// (frst-order low-pass flter)
/
clear,clc,clf;
R = 1e+3;
// Resistance in ohm
C = 1e-7;
// Capacitance in farad
freq = logspace(1,6,60); // Frequency range,
logarithmic
G = 1 ./ (1 + %i*2*%pi*freq*R*C); // Transfer function
G_dB = 20*log10(abs(G));
// Logarithmic
scale
phase = ((atan(imag(G),real(G)))/(%pi))*180; // Phase
subplot(211);
// Amplitude plot
plot2d(freq,G_dB,logflag='ln',style=5)
xgrid(2)
// Blue grid
xtitle('Amplitude','Frequency (Hz)','Gain (dB)')
subplot(212)
// Phase plot
plot2d(freq,phase,logflag='ln',style=2)
xgrid(3)
// Green grid
xtitle('Phase','Frequency (Hz)','Phase (deg)')
Ex 3-3: plot
Note that the xaxis label is
missing for the
phase plot,
although it was
specifed.
Scilab does not
repeat it since
it is the same
as the top one.
Change the
subplot
declarations to
(121) and (122)
and the x-axis
label is given
for both parts
(n-1)dsin
Radiating
elements
Amplitude
weights
Phase
shifters
ont
1
d
wN
N
......
(For a discussion on
antenna arrays, see
Brookner, E. (ed): Practical
Phased Array Antenna
Systems, Artech House,
1991)
Pha
......
wn
w3
w2
w1
En
| AF | =
sin [ N ( d ) sin ]
sin [ ( d ) sin ]
Scan angle
| AF | =
d
sin [ ( ) (sin - sin o)]
Scan angle
Ex 3-4:
script
This script is for the
previous expression
for AF, but normalized
(divided by N) to keep
the main beam value
at unity. The phase
functions have been
defned separately in
order to shorten the
expression for
AF_norm
The array factor is
plotted both in linear
and polar presentation
// array_factor.sce
//
//
//
//
---------------------------------------------------------------------------------/
Plots the array factor of a linear antenna array with N elemnts,
spaced at d wavelengths, and main beam scanned at +60 degr
---------------------------------------------------------------------------------/
clear,clc,clf;
// Variables:
N = 10;
// Number of radiating elements
d1 = 0.45;
// Element spacing in wavelengths
d2 = 0.55;
// Ditto
theta = [-%pi/2:0.01:%pi/2]'; // Half space, +/-90 deg
theta_z = %pi/3;
// Scan angle
// Plot functions:
subplot(211
// Linear plot (d=0.45,0.55)
plot2d(theta,[AF_norm1,AF_norm2], style=[2,5],...
leg="d = 0.55@d = 0.45")
xtitle("ANTENNA ARRAY FACTOR, N = 10, Beam angle = 60 deg",.
"Theta (radians)","Normalized amplitude")
subplot(212)
// Polar diagram (d=0.55)
polarplot(theta,AF_norm2, style=5)
xtitle('POLAR DIAGRAM FOR d = 0.55:')
Ex 3-4: plot
Grating lobe
Main lobe
Main lobe
Grating lobe
Main lobe
Grating lobe
Example 3-5:
3D sinc
// sinc_colormap.sce
// Define and plot 3D sic funtion, graphic /
// adjust properties with handles /
clear,clc,clf;
x=linspace(-10,10,50); // Linear space of x
y=x; // Ditto for y
// **** SUBROUTINE sincf(): **** /
//---------------------------------------------function [z]=sincf(x, y)
r=sqrt(x.^2+y.^2)+%eps; // Auxiliary computation
z=sin(r)./r;
// Amplitude
endfunction
Ex 3-6: Lissajous
figures, script 1
//
//
//
//
handles_demo2-1.sce
Two Lissajous fgures, sin(t) & cos(3t) and
/
sin(1.5t) & 0.5*cos(1.5t), with plot defnitions /
given by arguments of the plot2d() function
/
clear,clc,clf;
// Plot Lissajous figures:
//------------------------------t=linspace(0,6,100)';
sines = [sin(t) sin(1.5*t)];
cosines = [cos(3*t) 0.5*cos(1.5*t)];
plot2d(sines, cosines, [2,5], ...
leg='sin(t), cos(3t)@sin(1.5t), 0.5*cos(1.5t)',...
nax=[1,9,1,9], rect=[-1.1,-1.1,1.1,1.1])
Ex 3-6: Lissajous
figures, plot 1
The fgure defned by sin(t),
cos(3t) has not quite
fnished a full loop (its
reach is defned by the
argument 6 in linspace())
The second fgure,
sin(1.5t), 0.5*cos(1.5t), is
already on its second loop.
The ellipse becomes a
circle if we change the
cosine amplitude to 1
Pay attention to the fact
that plot2d() combines sines
and cosines arguments
element-by-element
That was the basic thing,
how do we improve it?
Ex 3-6: Lissajous
figures, plot 2
This is the plot that has
been modifed using
handles.* The script is
presented on the next
four slides
Major modifcations are:
- Both Lissajous fgures are
arrow style, one line is
dashdotted
- Title and axes labels have
been added & edited
- Background color has been
added
- The legend box has been
put
in the lower right-hand
corner,
text edited and box color
Ex 3-6: Lissajous
figures, script 2 (1/4)
# of linspace() steps is
lowered to 40 to better
show the arrows that are
used below
The body of plot2d() is
retained, the reminder will
be done with handles
The fgure handle is called
by gcf(), after which the
fgure background color
can be defned (addition
to Script 1)
// handles_demo2-3.sce
// Two Lissajous figures, sin(t) & cos(3t) and /
// sin(1.5t) & 0.5*cos(1.5t), with plot edited /
// using handles
/
clear,clc,clf;
// Plot Lissajous figures:
//------------------------------x=linspace(0,6,40)'; // 40 steps to allow arrows
sines = [sin(x) sin(1.5*x)];
// First figure
cosines = [cos(3*x) 0.5*cos(1.5*x)]; // Second figure
plot2d(sines,cosines,rect=[-1.1,-1.1,1.1,1.1])
Ex 3-6: Lissajous
figures, script 2 (2/4)
Ex 3-6: Lissajous
figures, script 2 (3/4)
Ex 3-6: Lissajous
figures, script 2 (4/4)
There were huge problems when I frst tried to include the gce(),
get current Entity, command in the script. The background color
did not come up after Scilab was reloaded, I could not defne
ticks, etc.
Lessons learned: Be sure that you now what you do with gce()!
And a fnal check
on the next slide
Ex 3-6: Lissajous
figures, check
After all these modifcations, lets make sure that we can
recall the basic plot by adding the following lines at the end
of the script:
// Check default settings:
//-------------------------------xdel();
// Delete Graphics Window
sda();
// Reset default Axes
plot2d(sines,cosines,rect=[-1.1,-1.1,1.1,1.1])
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
9. Converting Matlab
files
The embedded Matlab-toScilab translator seems to
work and manual conversion
is an option
Return to Contents
Tips on Matlab to
Scilab conversion
About halfway down
the Help Browser (which
is not in any logical
order) you fnd Matlab
to Scilab Conversion Tips.
You will see a long list
of the m2sci_... type of
functions
Click on the frst
subheading, MatlabScilab equivalents, and
you get a list of Matlab
functions and their
Scilab equivalents
(missing ones are not
included, like text() and
xlim() mentioned
below)
M-to-S translator:
messages on the
Console
Scilab
presents a list
of translation
conditions and
also warnings
of possible
errors on the
Console. The
warnings are
repeated as
comments in
the script (and
on one of the
text
documents)
M-to-S translator:
script (1/4)
This is the script that the translator delivers. It contains
comments that may or may not be of importance:
Statement &
warning added by
Scilab
Here comes the
second warning.
The Matlab
command was
clear,clc,clf;. May be
of importance if
the script is edited
with handles. In
such a case, try to
create a new script
by copy-pasting
// Display mode
mode(0);
// Display warning for floating point exception
ieee(1);
// Monopulse Antenna Pattern
// -------------------------------------clear,clc,// !! L.4: All children will be deleted, no
HandleVisibility property in Scilab graphics.
clf;
// Normalized Aperture Width
na = 4;
// Sampling Frequeny=Number elements per norm
aperture
fs = 8;
M-to-S translator:
script (2/4)
// Norm aperture with N elements
N = fs*na;
xna = na*(-1/2:1/(N-1):1/2);
Everything runs
smoothly here
The code is expected
to present the sum and
difference patterns for
a monopulse antenna
(tracking radar, etc.)
// Illumination Function
wxna(1,1:N/2) = ones(1,N/2);
wxna = mtlb_i(wxna,N/2+1:N,-ones(1,N/2));
wxnb(1,1:N/2) = ones(1,N/2);
wxnb = mtlb_i(wxnb,N/2+1:N,ones(1,N/2));
// Fill with M/2 zeros front and back
M = 1024;
xna = na*(-1/2:1/N+M-1:1/2);
wxna = [zeros(1,M/2),wxna,zeros(1,M/2)];
wxnb = [zeros(1,M/2),wxnb,zeros(1,M/2)];
// Beam Functions from -fs/2 to fs/2 in sine space
Nfft = max(size(wxna));
Esine = mtlb_fft(wxna,Nfft);
Esine = fftshift(Esine);
M-to-S translator:
script (3/4)
Esum = mtlb_fft(wxnb);
Esum = fftshift(Esum);
// Azimuth vector
sinf = ((fs/4)*(-Nfft/2:Nfft/2-1))/Nfft;
M-to-S translator:
script (4/4)
Note that title() is
an alternative to
xtitle()
Here come the last
warnings. The next
slide shows what
they mean
Well, lets see how
Scilab reacts by
executing the
script...
Yeees, it comes,
labels and all!
But the legends
are missing,
which means that
Scilab cannot
cope with
Matlabs text()
function
M-to-S translator:
comments
*) A paper by Sharma & Gobbert (2010) reports that the translator cannot
cope with Matlabs xlim() function. In their case the plot() function had to
be manually changed to plot2d() to correct the problem.
Manual conversion
(1/6):
Case #1, script
Comments: % //
Built-in functions: pi %pi
Plot commands are split up on
multiple rows. Indents are not
necessary, but a visual help
// M-to-S_1-modulation.sce
// beating sinusoidal tones /
cear,clc,clf;
t = linspace(-1e-2,1e-2,1001);
x = cos(2*%pi*1500*t) + cos(2*
%pi*1300*t);
m = 2*cos(2*%pi*100*t);
plot( t, x.*m, rect = [-0.01 0.01 -2.4 2.4] )
title( 'Beating between tones' )
xlabel( 'Time (s)' )
ylabel( 'Amplitude' )
Manual conversion
(2/6):
Case #1, plot
Manual conversion
(3/6):
Case
#2,
script
plot
The pie() function
has not
been discussed&
before,
but below
is a short Matlab script that draws a pie graph*
// M-to-S_2-pie.sce
// Draw a pie graph with labels /
clear,clc,clf;
revenues = [31 36 18 8 7];
pie(revenues,['Income Tax';'Sales
Tax';'Borrowing';
'Corporate Taxes';'Misc']);
Manual conversion
(4/6):
Case
#3,
script
plot
As a last case,
lets look
at a shifted sinc&
function
// M-to-S_3polarplot.sce
// Polar plot of 1+sin(x)/x /
clear,clc,clf;
x = -(5*2*%pi):.1:(5*2*%pi);
th = linspace(-%pi,
%pi,length(x));
rho = 1+sin(x)./x;
polarplot(th,rho)
Manual conversion
(5/6):
Case #3, discussion
Linear plot
// M-to-S_3polarplot.sce
// Polar plot of 1+sin(x)/x
clear,clc,clf;
x = -(5*2*%pi):.1:(5*2*%pi);
th = linspace(-%pi,
%pi,length(x));
rho = 10*log10((1+sin(x)./x));
subplot(211);
plot2d(th,rho)
subplot(212);
polarplot(th,rho)
Polar plot
Manual conversion
(6/6):
discussion & hints
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
10. Subroutines
This discussion on
subroutines is a prelude to
flow control that will be
discussed in Chapter 11
Return to Contents
Terminology
Recall from Chapter 1 that Scilab does not recognize the
term subroutine, which belongs to the group of varied
constructs that Scilab calls function. More exact, we are
talking about user defned functions (UDFs), an expression
that Scilab also does not know
Regardless of official Scilab terminology, I willwhen
possibleuse the traditional term subroutine since it is an
elegant way of pointing to specifc entities in computer
programs
An introductory demo
function A = triangle_area(a,b,c)
// The function 'triangle_area' calculates the
/
// area of a triangle with side lengths a, b, c.
/
funcprot(0)
p = (a+b+c)/2 // p = half perimeter
A = sqrt(p*(p-a)*(p-b)*(p-c))
endfunction
-->function A = triangle_area(a,b,c)
-->// The function 'triangle_area' calculates the /
-->// area of a triangle with side lengths a, b, c. /
-->funcprot(0)
-->p = (a+b+c)/2 // p = half perimeter
-->A = sqrt(p*(p-a)*(p-b)*(p-c))
-->endfunction
-->triangle_area(4,5,6)
ans =
9.9215674
Local function
(local subroutine)
.....
.....
Call 1
Call
Result 1
Result
.....
.....
Call 2
Result 2
Scilab script
.....
.....
Scilab script 1
Global function
(global subroutine)
.....
.....
Call
Result
Scilab script 2
You will run into the terms local and global variables
and they need a short clarifcation:
As with functions, Scilab has two types of function
variables, local and global:
Subroutines, more
formally
endfunction
On output arguments
The example to the
right highlights the
basic way in which
Scilab manages
output arguments
of subroutines
When you need to
influence the
management of
input and output
variables, Scilab
offers the functions
argn (), varargin (), and
varargout ()
3x4=12
-->y2 = myfunc(4,7)
y2 =
12.
3x4=12
-->[y1,y2] = myfunc(4,7)
y2 =
37.
5x7+2=37
y1 =
12.
3x4=12
With no output
argument defned,
the frst output
argument is
returned in the ans
variable
The same answer
is returned when
only one output
argument is
defned
With both output
arguments
defned, the result
of the computation
is returned in full
Vector arguments
x(1)=5*(-5)-8*(-13)
x(2)=8*7-(-2)*(-5)
x(3)=-2*(-13)-5*7
*) Here I use the term function since the code is independent and not called
by a main program.
Demo (1/2):
script
Task: Compute &
plot a parabola, fnd
its positive root
Here the subroutine
is called for the frst
time using the input
argument x
Here the subroutine is
called twice more, frst
with the input argument
a, then b
Interesting way of
fnding the root location.
Later well do the same
using fsolv()
// subroutine1.sce
// Compute & plot the function y = x^2-x+1 in the /
// range [-5,5] and determine its positive root.
/
// Assume we know the root lies in the range [1,2] /
clear, clc, clf;
// SUBROUTINE para():
//-----------------------------function y=para(x);
// Subroutine declaration
y = x^2-x-1
// Equation (parabola))
endfunction
// MAIN script:
//------------------x = linspace(-5,5,100); // Range of interest
plot(x,para)
// Call subroutine and plot
xgrid;
// Add grid
a=1; b=2;
// Search limits
while b-a > 10^(-4)
// Accuracy for searching roo
c = (a+b)/2;
// Midpoint of limits
if para(a)*para(c)>0 then // IF (lower)*(midpoint
// is positive
a=c;
// THEN change lower limit
else
b=c;
// ELSE change upper limit
end
end
disp("The root lies between "... // Output root limits
+string(a)+" and "+string(b))
a = para(x);
plot(x,a)
Subroutines have to be
declared before the calling
main part of the script
Nested subroutines
-->function y = nested(x)
--> a = sin(x) + 2*%pi;
-->
function y = inner(x);
-->
y = x^2 -sqrt(x);
-->
endfunction
--> y = inner(a) + 3^2;
-->endfunction
-->value = nested(%pi/3)
value =
57.437413
Global subroutines:
window demo (1/4)
Global subroutines:
window demo (2/4)
Global subroutines:
window demo (3/4)
// reuse_function.sce
// Reusing graphics function,
/
// defenitions with handle commands /
clear,clc;
Figure saved.
So it is as a subroutine. I
called it window_demo.scg .
Note the ending .scg. Not .sce
or .sci. Its g for graphic
Then we need a main script
that uses global subroutine
Note that I call the Entity
handle e=gce(). It simplifes
compared to the path needed
if calling the Axes handle, as
was done in Chapter 7
Global subroutines:
window demo (4/4),
plot
Comment: multiple
plots with a single
command
y1 = 2*sin(x) - 2;
// First equation
y2 = 2*cos(2*x) + 6;
// Second
equation
plot2d(x,[y1',y2'])
// Plot both
e=gce();
// Get Entity
handle
e.children.thickness=5; // Polyline size
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Introduction
We have now come to the line that separates boys from men
Some examples using flow control (also known as conditional
branching and programming) have come up in the preceding
chapters, but the nature of conditional branch commands like
if ... then ... else has not been discussed*
Flow control together with subroutines are needed for serious
practical simulations
We shall therefore take a good look at the most important
aspects of flow control
Note, however, that loop operations are slow. We should aim for
vectorized operations if a task requires a lot of loop iterations
(there is a brief discussion on the subject in Chapter 18 )
*) Historical note: Konrad Zuse, the German who built the first real computer
during WW II (using over 2000 relays because he did not trust vacuum tubes),
got everything right except for conditional branches.
Flow control
constructs
The following are main constructs that you should be familiar with:
Branch commands:*
for ... (if ... else) end
while ... (if/then/else) ... end
if ... (elseif ... else) ... end
select ... case (... else) ... end
break ... continue
try ... catch ... end
Logical operators:
Comparison operators:
==
equal to
<
smaller than
>
greater than
<=
smaller or equal to
>=
greater or equal to
<> or ~=
not equal to
Logical/Boolean constants:
&
and
| or /
or
%t or %T
true
not
%f or %F
false
*) Rumor has it that Scilab will see select ... case renamed switch ... case in
line with Matlab.
for end
As seen here:
square
cannot be used
as variable
name since
square() is a
Scilab function
// for-end_demo.sce
// Compute the square root and
square /
// of odd integers from 1 to 8
/
n = 8;
for k = 1:2:n
root = sqrt(k);
quadrat = k^2;
disp([k, root, quadrat])
end
1.
7.
49.
1.
1.
2.6457513
for ... end can be nested with if/else conditions to allow for
execution of alternate statements:
for variable = initial_value:step:final_value
if condition
// foo
else
// foo
end
end
Only variables,
nothing to comment
// --------------------------------------------------------------------------- /
// The script generates Gaussian noise around a fxed
signal.
/
// Each sample ("signal") is sorted according to whether it
/
// is within, above or below default variance limits (+/-1).
The /
// result is reported verbally with strings and is also plotted
/
// --------------------------------------------------------------------------- /
clear,clc,clf;
// Define variables:
// -----------------------n = 500;
// # of forend loops
above = 0;
// Signals above upper variance limit
below = 0;
// Signals below lower variance limit
within = 0;
// Signals within variance limits
ave = 3;
// Mean (average)
x = [];
// x axis vector
// Generate signal:
// ---------------------dt = getdate();
// Get date
rand('seed',(531+n)*dt(9)+dt(10)); // Initialize random
generator
signal= ave + rand(1,n,'normal');
// Shifted Gaussian signal
// Sort signal:
// ---------------for j = 1:1:n
if signal(1,j) > ave+1 then
// Default variance = +/-1
above = above + 1;
// Count signal > mean+var
elseif signal(1,j) < ave-1
// Default variance = +/-1
below = below +1;
// Count signal < mean-var
else
// If within variance limits
within = within + 1;
// mean-var <= signal <=
mean+var
end
end
This particular
form of multiple
plots was
discussed earlier
and is worth
keeping in mind
// Display result:
// -------------------disp(['Result from generating', string(n), 'Gaussian distributed
samples'])
disp(['(signals) with mean =' string(ave) 'and variance = 1:'])
disp([' -' string(within) ' samples were inside variance limits,'])
disp([' -' string(above) 'above upper variance limit, and'])
disp([' -' string(below) 'below lower limit'])
// Plot result:
// --------------x = [1:1:n];
// Array for x axis
y1 = ave*ones(1,n);
// Array for mean value
y2 = (ave+1)*ones(1,n);
// Array for upper variance
limit
y3 = (ave-1)*ones(1,n);
// Array for lower variance
limit
rect = [0,ave-4,n+1,ave+4];
// Set pot window
plot2d(x,signal,2,"011"," ",rect) // Plot samples
plot2d(x,y1,5,"000")
// Plot mean value
plot2d(x,y2,3,"000")
// Plot upper variance limit
plot2d(x,y3,3,"000")
// Plot upper variance limit
legend('signal','average','variance');
xtitle('GAUSSIAN RANDOM SAMPLES','Sample #','Sample value')
What kept me on the wrong track for too long was that the data
was collected correctly, but is was destroyed when it was brought
outside the for ... end loop. However, that did not happen if there
was a display command inside the loop. For instance, no
semicolon after signal(:,n). Speak of coincidences.....
while end
while condition
// foo
// loop counter, i.e. count = count +1;
end
-->k = 1;
52.
while if /then/else
end
The while ... end condition can be nested with an optional if ...
then ... else instruction:
while condition_1
if condition_2 then
// foo
else
// foo
end
// foo
end
while if /then/else
end: demo
// The function draws a random number in the /
// range [1,M] that the user should guess.
/
// Game fnishes when correct number is found /
clear,clc;
-->guess_a_number
// game.sci
Loop
M=30;
// Upper limit of numbers
number=floor(1+M*rand());
// Draw a random
number
disp('Guess a positive integer in the range ');
disp([1,M]);
// State range of random
numbers
guess=input('You guess: ');
// User's guess
while (guess~=number)
// Start while condition
if guess>number then
// Start if-then-else
disp('Number is too big');
else
disp('Number is too small');
end
// End if-then-else
guess=input('You guess: '); // User's next guess
end
// End while condition
disp('Correct!');
Comments on
interactivity
To the user the input() prompt is not very clear since the text
string only pops upit should at least blink. One must therefore
try to fnd expressive text messages. Perhaps the following would
be better in the previous case:
guess = input(Now, Sir/Madame, type your guess: )
foo do end
if (elseif/else) end
if condition_1
// foo
elseif condition_2
// foo
else
// foo
end
if elseif/else end:
demo
The following function computes the n:th term of the Fibonacci
sequence when n is given:
// fbonacci.sci
// Gives the n-th term of the Fibonacci /
// sequence 0,1,1,2,3,5,8,13,...
/
funcprot(0)
// Suppress redefenition warning
function [K] = fbonacci(n)
if n==1
// Begin if-elseif-else-end
K = 0;
elseif n==2
// Condition to proceed, n > 2
K = 1;
elseif n>2 & int(n)==n
// Check if n is an integer >2
K = fbonacci(n-1) + fbonacci(n-2);
// Compute
Fibonacci #
else
// Previous conditions not met
disp('error! -- input is not a positive integer'); // Error
message
end
// End of if-elseif-else-end
endfunction
13.
Check what
happens
ans = for n <
1 --
The select ... case ... else ... end construct executes the frst case
that matches the stated condition
If no match is found it executes the else statement
The advantage of select ... case ... else ... end is that it allows us
to avoid multiple if statements
select condition
case 1
// foo
case 2
// foo
else
// foo
end
// randomwalk.sce
//-----------------------------------------------------------------/
// Creates a track of marks that proceed randomly
/
// in the x,y plane. The walk starts at the origin
/
// and proceeds for a predetermined number of
steps /
// either up, down, right, or
left
/
//-----------------------------------------------------------------/
clear,clc,clf;
funcprot(0);
function randwalk(steps)
x=zeros(1,steps+1);
// Counter for x
track
y=zeros(1,steps+1);
// Counter for y
track
for k=1:steps
direction=floor(4*rand()); // Draw random
move
select direction
->randwalk(1000
)
case 2 then
x(k+1)=x(k);
y(k+1)=y(k)+1;
case 3 then
x(k+1)=x(k);
y(k+1)=y(k)-1;
end
end
clf
plot(x,y,'o-');
endfunction
// Move up
// Move down
// Plot marks
The starting
point is always
the origin (I
have run this
simulation
numerous times
and Scilab
seems to prefer
to go in the
northeastern
7.
break: demo
// break.sce
// Input m positive integers that are summed /
// up, but the program breaks if the input
/
// is not a positive integer
/
clear,clc;
n = input('Give amount of numbers to sum_');
summa = 0;
// Reset summa counter
for i = 1:n
number = input('Give next number_');
if number < 0
// Condition: number
~< 0
disp('wrong-----negative value!');
break;
end
if number ~= int(number)
// Check if
integer
disp('wrong-----not an integer!');
break;
end
summa = summa + number; // Sum up
end
disp(['Accumulated error-free sum is:'
!Accumulated error-free
sum is: 37 !
Give next number_7
Give next number_17
Give next number_13
Give amount of numbers to
sum_3
!Accumulated error-free
sum is: 19 !
wrong-----negative value!
Give next number_-1
Give next number_2
try
// foo
// If an error occurs in this part....
catch
// .... execution continues here
// foo
end
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Unit step:
1
0
t0
y(t) =
t
0, t < t0
1, t > t0
Rectangular pulse:
y
A
0
t0
y(t) =
t1
A, t0 t < t1
0, otherwise
// Define u(t)
y = 2*(u(t-3) - u(t-5));
// Define pulse
plot2d(t,y,5,rect=[0,0,8,2.5]) // Plot
xgrid()
// Add grid
f=gcf();
// Figure handle
f.children.thickness=2;
// Figure lines
a=gca();
c=a.children;
// Compound handle
c.children.thickness=3;
// Line thickness
In the frst case (unit step) the handle command for line
thickness is
a.children.children.thickness=3;
In the second case (rectangular pulse) Scilab did not accept this
form and it had to be rewritten as
c=a.children;
c.children.thickness=3;
I have no idea why this is the case and Help certainly is of no help
In the latter case I happened to write the script without the deff()
function, and for a while everything came out all right. But when
I added handle commands Scilab decided that the variable u is
undefned. The KISS principle (Keep It Simple, Stupid) did not
apply in this case
// ********************************************** //
// The script generates and plots a cone with
its
//
// tip at the origin. It plots two copies of the
// cone, one shifted and one shifted &
rotated
//
//
// ********************************************** //
//
//
clear,clc,clf;
// Vertical reach of 3D object:
vertical=[0,1.0,1.6,2.5,2.2,2,1.6,0.9,0.5,0.3,0.3,0.4,0.6,1,
1.4,...
1.7,0,0,0.1,0.4,0.8,1.1,1.4,1.7,1.9,2.2,2.4,2.7,3,3.3,3.7,3.9
]/2;
// SUBROUTINE 1: Generation of 3D object:
//---------------------------------------------------------function [x,y,z]=cone(reach,Z) // Generation of a 3D
object
x=vertical(1,Z).*cos(reach)
// Extension along x
axis
Non-rotational
dilatation of objects is
the task of homothety()
rotation() creates a
matrix for rotating
objects around the
three axes
Those are the four user
defned functions
of rotation around
// Rotation along x
// Rotation along y
// Rotation along z
Ex 4-2: plot
Original cone
with tip at the
origin
Second cone,
laterally shifted
and enlarged
Third cone,
laterally shifted
and rotated
And the shading
of them is all
wrong. See
Example 4-3 for
an explanation
Ex 4-2: comments
Among the handle commands are some that have not been
discussed before: f.color_map=graycolormap, e1.color_mode,
e1.hidden_color, a.rotation_angles, and a.isoview=on (recall
however the colormap command that was used in Ex 3-5)
// cone_creation.sce
// A bare-bone eval3dp() script for plotting a 3D cone /
clear,clc,clf;
vertical=[0,1,2,2.3,3,4];
object
// Vertical reach of 3D
Ex 4-3: plot
Dark gray interior (e1.hiddencolor = 30)
Z5 = 3
Box alignment
defned by theta
and alpha in
plot3d()
Z4 = 2.3
Z3 = 2
Z2 = 1
Z1 = 0
Light gray exterior (e1.color_mode = 24)
Ex 4-3: discussion
Ex 4-3: how to
transform the cone to
a vase
// vase_creation.sce
// Vertical reach of 3D
// Correction matrix
no
abstain
//
//
//
//
clear,clc;
funcprot(0)
function voting
// Give input and check entered number:
//------------------------------------------------------n = input('Give number of issues to vote on_ ');
if n <= 0 do
// # of votings must be > 0
disp('warning-----must be > 0');
abort;
end
if n ~= int(n) do
// n should be an integer
disp('warning-----not an integer!');
abort;
end
Generation of random
numbers in the similar
manner to Ex 1-3
Ex 4-4: comments
if ... end
Note how
min() and
max() ensure
that scale
limits are not
exceeded
// conditional.sce
//
//
//
//
scale = [1 2 3 4 5 6 7 8 9]';
// Define scale to climb
i = 1;
// Preset counter
strg = ' ';
// strg = empty string
while strg ~= 'e'
// Until the "e" key is hit
disp(scale(i,:));
// Display location on
scale
strg = input('Exit(e), Up(u), Down(d)?','string')
if strg == 'u' then
// If "u" is hit
i = min(i+1, size(scale,1)); // One step up, until
highest
elseif strg == 'd' then
// But if "d" is hit
i = max(i-1, 1);
// One step down, until
lowest
elseif strg == 'e' then
// If "e" is hit
break;
// Jump out of the loop
else
// Whatever else is hit
disp('---incorrect input---') // Present error message
end
// End of if statement
Example 4-5:
execution
The scale counter i is preset
to 1 and
increases/decreases
depending on the entered
data
Any input parameter except
u, d, or e give an error
message
The break command works
well
in thisthe
case
Homework:
Modify
script by
using the select ... case ... else ... end
structure instead of if ... elseif ... else ...
end. Which solution is simpler?
1.
Exit(e), Up(u), Down(d)?u
strg =
u
2.
Exit(e), Up(u), Down(d)?u
strg =
u
3.
Exit(e), Up(u), Down(d)?d
strg =
d
2.
Exit(e), Up(u), Down(d)?6
strg =
6
---incorrect input--2.
Exit(e), Up(u), Down(d)?u
strg =
u
3.
Exit(e), Up(u), Down(d)?e
strg =
e
you hit e=Exit
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Math in earlier
chapters
"Do not worry about your problems with mathematics, I assure you mine are
far greater. Albert Einstein
// optim_list.sce
// Investigation of minima and maxima of the function /
// sin(x)/((x-0.1)^2+0.1)
/
clear,clc,clf;
// SUBROUTINES
//---------------------deff('[fun1,grad,ind]=cost1(x,ind)',...
// Function
'fun1=sin(x)/((x-0.1)^2+0.1),grad=0');
deff('[fun2,grad,ind]=cost2(x,ind)',...
// Inverse functio
'fun2=-sin(x)/((x-0.1)^2+0.1),grad=0'); // note minus sig
// ---- MAIN ---- //
// Plot function:
//-------------------x=-5:0.01:5;
fplot2d(x,cost1,5)
xgrid
// Plot function
min
max
2.1199214
max
- 1.1381166
roots
min
x1 -3, x2 0, x3 3
With the script is loaded into Scilab, we fnd the solutions on the
Console using the command x = fsolve(x0,f):
x1
x2
x3
Equation systems
require a different
approach. See e.g.
Zogg, pp. 66-69
I said above that the Help
Browser is confusing when
one tries to fnd out
something about optim(). A
better source is Section 4.2
in Campbell et al.
fsolve(): limitation
The script below demonstrates that for values of point close to
peak of the sin curve, e.g. 4.6 or 8, Scilab cannot solve the root
correctly
// fsolve.sce
//
//
//
//
/
/
/
/
clear,clc,clf;
function y=myfunc(x)
a=1;
y=sin(a*x)-x.*exp(-x);
endfunction
x1=linspace(0,10,300);
plot2d(x1,myfunc(x1),5)
// Plot function
plot2d(x1,zeros(x1),2)
// Add y=0 graph
point = 8;
// Point of interest
[x,y]=fsolve(point,myfunc) // Def root closest to point
plot2d(x,y,-3)
// Add mark for root location
Complex numbers:
demo, task
Complex numbers
have not been
discussed at any
length before, so
lets look at a
practical problem
R2+jL
] = Z[
-R2
-jL
-R2
R1+R2
-R1
-jL
-R1
R1+jL-jC
Complex numbers:
demo, equations
i1
i2
i3
80+j12
-80
-j12
-80
100
-20
-1 0-j100
-j12
-20
-500-j0
20-j8
0+j0
Note that u2 was selected opposite to u1, hence the minus sign
Scilab has no problems with doing inverse matrices but, as
mentioned before, left hand division (\) typically gives better
accuracy
Complex numbers:
demo, script (1/3)
// circuit3.sce
//
//
//
//
clear,clc;
// Compute complex currents:
//--------------------------------------Z = [80+12*%i, -80, -12*%i;
-80, 100, -20;
-12*%i, -20, 20-8*%i]; // Impedance matrix
u = [-100*%i; -500; 0];
// Voltage matrix
i_n = Z\u;
// Compute i = Z\u
// Calculate magnitude and phase:
//--------------------------------------------magn_i = [];
// Define empty current matrix
phase_i = [];
// Define empty phase matrix
for j = 1:1:3
// Compute for three currents
magn_i(j) = sqrt(real(i_n(j))^2 + imag(i_n(j))^2);
// Computes magnitude
Complex numbers:
demo, script (2/3)
// Calculate phase:
//-----------------------if clean(real(i_n(j))) > 0 then
// In 1st or 4th quadrant
phase_i(j) = atan(imag(i_n(j))/real(i_n(j)))*(180/%pi);
elseif clean(real(i_n(j))) < 0
// In 2nd or 3rd
quadrant
if clean(imag(i_n(j))) > 0 then // In 2nd quadrant
phase_i(j) = atan(imag(i_n(j))/real(i_n(j)))*(180/%pi) +
180;
elseif clean(imag(i_n(j))) < 0 then
// In 3rd quadrant
phase_i(j) = atan(imag(i_n(j))/real(i_n(j)))*(180/%pi) 180;
else
// On negative Re-axis
phase_i(j) = 180;
end
elseif clean(imag(i_n(j))) > 0
// On positive Im-axis
phase_i(j) = 90;
elseif clean(imag(i_n(j))) < 0
// On negative Im-axis
phase_i(j) = -90;
else
// Origin: imag(i_n(j)) = real(i_n(j)) = 0
phase_i(j) = 0;
end
result(j,:) = [i_n(j), magn_i(j), phase_i(j)];
// Matrix collects computed data
j = j+1;
Complex numbers:
demo, script (3/3) &
print
In plain English:
// Display summary:
//-------------------------currents = ['i1 = ', 'i2 = ', 'i3 = ']';
// String
matrix
statement = [' equals: ',' equals: ',' equals: ']';
// String
matrix
disp(['CURRENTS IN COMPLEX AND POLAR FORM:']) //
Headline
disp([currents, string(result(:,1)), statement,...
// Display
result
string(result(1:3,2)), string(result(1:3,3))])
// Check residual:
//---------------------residual = clean(u - Z*i_n)'
// Check initial results
CURRENTS IN COMPLEX AND POLAR FORM:
! i1 = -14-%i*17
equals: 22.022716 -129.47246 !
!
!
! i2 = -15.2-%i*18.6 equals: 24.020824 -129.25584 !
!
!
! i3 = 5-%i*25
equals: 25.495098 -78.690068 !
Numeric derivation
(1/3):
derivative()
The derivative of the function f(x) is
defned as the limit
// derivative_1.sce
f(x) = lim
d0
f(x + d) f(x)
d
// Derivative of sin(x)/((x-0.1)^2+0.1) /
// calculated at selected points
/
clear,clc;
funcprot(0);
deff('y=f(x)','y=sin(x)./((x-0.1)^2 +
0.1)');
x = [-2 -1 0 1 2]';
// Points of
interest
disp(["Point", "Derivative"])
disp([x, diag(derivative(f,x))])
Numeric derivation
(2/3):
script
// derivative_3.sce
children(2) and
children(3) are used
because children(1) is
reserved for legend
clear,clc,clf;
funcprot(0)
x = -5:0.01:5;
d = 0.001;
// Area of interest
// Step size
Numeric derivation
(3/3):
plot
A lesson from
doing this exercise
is that two deff()
functions in
tandem, i.e. one for
f(x) followed by
one for f(x) that
utilizes f(x), does
not work. On the
contrary, the
attempt may cause
Scilab to crash
Pay attention to the legend command in the script. It comes
before the related handle statements, but Scilab does not
complain. Beats me...
Numeric integration
(1/6):
definite
integral
Consider the defnite integral
A=
f(x) dx
*) The function
integrate() can be more
useful in some cases.
Check with Help
-->deff('y=f(x)', 'y=sin(x)');
18.
A =
-->A = intg(-2,1,f)
Change the
integration limits
-->deff('y=f(x)',
'y=6*x^2'); to 0 and 2*%pi,
and this is what
-->A=intg(0, 2*%pi, f)
you get
Numeric integration
(2/6):
length of an arc
-->deff('y=g(x)','y=sqrt(1+(x^2/8-2*x^(-2))^2)');
L=
{1 + [f (x)] }
2 1/2
dx
-->L=intg(2,3,g)
L =
1.125
-->L=intg(3,4,g)
L =
1.7083333
Numeric integration
(3/6):
double
integral, principle
The function int2d () computes
d
I=
f(x,y) dx
y
d
dy
D=a,d
C=b,d
ACD
ABC
A=a,c
B=b,c
a a
c c
X= b b , Y= c d
b a
d d
ABC ACD
ABC ACD
Numeric integration
(4/6):
double integral, demo
I=
(y cos(x) + x sin(y)) dx
/2
-->deff('z=f(x,y)', 'z=y*cos(x)+x*sin(y)');
0 0
X=
0
/2 /2
Y = /2 2
2
2
dy
0.
3.1415927
3.1415927
0.
3.1415927
0.
1.5707963
6.2831853
6.2831853
-->[I,err] = int2d(X,Y,f)
err =
9.805D-11
I =
- 4.9348022
Numeric integration
(5/6):
double integral, plot
The plot of f(x,y) = y*cos(x)
+ x*sin(y) is here done with
a separate script:
// double_integral_plot.sce
// Plot the function z = y*sin(x) + x*sin(y)
/
// over the rectangle 0<x<%pi, %pi/2<y<2*%pi /
clear,clc,clf;
x=linspace(0,%pi,30);
// Linear x axis
y=linspace(%pi/2,2*%pi,30); // Ditto y axis
[X,Y]=meshgrid(x,y);
// Surface mesh
Z=(Y.*cos(X)+X.*sin(Y));
// 3D surface
equation
surf(X,Y,Z)
// Plot 3D surface
xtitle('f(x,y) = y*cos(x) + x*sin(y),
// Add
title
with 0<x<%pi, %pi/2<y<2*%pi')
Numeric integration
(6/6):
double integral, check
D=a,d
BCD
C=b,d
ABD
A=a,c
B=b,c
a b
c c
X= b b , Y= c d
a a
d d
Same result, but a small
difference in the estimated
error
Ordinary differential
equations (ODEs):
ode()*
This simplest call for solving ODEs is ode() that has the
general form:
y = ode(y0,t0,t,f(t,y))
where
First-order ODEs:
demo
Second-order ODEs:
introduction
Problem expressed as
second-order ODE
Select state variables
Substitute state
variables with zerothorder variables
Rewrite problem as
first-order state-space
equation system
Solve using Scilabs
ode() function
Second-order ODEs:
RLC circuit (1/5), the
task
The task is to plot the
output voltage v for the
U = 5V
switch closes at t = 1
R = 0.3
L = 0.5 H
C = 0.8 F
d2v2(t)
dt
+ RC
dv2(t)
dt
+ v2(t) = v1(t)
Second-order ODEs:
RLC circuit (2/5),
reduce
x1
RC
x2 +
u
LC
x1
0
=
x2
1
1
RC
x1
R
x
L2
0
+
1u
LC
Second-order ODEs:
RLC circuit (3/5), script
Recall the
discussion in
connection with
Ex 2-3: We are
working with a
matrix expression
of the type
x = Ax + bu
All of these factors
can be seen here,
with x being
denoted ss and x
substituted by y
// RLC_ODE.sce
// Simulation of a series RCL circuit with /
// 5V step input voltage at t = 1s
/
clear,clc,clf;
// Define circuit components:
//-------------------------------------R = 0.3;
L = 0.5;
C = 0.8;
Second-order ODEs:
RLC circuit (4/5), script
The ode() function
computes our
differential equation
by using the RLC
state-space
expression of the
second deff()
function. Calling
parameters are y0
and t0
Note the plot
command (new way
of doing
plot2d())
Handle
commands
come before the
legend (in this case
Scilab gives an error
message if you try it
the other way)
Second-order ODEs:
RLC circuit (5/5), plot
The plot shows that
the circuit is
undercritically
damped. Change the
resistor value to 1.5 ,
and it becomes
critical. It is
overcritical for still
higher values of R
Handle commands
could be used to edit
the fgure further. I did
not do it because the
main point with this
demo is to solve a
second-order ODE
odeoptions()
The command
%ODEOPTIONS = odeoptions()
opens the GUI shown right.
With the help of it you can
change parameters for
solving differential equations.
Examples:
h0 = size of frst step
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Example 5-1:
solving an equation
(1/3)
-->plot2d(x,[log(x), x.^27*x+10])
-->x = (0.01:0.01:8)';
Ex 5-1: solving an
equation (2/3)
The zoom function gives more precise values for the roots:
x1 = 1.81 and x2 = 5.49
To improve the accuracy even more we can calculate the
roots with the fsolve() function (next slide)
Ex 5-1: solving an
equation (3/3)
-->deff('y=f(x)', 'y=log(x)-(x^2-7*x+10)');
-->x1=fsolve(1.8,f)
x1 =
1.8132512
-->x2=fsolve(5.5,f)
x2 =
5.4881107
-->f(x1),f(x2)
ans =
- 7.772D-16
ans =
- 4.441D-16
Check
di(t)
dt
+ Ri(t) +
1
C
q(t) = u(t)
where
t
q=
i(t) dt
or:
dq
dt
= i
R = 0.3
L = 0.5 H
C = 0.8 F
u(t) = sin(5t)
LC
R
L
Remember: x = Ax + Bu
1u
L
There is nothing
new here
compared to the
previous
RLC/second-order
ODE
//
//
//
//
clear;clc,clf;
// Define circuit components:
//-------------------------------------R = 0.3;
// Resistance (Ohm)
L = 0.5;
// Inductance (Henry)
C = 0.8;
// Capacitance (Farad)
// Define state-space equations & input signal:
//-------------------------------------------------------------A = [0 1; -1/(L*C) -R/L];
// SS system matrix
B = [0; 1/L];
// SS input matrix
deff('[ut]=u(t)','ut=sin(5*t)');
// Sinusoidal input
deff('[ss]=RLC(t,y)',ss=A*y+B*u(t)'); // SS expression
This example is modifed from Povy (pp. 66-67, Povy also has an
animation version on pp. 67-68, but it causes Scilab to crash).
The example fnishes with and interesting plot2d() command
The task is to plot the slope (vector) feld for the following
system of frst-order ODEs :
x = y
y = -x y
x
0 1
=
y
-1 -1
x
y
Ex 5-3:
script
The state-space
function is named
firstorder()
The vector feld is
drawn with fchamp()
ode() has only one
argument (and
accepts only one
name) for the initial
condition x and y
are renamed x(1) and
x(2) respectively, as
shown in the
arguments for plot2d()
// ode_phase_plane_m.sce
//
//
//
//
clear,clc,clf;
funcprot(0);
// First order transformation:
//-------------------------------------A = [0 1;-1 -1];
// State vector
deff('[ss]=frstorder(t,x)',ss=A*x');
// Create & draw slope (vector) field:
//------------------------------------------------z = linspace(-1.5,1.5,10);
fchamp(frstorder,0,z,z)
// Draw vector field
// Create phase portrait:
//------------------------------x0 = [1;1];
// Initial condition
t = linspace(0,30,300);
[x] = ode(x0,0,t,frstorder); // [x]=state variable
vector
// with x=x(1), y=x(2)
// Plot phase portrait on slope field:
//----------------------------------------------plot2d(x(1,:),x(2,:),5,'004')
xtitle('Phase plane of dx/dt=y, dy/dt=-x-y')
Ex 5-3: plot
Full plot
Phase portrait
with initial
condition [1,1]
Zoomed center
area
Example 5-4:
Simpsons rule, the
task
I =
(y cos(x) + x sin(y)) dx dy
/2 0
x y
9
ij
i=2
j=2
i = i+2 j = j+2
d -c
// double_integration_simpson.sce
1. Overall headline
comments for the
program
//-----------------------------------------------------------------/
// The program calculates the double integral of the
2. UDF declaration
followed by clarifying
comments
clear,clc;
function [integral] =
simpson_double(x0,xn,n,y0,ym,m,f)
//
//
//
//
//
//
/
/
/
/
/
/
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Introduction
delmenu()
setmenu()
unsetmenu()
Create
-->addmenu('Graphics',['New window','Clear window','Close window'])
-->Graphics = ['scf()','clf()','xdel()']
Graphics =
!scf() clf() xdel() !
xclick ()
xgetmouse ()
seteventhandler ()
// rectangle_selection.sce
// The script demonstrates the use of the mouse-related
// commands xclick(), xgetmouse() and xrect() when they
// are used to draw a rectangle in the Graphics Window
/
/
/
clear,clc,clf;
// Initialize drawing process:
//-------------------------------------a = gca();
// Get current Axes
a.data_bounds = [0 0;100 100]; // Boundaries for x & y
coordinates
xtitle('Click left mouse button & drag to create a rectangle. ...
Click a second time to freeze')
// Display instruction
show_window();
// Put Graphics Window on
top
// Start drawing rectangle in the Graphics Window:
//-------------------------------------------------------------------[button,x_coord,y_coord] = xclick(); // Point of mouse button
click
xrect(x_coord,y_coord,0,0)
// Start rectangle at mouse pointer x & y
coordinates
GUI demo 1:
Introducing figure() &
uicontrol()
// uicontrol-1.sce /
// A basic GUI exercise /
clc; xdel();
f = fgure();
// Create a figure
h = uicontrol(f,'style','listbox',..
// Create a
listbox,
'position',[50 300 150 100]);
//
h = handle
set(h,'string',"Alpha|Beta|Gamma.. // Fill the list
|Delta|Epsilon|Zeta|Eta|Tau");
set(h,'value',[1 3]); // Highlight items 1 and 3 in
the list
Scilab has several commands for creating pop-up windows. Note that
x_message() is obsolete and will not work in Scilab 5.2 and later
versions; messagebox() has to be used instead:
Command
Feature
messagebox()
x_choose()
x_choices()
x_dialog()
x_mdialog()
x_matrix()
list()*
GUIs: messagebox()
The syntax of the messagebox() function is the following:
messagebox (message, title, icon, [buttons], modal )
Message that
you want to
convey
Box title (the
default is
Scilab
Message)
1xn vector of
strings with
button legends
modal tells Scilab to
Icon to be
wait for user actions
placed in the
(otherwise 0 is
box
returned)
Default title
Case 2:
Default icon
Case
2. 4: x_dialog() with input
transformed from string to matrix
ans =
->ans=x_choose(['Alpha','Beta','Delta','Gamma'],'D
ouble-click on one:')
6. Change
5. 4. matrix as needed, click OK
1. 2. 3.
3.
2.
Case 5: x_choices()
with four
alternatives for
three cases
Pick your
choices,
click OK,
and Scilab
returns the
answer as a
*) Scilab 5.1.1 returns the answer automatically,
vector*
1.
with 5.3.1 & 5.3.2 it must be asked for (a bug?)
clear,clc;
A = x_matrix('Change matrix to nxn as
needed',eye(3,3));
det(A)
// Calculate determinant
clean(det(A))
// Clean det(A) for small
values
ans =
Here Brandy is
selected and the
answer returned*
3.
m =
-->m
2.
-->get(0,"screensize_px")
ans =
1.
1.
1280.
800.
-->get(0,"screensize_pt")
ans =
0.
0.
960.
600.
-->get(0,"screensize_norm")
ans =
0.
0.
1.
1.
-->get(0,"screendepth")
ans =
24.
GUI demo 3:
predefined GW,
screenshot
GUI shortcomings
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Return to Contents
File handling:
introduction
mfprint, fprintMat()
mfscanf(), fscanMat()
mseek()
menf()
size()
*) The full set of i/o functions (~60 in all) can be found under Help/Files:
Input/Output functions. Recall the related load() function in Chapter 10.
// fle_exercise1.sce
// The script demonstrates the process of 1) creating a text fle
/
// on Scilab, 2) closing it, 3) opening it again to be written into,
/
// 4) writing the actual data into the fle, 5) reading
certain
/
// pieces of data from the fle, and 6) closing the read
fle,
/
// Notice that both close operations are
necessary!
/
clear,clc;
// Create and open a text file for the exercise:
//------------------------------------------------------------fd = mopen('H:\Dr.EW\Writings\Scilab
examples\fle_exercise1.txt','w');
// Create data and write into the exercise file:
//------------------------------------------------------------t = (1:1:18)';
// Integers from 1 to 18
mfprintf(fd,'%6.3f\n',t);
Then opened
again to be read
(r)
Next we read in
its entirety (the
-1)
before we can
defne which data
we want to see
Finish by closing
the fle (see below
The defned
read variable
contents brings
up the contents
of the text fle
on the Console
n is the # of
elements (-1) in
the vector it
belongs to (4-1)
We can then
pick out
specifc
elements from
the list
We can also
address specifc
elements in the
column vector
and get the
answer as a
row vector
18.
Spreadsheet data
(1/7):
Creating data
Spreadsheet data
(2/7):
Data saved as .csv file
Spreadsheet data
(3/7):
.csv file read by[G,text]
Scilab
= fscanfMat()
-->M = fscanfMat('I:\file_spreadsheet_demo5.csv')
M =
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
- 7.3
- 7.8
- 8.3
- 7.6
- 5.
- 3.3
- 1.9
0.1
1.2
0.4
- 2.1
- 3.6
20.1
19.8
19.5
19.5
19.7
20.
20.2
20.6
21.1
21.3
21.
20.7
M = fscanfMat()
-->[G,text] = fscanfMat('I:\file_spreadsheet_demo5.csv')
text =
Reading
Outdoor
Indoor
G =
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
- 7.3
- 7.8
- 8.3
- 7.6
- 5.
- 3.3
- 1.9
0.1
1.2
0.4
- 2.1
- 3.6
20.1
19.8
19.5
19.5
19.7
20.
20.2
20.6
21.1
21.3
21.
20.7
Spreadsheet data
(4/7):
script for plotting (1/2)
The fscanfMat()
command cannot
be split on two
rows (even if it is
not needed in this
case)
The size(name,r)
function is used to
determine the
number of matrix
rows
Matrix columns
form separate
vectors
// spreadsheet_data_plot.sce
// The script reads data from the test fle
/
// fle_spreadsheet_demo5.csv, determines its /
// length,and plots its two measurement sets /
clear,clc,clf;
// Open the file, determine number of rows,
// and form vectors of its columns:
//----------------------------------------data_fle = fscanfMat(IH:\fle_spreadsheet_demo5.csv');
// Opens text file
rows = size(data_fle,'r'); // Determine number of rows
readings = data_fle(:,1); // Column 1, reading #
(redundant)
outdoor = data_fle(:,2);
// Column 2, outdoor
temperature
indoor = data_fle(:,3);
// Column 3, indoor temperature
Spreadsheet data
(5/7):
script
for
The plot command
uses plotting (2/2)
the obsolete plot2d()
syntax that we have
seen before. The reason
for having it here is that
plot2d() with the frameflag
argument of the new
syntax does not work
when two graphs should
be fused into one plot:
The second plot
destroys the frst one,
and when the rect
argument is included
Scilab responds with an
error message (know it,
tried it)
Spreadsheet data
(6/7):
plot
Simple plot, but
the main point
with this exercise
is to show how to
go from
spreadsheet data
to a text fle and
then to plot the
data
And then we turn
to the question of
how to create text
fles with
LibreOffice Calc
and
OpenOffice.org
Calc (next slide)
Spreadsheet data
(7/7): Text data in LibO
& OOo
Save as Text CSV (.csv)
and select Tab in the
Field delimiter
dropdown menu of the
window that opens.
Thats it
mopen()
It can be a good idea to check the err parameter after a fle has
been opened (has not been done in Demo 1)
mclose()
mfprintf(), fprintfMat()
Format definitions
\n go to a new line
\t use a horizontal tabulator
Format demo:
script (1/2)
This demo aims at clarifying the use of format
declarations:
// fle_format_demo.sce
//
//
//
//
clear,clc;
// Create a new test file for writing:
//---------------------------------------fd = mopen('H:\Dr.EW\Writings\Scilab examples\fle_format_demo.txt','w');
// Some variable to play with:
//--------------------------------A = 123.45678901;
a = 0.3;
b = 1.23e-02;
c = a + %i*b;
text = 'Hello World';
Format demo:
script (2/2) & text file
// Several outputs to be demonstrated:
//-------------------------------------------mfprintf(fd,'%d\n %10d\n %20d\n %8.4f\t %8.4f\n %5.2f\t %5.2f\t
%5.2f\n',...
A,A,A,A,A,A,A,A);
mfprintf(fd,'%d\n %f\t %e\n %10.3f\t %6.2f\n complex = %3.4f + i
%3.4f\n\n',...
A,A,A,A,A, real(c), imag(c));
mfprintf(fd,'%e\t %5.2e\n %s\n %5s\t %10s\t %15s\t %20s\t\n',...
A,A, text, text, text, text, text);
// Close the opened file:
//-------------------------mclose(fd);
Remembe
r to close!
No
optional
text is
used in
any of the
cases
mfscanf(), fscanfMat()
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
17. Animation
A brief introduction to
creating dynamic graphics
Return to Contents
Introduction
Demo 1 (1/4):
Introducing pixmap &
xfarcs()
This demo is adapted from Antonelli & Chiaverini. It exhibits
The script uses the xfarcs() function to fll the moving pie.
Related Scilab functions are xfarc(), xarcs(), and xarc()
xfarcs() is used instead of xfarc() because the latter has no
provision for defning plot color by arguments, and its Axes
handle gca() does not recognize any children that would
allow colors to be defned
*) Also called double buffer mode because the picture is first created in one
buffer before being pushed to the second (the Graphics Window).
Demo 1 (4/4):
discussion
clear,clc,clf();
f=gcf();
f.pixmap='on';
// Double buffer mode
f.pixel_drawing_mode='nor';
// NOR mode
f.background=color("lightblue");
ax=gca();
ax.data_bounds=[0,-4;14,10];
// Plot limits
ax.margins=[.1 .1 .1 .1];
// Plot framed
ax.background=color("lightgrey");
max_pos = 10;
// Max position of rectangles
k=%nan;
// Auxiliary parameter
xfrect(k,k,4,4);
// First black rectangle
e1 = gce();
xfrect(max_pos-k,max_pos-k,4,4); // Second
rectangle
e2=gce();
for k=linspace(1,10,200)
// Animation
loop
e1.data(1:2)=k;
e2.data(1:2)=max_pos-k;
show_pixmap()
//Show double buffer
end
Demo 3 (1/3): a 3D
object, script (1/2)
// rotating_surface.sce
// The 3D surface is first rotated and then /
// tilted, after which its position is locked
/
clear,clc,clf;
// Initialize:
//-------------f=gcf();
f.pixmap="on";
clear_pixmap();
t=%pi/20*(-20:20); // Bounds & mesh resolution
// First plot command, defines labels:
//------------------------------------------------plot3d1(t,t,sin(t)'*cos(t),%nan,%nan,..
'x_axis@y_axis@z_axis');
Demo 3 (2/3): a 3D
object, script (2/2)
Demo 3 (3/3): a 3D
object, plot
The surface has
reached its destination:
rotated to 100
(azimuth) and tilted to
80 (elevation)
While testing various
parameters I saw this
message on the
Console (long list). It
disappeared when I rerun the script
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
..
at
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
18. Miscellaneous
A hotchpotch of philosophy
and realism that hopefully is
of use
Return to Contents
The problem-solving
process
The problem-solving process for a computational problem
typically goes through the following steps (not a textbook
defnition):
1.
2.
3.
4.
5.
6.
Good program
structures
Programming pitfalls
(1/4)
*) The term bug, according to anecdote, was coined in 1947 when Grace
Hopper (Grandma Cobol) of the US Navy identified a computer problem
being caused by a moth in a relay (/tube/connector, the story varies). The
original bug was thus a hardware related problem and lethal to the bug.
Programming pitfalls
(2/4): error types
Programming pitfalls
(3/4): error messages
Incompatible vector
lengths would be a better
error message
This message
is misleading if what
Inconsistent
you intend is [] * [], but ok if you
addition. multiplication
aim at elementwise
!--error 8
[] .* [] (but Wrong multiplication
is better still)-->[1 2 3] + [4 5]
Inconsistent
multiplication.
!--error
10
-->[1 2 3] * [4 5Here
6] you can see that the warning redefning
function does have a meaning. I have improperly
used sqrt as a variable name, but Scilab
76.
recognizes it is a built-in function. The answer is
correct, but one should rather change the variable
name. Check help name if you are uncertain if an
sqrt =
intended variable name is reserved
Programming pitfalls
(4/4): the endless loop
I have several times
mentioned the risk of creating
an endless loop, so lets look
at this little beast
When you execute the script
you have to crash the program
to stop it. The easiest way is
to press the Close button on
the Console and then reload
Scilab
Why does the loop not end?
Because we die from old age
before the variable n by
chance gets exactly the value
0.5
// endless_loop.sce
// Demonstrates an endless loop.
// Execution ends only by crashing
// the program (click on the Close
// button (X) on the Console)
n = .1;
dt = getdate();
rand('seed',1000*dt(9) + dt(10));
while n ~=0.5;
n = rand(0,'normal');
end;
disp(n)
/
/
/
/
Debugging (1/2)
Debugging (2/2):
validation
Speeding up Scilab
(1/4): introduction
Speeding up Scilab
(2/4): vector-based
functions
// add_demo1.sce
clc;
add = 0;
i = 0;
while ( i < 100 )
i = i + 1;
if ( modulo( i, 2 ) == 0 )
then
continue;
end
add = add + i;
end
disp( add )
2500.
// add_demo2.sce
clc;
add = sum(1:2:100);
disp(add)
2500.
Speeding up Scilab
(3/4): execution time
tic()..toc()
// measure_time1.sce
clear,clc;
x=[];
// Initate vector
y=[];
// Ditto
tic();
// Start stopwatch
for t=0:0.0002:2*%pi
x=[x; t];
y=[y; sin(t)];
end
time=toc(); // Stop watch
disp(time) // Display time
// measure_time2.sce
clear,clc;
tic();
t = (0:0.0002:2*%pi)';
[t,sin(t)]
disp(toc())
0.014
6. 17.389
0.2794155
4. 0.7568025
2.
0.9092974
0.009
0. 0.
Speeding up Scilab
(4/4): two more ideas
Replace loop by ones ():
tic();
77.481
for i = 1:100000
x(i) = 1;
end
disp(toc())
tic();
x = ones(100000,1);
disp(toc())
0.005
!k = 200660 !
!time = 10.142 !
tic();
k = 0;
for i = 1:1000000
x = rand(1,1);
if x < 0.2 then
k = k + 1;
end
end
disp(['k =' string(k)])
disp(['time =' string(toc())])
tic();
k = length(fnd(rand(1000000,1) < 0.2));
disp(['k =' string(k)])
disp(['time =' string(toc())])
!k = 199649 !
!time = 0.298 !
Discrepancy in time
measurements (1/2)
I wanted to check Scilabs computation time for a cased
given in a textbook on Matlab by Hahn & Valentine. First I did
it on the Console and then on the Editor, but the results did
not match:
The result is
// scilab-matlab_loop.sce
97.531 seconds on
the Console.
clc;
tic();
Clearly not true
s = 0;
because the
for n = 1:100000
answer came up
s = s + n;
end
without delay
time = toc();
It is only 0.453 s
disp(time)
when done on
the Editor. Thats
more like it
97.531
Discrepancy in time
measurements (2/2)
And here is the same in vectorized form:
Now the Console
tells of a threefold
improvement in
computation time,
but still not true
// scilab-matlab_vectorized.sce
clc;
tic();
n = 1:100000;
s = sum(n);
time = toc();
disp(time)
The bug (Scilab bug #8942) remains unsolved and its true
influence is unknown to me. The Scilab team gives the unhelpful
suggestion to download the mentioned fle
hold on
ATOMS (6/6):
discussion of problems
Building a script
library
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Return to Contents
A sine plot
A slider for changing the angular
frequency of the plot
Two radiobuttons by which the
properties of the plotted graph
can be changed
An exit button that closes the
GUI
START
Any changes?
Yes
EXIT pressed?
Yes
Close GUI
END
No
Implemen
t changes
No
Go to the MAIN
program below if
you want to proceed
in a logical order
The frst
subroutine,
initial_GUI(),
creates the initial
sine plot within the
Graphics Window;
including title and
axes labels
The initial angular
frequency is
defned as 5 Hz
There is really
Ex 6-1:
script/
function update_radio()
new_GUI_data();
endfunction
// IF radiobutton click
// GOTO new_GUI_data()
Ex 6-1: discussion
// animation_pincon_m2.sce
//------------------------------------------------------------------------------/
// The script plots the track of a blue polygon (rectangle)
/
// with red border, as it turns around its axis while racing
/
// counterclockwise in a circular loop on a black
background.
/
// The rectangle can be chaged to a trapetzoid or other
shape
/
// by changing element values in the matrix polygon.
Changing /
// theta arguments in the matrix align gives different
effects
/
//------------------------------------------------------------------------------/
clear,clc,clf;
// Basic parameters:
//---------------------steps = 100;
// Steps per circular loop
blength = 0.6;
// Basic length of polygon
width = 0.3;
// Basic width of polygon
Ex 6-2: animation of a
waltzing polygon (2/4)
h=gca() declares h as a
handle
Ex 6-2: animation of a
waltzing polygon (3/4)
Ex 6-2: animation of a
waltzing polygon (4/4)
In this screenshot the
polygon (rectangle) has
made just over three
quarters of its
counterclockwise loop. At
the same time it has spun
2 times around its axis,
and has begun the last
turn. There are 100
position samples on a full
loop (steps = 100;) and it
completes in a few
seconds
clear,clc,clf();
// Plot function:
//-------------------Z = sin(x)'*cos(y);
Sgrayplot(x,y,Z)
grayplot
// Function to plot
// Smoothed
cos(y)
sin(x)
/
/
clear,clc,clf;
//
---- SUBROUTINE ---/
// The plot2d() function defines the figure, /
// xfarcs() adds colored sectors to the plot /
function create_sectors(r, angle, width, col)
plot2d(%nan,%nan,-1,"031"," ",[-1,-1,1,1])
arcs=[-r;r;2*r;2*r;(angle-width/2)*64;width*64];
xfarcs(arcs,col)
// Add sectors
xtitle('COLORED SECTORS')
endfunction
// ---- MAIN ---- /
// Define sectors:
//---------------------rad = [.9,.6,1,.5]
angle = [0,135,225,270]
width = [45,75,60,80]
colors = [2,3,5,7]
// Sector radii
// Sector midpoints
// Sector widths
// Color definitions
// Call subroutine:
//----------------------create_sectors(rad,angle,width,colors)
// ---- END MAIN ---- /
Finish
L2
x2
Start
L1
1
x1
Base motor
Elbow motor
Hand
b= T\d
%
% Equations of motion
L1 = 4;
L2 = 3;
t = linspace(0,2,401);
tq = [ t.^5; t.^4; t.^3 ];
theta1 = theta10 + a*tq;
theta2 = theta20 + b*tq;
x1 = L1*cos(theta1) + L2*cos(theta1 +
theta2);
x2 = L1*sin(theta1) + L2*sin(theta1 +
theta2);
%
% Plot path of hand
plot(x1,x2),...
xlabel(x_1),...
ylabel(x_2),...
title(Path of robot hand),...
text(4.3,0,t=0s: (x_1,x_2) = (6.5,0)),...
text(0.2,2,t=2s: (x_1,x_2) = (0,2))
following polynomial
expressions:
1(t) = 1(0)+a1t5+a2t4+a3t3+
+a4t2+a5t
2(t) = 2(0)+b1t5+b2t4+b3t3+
+b4t2+b5t
//
//
//
//
clear;clc,clf;
// Initial values, angles in degrees:
//--------------------------------------------tf = 2;
// Finish time
theta10 = -19*%pi/180;
// Theta 1 start position
theta1tf = 43*%pi/180;
// Theta 1 final position
theta20 = 44*%pi/180;
// Theta 2 start position
theta2tf = 151*%pi/180; // Theta 2 final position
// Equations for a coefficients (velocity
// constraints have been taken into account):
//-----------------------------------------------------------T = [ tf^5
tf^4
tf^3
5*tf^4 4*tf^3 3*tf^2
// Angular velocity
20*tf^3 12*tf^2 6*tf ]; // Angular acceleration
c = [ theta1tf - theta10; 0; 0 ]; // Theta 1 movement
a = T\c
// Coefficient vector a
disp(['Coefficients for theta1 motion:'])
disp([string(a')])
// Equations of motion:
//-----------------------------L1 = 4;
// Length of upper arm [feet]
L2 = 3;
// Length of lower arm [feet]
t = linspace(0, 2, 401);
// Computation steps
tq = [ t.^5; t.^4; t.^3 ];
theta1 = theta10 + a'*tq; // Base motor angular speed
theta2 = theta20 + b'*tq; // Elbow motor angular speed
x1 = L1*cos(theta1) + L2*cos(theta1 + theta2); // x1 positio
x2 = L1*sin(theta1) + L2*sin(theta1 + theta2); // x2 position
// Plot path of hand, add labels & legend:
//-----------------------------------------------------plot(x1,x2),..
xlabel('x_1'),..
ylabel('x_2'),..
title('PATH OF A ROBOT HAND'),..
h1 = legend(['START: t=0s, (x_1,x_2) = (6.5,0); ..
STOP: t=2s, (x_1,x_2) = (0,2)'], 3)
Example 6-6:
animation with planet
&Themoon,
task is to animateintro
a planet with a moon rotating
/ clear,clc,clf;
// **** SUBOUTINE **** //
// Attach defined points to the spheres:
function [x, y, z] = facet(v, h)
x = cos(v)'*cos(h);
// Facet x-matrix
y = cos(v)'*sin(h);
// Facet y-matrix
z = sin(v)'*ones(h);
// Facet z-matrix
endfunction
// **** MAIN **** //
// Define planet & moon variables:
//--------------------------------------------// Planet (p), 10x10 degree grid:
vp = linspace(-%pi/2,%pi/2,18); // 18 steps vertically
hp = linspace(0,2*%pi,36);
// 36 steps horizontally
rp = 2;
// Planet radius
Recalculate moon
location & push data
to frst buffer
show_pixmap() =
push plot to screen
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
20. Adieu
Final words to accompany you
in your struggle for survival of
the fttest
Return to Contents
We have reached the end of our journey. The road was longer
and bumpier than I anticipated
There is much more to Scilab but we are on our way if we master
even this material (think of an office software package and how
little of its potential you really know even if you use it daily)
The most important next step is to do Scilab simulations on our
own, to solve problems in our particular sphere of interest
And for everybodys sake, keep reminding the Scilab team about
the need for a comprehensive, up-to-date tutorial. To repeat an
old engineering adage: The job isnt done until the paperwork is
done!
All the best and take care
JH