Escolar Documentos
Profissional Documentos
Cultura Documentos
E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
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 Copyleft: This material is released under the only
condition that you do not put restrictions or a price
Johnny Heikell tag on your redistributionsmodified or notand
add this requirement to child copies.
www.heikell.fi Otherwise J. Heikell 2011
LinkedIn
Tribute to old gods
The best Scilab tutorials are non-English. The following are the ones
that I have consulted most for this work:
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.
1. Introduction
What is and why use Scilab?
Return to Contents
What Scilab is (1/2)
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.
Why people dont use
Scilab
The following are some comments about Scilab and open-source
software in general that I have come across:
Scilab? Never heard of it
Octave is closer to Matlab
As a company we have to use software that will be supported ten
years from now
It doesnt have the toolboxes that we need
There is a cost involved in shifting to a new software tool, even if
the tool is gratis
Training and documentation support is poor
There are no interfaces for other software tools that we use
It seems to be rather slow
*) 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 defined functions (UDF)
*) 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
ATOMS is Scilabs system for downloading
and installing user-developed toolboxes. It
has given me real gray hair
sound, but there is a risk with nerds that
have more zeal than ability and tenacity to
properly test their programs
Embedded information
Scilab learning obstacles
Learning Scilab can be frustrating to a person with limited previous
programming experience. The biggest hurdles are:
Lack of hands-on tutorials for English-speaking newbies. The
situation is better, though not good, with some other languages
Excessive number of Scilab functions. There are some two thousand
of them. There are often numerous options to select between; some
of which work, some dont, some of which you know, most you dont
Unhelpful Help Browser. Even when you have a hunch of which
function to use, you cannot get it right because of the Help Browsers
cryptic explanation
Basic programming errors. Creating infinite loops, dividing by zero,
using * instead of .* , etc. We all make them, there is no way around
them than by practicing. bung macht den Meister!
On the bright side...
Scilab works! Despite my complaints it mainly does a fine job
It is a great thing that it is given away for free to all of us who
cannot afford expensive commercial simulation tools
It is a great thing that it is give away for free to all commercial and
non-commercial institutions that care about cost-effectiveness
It is a free gift (though with restrictions*) to science and engineering
and deserves support of us who happily download whatever comes
gratis on the Web
It deserves support because Scilab, like other open-source IT
solutions, faces an uphill struggle against vast commercial interests
and skeptical individuals
Long live the free and open-source/access community!
*) 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
Return to Contents
Windows installation (1/3)
Menu bar
Toolbar
Command prompt
*) The Console has other names as well: Workspace, Startup/Main Window, etc.
Folks:
Shift Right/Left:
Indent/unindent a row by one
step (this pair should be on the
toolbar)
Comment/Uncomment Selection:
Add/delete a comment
Editor menu bar (3/5):
Preferences
Each
window
le
Conso Editor
part has an
arrow in
the upper
right-hand
corner, by
w which you
i n d o
B r owse r p h ics W can release
Help G ra it from
docking
On scripts and functions
Scilab has two command types:
Scripts. A set of commands used to automate computing. Script
commands are normally returned to the Console, but plots are
returned to the Graphics Window
Functions (macros). Short programs that interface with the
environment through input and output variables. A list of
common built-in functions is given on the next slide. Functions
defined by the user can either be local (integrated in a script) or
global (stored as a separate file and accessible to any script)
I may use the term code to make general references to either
scripts or functions
As was already saidand will repeatedone should rather
create scripts and functions on the (Text) Editor (SciNotes)
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).
%i i = -1 Imaginary unit
%pi = 3.1415927. Pi
%e e = 2.7182818. Napiers constant e
%eps = 2.22 10-16 Precision (machine dependent)
%inf Infinite (not mathematically infinite)
%nan Not a Number
%s s Polynomial variable
%z z Polynomial variable
%t, %T true Boolean variable
%f, %F false Boolean variable
Scilab operators (1/2)
The list contains the majority of operators used in Scilab. Many will be
explained in detail later.
*) Both simple (') and double (") quotes are allowed to define character strings
Scilab operators (2/2)
-->f = gcf()
The function plot2d() f =
produces the plot below
The command gcf() gives Handle of type "Figure" with properties:
========================================
the list to the right children: "Axes
The list is the handle for the figure_position = [567,485]
defined function (Scilab figure_size = [628,592]
axes_size = [610,460]
literature also refers to auto_resize = "on
individual rows in the list by viewport = [0,0]
the term handle) 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
The term foo is used in many tutorials. It may be confusing
if you are not intimately familiar with programming
Simply stated, foo can be interpreted as something comes
here. The professional expression is placeholder name, also
referred to as metasyntactic variable
Example:
for k = 1:2:n
foo;
end
Return to Contents
Console keyboard
shortcuts
Keyboard shortcuts allow
speedier execution of
commands, but require
frequent use to stay
memorized
The command
who (+ Enter)
produces a list of
some Scilab
variables. At least
on my Windows
Vista laptop the
columns are right
aligned (French
logic or a bug?).
Note that variables
from the previous
example are
displayed
List of variables (2/2)
a =
Displaying graphics
The Console can also be
used to give commands for
plotting graphics:
--
>plot3d(x,y,sinh(x')*
cos(y))
The-->y = linspace(-
graphical picture is
%pi,%pi,40);
plotted in the Graphics
-->x =that
Window linspace(-%pi,
pops up
%pi,40);
automatically (more in Ex. 1)
The meaning of the entered
code will become clear as we
proceed
Command line editing
Suppose we make a mistake when
entering the command line and
Scilab returns an error message
Instead of retyping the whole line,
we can press the up arrow ( ^ |) on
the keyboard to return the line
^
| Press up
and correct the mistake
-->a = 2; b = sqt(a) arrow
In the shown example the
function for the square root, sqrt(), Correct
was first erroneously typed sqt()
1.4142136
b =
Note that this is just one of -->a = 2; b = sqrt(a)
several alternatives for command Undefined variable: sqt
line editing !--error 4
-->a = 2; b = sqt(a)
Editing demo
-->s=.5; log(s^2-2*s*cos(%pi/5)+1)
Evaluate the function ans =
-->s=.95; log(s^2-2*s*cos(%pi/5)+1)
for s = 0.5, 0.95, and 1 ans =
- 1.006851
Do not rewrite the function, use -->s=1; log(s^2-2*s*cos(%pi/5)+1)
instead the up arrow to edit ans =
previous commands! - 0.9624237
Complex numbers -->x = 2 + 3*%i;
1. + 4.i
3.
The variable %i stands for -1
-->z2 = x * y
z2 =
The first example shows how
Scilab evaluates some functions 5. + i
with the complex argument x =
2 + 3i 0.9827937 -->z3 = x / y
ans = z3 =
An imaginary sin() argument -->atan( imag(x), real(x) )
- 0.5 + 2.5i
produces a result! 9.1544991 - 4.168907i
ans =
The second example shows how -->sin(x)
Scilab does arithmetic ans =
operations with two complex -->imag(x)
equations, x and y 2.
ans =
-->real(x)
3.6055513
Vectorized functions
Scilab functions are vectorized, meaning that
-->t = [0:5]'
-->p=1+2+3+4+5+6+7+8+9+10+11+12+...
Long command expressions -->13+14+15+16+17+18+18+19+21+22+23+24+25
can be divided among two or p =
more lines
323.
z =
Poles and zeros: plzr()
-->s=%s;
The plzr() function -->sys=syslin('c',((1+2*s)*(1+3*s))/(s*(s*s+s+1)));
plots the poles and -->plzr(sys)
zeros of a polynomial
The syslin() function
used here will be
discussed later
When pressing Enter
after the plzr(sys)
command, the
Graphics Window
opens and displays the
plot (The Graphics
Window will be
discussed in Example
1-1)
Gadgets (1/2): calendar
-->calendar(2013,6)
ans =
Among Scilabs built-in gadgets
is a calendar. The command ans(1)
calendar(y,m) ans(3)
4. Examples, Set 1
Demonstration of basic Scilab
programs
Return to Contents
Example 1-1: script for a
simple plot
Lets elaborate on the
example from Scilab in 15 // plot1.sce
minutes
We work with the Editor // A simple 2D plot of a sine function /
// with the abscissa x = 0 ... 10, /
using the same script as // and amplitude A = increases with x /
before, but with added // The function itself is y(x) /
comments
x = [0:.1:10]; // The abscissa x is a row vector
Save the function when it A = 0.5*x; // Modulated amplitude, row vector
has been typed in. I call it y = A.*sin(2*x); // Element-by-element multiplication
plot1.sce and have saved it plot(y) // Plot command
on my USB thumb drive,
you can save it wherever
you like
To run the script, Click on Note: Comments begin with a double
the Editors Execute icon slash (//). Scilab disregards everything
What happens is shown on behind the // when it executes the code
the next slide
Ex 1-1: the Graphics
Window
As seen before,
Scilab uses a
third window,
the Graphics
Window, to
present the plot
Information on
the executed
script is echoed
to the Console.
Error messages
are also
displayed on
the Console These three are the windows that we mainly work
with, but there are more. You have already seen a
few like the Help Browser and Variable Browser
Ex 1-1: using the Console
The script could also be
executed from the Console
After the command prompt,
type
exec plot1.sce
Up pops the
Graphics
Window with a
plot of the
defined
function...
while the script
is echoed to the
Command
Window
(Console)
Ex 1-1: comments (1/4),
command details
Editor contents will from // plot1.sce
now on be shown on light
// A simple 2D plot of a sine function /
green background // with the abscissa x = 0 ... 10, /
// and amplitude A = increases with x /
// The function itself is y(x) /
The vector definition
x=[0:0.1:10] can be x = [0:.1:10]; // The abscissa x is a row vector
interpreted as from 0 to 10 A = 0.5*x; // Modulated amplitude, row vector
y = A.*sin(2*x); // Element-by-element multiplication
in steps of 0.1 plot(y) // Plot command
memory*
clc, cleans the Console; the
echo signal is mainly erased Thus our final script looks like this. Pay
clf, wipes an open Graphics attention to the semicolon (;) at the end
Window of each expression apart from the last
*) Careful with clear, it may cause havoc in some cases (there will be a demo on
this later)
Example 1-2: the task, a
decaying linear chirp
Write the script for a linearly frequency modulated sinusoidal
signal s(t), i.e. a linear chirp of the type
// f-modulation1.sce /
The linspace() function creates
a linearly space plotting vector // Plots a sinusoidal function of the type /
with the arguments from, to, // s = A(t)(sin(wt+x(t)+phi)), where w = angular /
// velocity, x(t) = frequency modulation, phi = /
number of points. The default // phase shift, and A(t) = amplitude /
value is 100 points, but more are
needed here clear, clc, clf;
f = 1; // Frequency
w = 2*%pi*f;
phi = %pi/4; // Initial phase shift
Here is the Dot Operator (.*) fin = (4*%pi)/w; // End of plot
again t = linspace(0,fin,1000);
A = 2*exp(-t);
s = A.*sin(w*t + 10*t^2 + phi);
The plot2d() produces the 2D plot2d(t,s,5)
plot. The arguments t and s
stands for the x and y-axes, the
number 5 produces a red graph Note: fin is used as the end of plot
variable name because end is
reserved (Scilab keyword)
Ex 1-2: plot
plot2d() is a more
versatile function
than plot(), which
is similar to the plot
function in Matlab
Ex 1-2: improved plot
// f-modulation2.sce
Here I have
added code // Plots a sinusoidal function of the type /
// s = A(t)(sin(wt+x(t)+phi)), where w = angular /
to plot the // velocity, x(t) = frequency modulation, phi = /
grid, xgrid(), // phase shift, and A(t) = amplitude /
title, xtitle(), clear, clc, clf;
and x and y f = 1; // Frequency
w = 2*%pi*f;
labels, phi = %pi/4 // Initial phase shift
xlabel(), fin = (4*%pi)/w; // End of plot
t = linspace(0,fin,1000);
ylabel(). A = 2*exp(-t);
Crude, but it s = A.*sin(w*t + 10*t^2 + phi);
plot2d(t,s,5)
works
xgrid()
xtitle('SINUSOIDAL PLOT')
xlabel('t')
ylabel('Amplitude')
Ex 1-2:
printing
Scilabs windows (Console, Editor,
Graphics Window) all have both
normal and advanced print functions
One way of getting a coherent
printable document is to copy the
contents of the windows and paste
them into a word processing page
(Scilab supports LaTeX)
The image shown here was done on
MS Word (OOo Writer did not
recognize Scilabs file type). It was
then printed as .PDF, saved as a
.PNG file, and finally cropped with
MS Picture Manager
Thats a tedious method. Consult
Help for advanced print features
Ex 1-2: checking
To show that the frequency is
// f-modulation3.sce /
linearly modulated, we can
add frequency as a function of // Plots a sinusoidal function of the type /
t to the plot // s = A(t)(sin(wt+x(t)+phi)), where w = angular /
// velocity, x(t) = frequency modulation, phi = /
For that we add the function // phase shift, and A(t) = amplitude. Second /
f_mom to the script // plot for momentary frequency values /
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.
Ex 1-3: task 1, saving
This script
(function) differs a
bit from the earlier
ones, so lets go
through the save
operation:
Save the script as
lotto.sci in your
preferred file
Next, Click on the
Execute icon of
the Editor to load
the saved file into
Scilab
Continues on next
slide
Ex 1-3: task 1, running
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
-->round(-2.7), round(2.7)
of four rounding functions in Scilab: ans =
round(), fix() (or int()), floor(), and
- 3.
ceil() ans =
3.
ceil() rounds up
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Return to Contents
Introduction
As Scilab is built around matrices we are forced to use them
Scilab stores numbers (and characters) in matrices
A matrix can be seen as a table, consisting of m rows and n columns
(mxn matrices, also denoted ixj matrices)
Scalar variables do not exist per se, they are treated as 1x1 matrices
The general form of a Scilab matrix (here 3x3 matrix) is
A = [11 12 13; 21 22 23; 31 32 33]
Row elements can also be separated by commas:
A = [11, 12, 13; 21, 22, 23; 31, 32, 33]
In both cases semicolons separate rows
The next page shows both alternatives for the 3x3 matrix
[The vector] has never been of the slightest use to any creature.
Attributed to Lord Kelvin
The 3x3 matrix
-->rand(4,4)
1. 1. ans =
3x2 matrix 1. 1.
of ones 0.2312237 0.3076091 0.3616361 0.3321719
0.2164633 0.9329616 0.2922267 0.5935095
0.8833888 0.2146008 0.5664249 0.5015342
0. 0. 0. 0.6525135 0.312642 0.4826472 0.4368588
0. 0. 0.
-->rand(4,4,'normal')
2x3 zero E = ans =
matrix -->E=zeros(2,3)
1. 1. - 1.3772844 - 0.6019869 - 0.3888655 - 0.7004486
0.7915156 - 0.0239455 - 0.6594738 0.3353388
D = - 0.1728369 - 1.5619521 0.6543045 - 0.8262233
-->D=ones(3,2) 0.7629083 - 0.5637165 - 0.6773066 0.4694334
1. 0. 0.
C =with square brackets, [], while parentheses, (), are
Matrices are defined
used to cluster function arguments
Basic matrix calculations
-->A = [1 2 3; 4 5 6]; B = A; C = A + B -->A = [1 2 3; 4 5 6]; B = A'; C = A * B
C =
2. - 1.
1. 1.518D-16 - 2.5 1.5
3.795D-15 1.
H =
-->prod(A, 'c')
prod(A, c) returns the product ans =
of each row as a column vector
6.
120.
prod(A) returns the product of 504.
all matrix elements
-->prod(A)
ans =
362880.
min(), max() -->A=[3 0 1; 2 2 7; 5 9 4]
A =
3. 0. 1.
2. 2. 7.
5. 9. 4.
-->max(A, 'c')
max(A, c) returns a column ans =
vector containing the biggest
elements in each row 3.
7.
9.
Min/max position & value
A variation of the min() and max()
-->A = [5 3 1; 2 4 6];
functions allow us to determine the
-->[min_val min_pos] = min(A)
position and value of the smallest alt.
largest matrix element
-->A = [1 2 3 4; 5 6 7 8];
-->size(A)
The function size() can be used
to find out the size of a matrix 2. 4.
4. 1. ans =
The answer is given as the ans =
number of rows and columns (in -->size(v2)
that order) 1. 4.
-->[n,m] = size([1 2 3; 4 5 6])
ans =
When row and column variables -->size(v1)
are named, the answer is given
in alphabetic order (here 2.
columns first) n =
3.
Matrices with string elements m =
(strings were used in the dialog -->size(['You' 'Me'; 'Alpha' 'Beta'; 'Two' 'Three'])
box in Ex 1-3 and will be
discussed in detail later) are 3. 2.
treated the same way ans =
length()
-->X = [9 1 8; 2 7 3; 6 3 5];
The function find() identifies and
returns the row locations of those -->find(X<5)
matrix elements that satisfy the ans =
Boolean condition stated in the
argument 2. 4. 6. 8.
1. 2. 3. 4. 5. 7. 9.
gsort()
-->matr = [-1 4 -2 2; 1 0 -3 3; -4 5 0 -5]
Scilab does not recognize Matlabs matr =
sort() function (it used to before
version 5.3). Instead we must use - 1. 4. - 2. 2.
1. 0. - 3. 3.
gsort(), which is different but serves - 4. 5. 0. - 5.
the same purpose
-->s_matr = gsort(matr)
s_matr =
As shown to the right, gsort()
picks out matrix elements in 5. 2. 0. - 3.
decreasing order and returns them 4. 1. - 1. - 4.
3. 0. - 2. - 5.
column by column
-->testmatrix('magi',5)
Additional matrices that can be ans =
determinant
The determinant of Drers magic
square is zero (the matrix is singular),
but as shown, the rounding error
prevents Scilab from returning the
exact answer (recall that we 0.
encountered this problem before) ans =
To get rid of the rounding error we -->clean(det(M))
can use the clean() function. It - 1.450D-12
ans =
returns zero for values below 1e-10
-->det(M)
4. 14. 15. 1.
9. 7. 6. 12.
Deleting rows and
columns
-->m = [16 3 2 13; 5 10 11 8
Rows and columns can be deleted by --> 9 6 7 12; 4 15 14 1]
using a pair of square brackets m =
16. 3. 2. 13.
5. 10. 11. 8.
We start with the 4x4 magic square, 9. 6. 7. 12.
4. 15. 14. 1.
denoted m because we shall distort it
-->m(:,3) = [] delete
m =
We first delete the third column. The 16. 3. 13.
Colon Operator argument is used to retain 5. 10. 8.
all rows, the argument 3 points to the 9. 6. 12.
delete
4. 15. 1.
third column. The result is a 3x4 matrix
-->m(2,:) = []
m =
In the second instance we delete the 16. 3. 13.
second row, to end with a 3x3 matrix 9. 6. 12.
4. 15. 1.
Changing rows and
columns
The logic on the previous slide can be used
to changing rows and columns m =
16. 3. 13.
9. 6. 12.
We start from the previous 3x3 matrix 4. 15. 1.
-->m(2,:)=[0 0 0]
First change elements in the second row to m =
16. 3. 13.
zeros 0. 0. 0.
4. 15. 1.
Then we change the last column to ones
-->m(:,3)=[1 1 1]'
(note transpose) m =
16. 3. 1.
0. 0. 1.
These operations can also be seen as 4. 15. 1.
inserting a defined row/column vector in
place of an existing row or column
Addressing matrix elements
by linear indexing
-->M=testmatrix('magi',4)
Scilab regards matrices as column vectors.
This allows us to address matrix elements in
5. 11. 10. 8. a simplified way
9. 7. 6. 12.
4. 14. 15. 1.
We start from the 4x4 magic square
16. 2. 3. 13.
M-->M(14)
=
Then we pick out the element (2,4), which
is number 14 if you count along the columns
0:%pi/36:%pi
5. 11. 10. 8.
Meaning: Starting at 0, step by 9. 7. 6. 12.
4. 14. 15. 1.
/36 up to
The first example shows that
the truncated form 1:8 7.
produces a row vector with
increment 1. The second shows 14.
how to refer to rows 3-4, K =
column 2, of the magic square -->K = M(3:4,2)
16. 2. 3. 13.
M =
Operators (2/4):
more examples with (:)
The second example on the previous slide was a case of subscript
manipulation of the type M(i:j,k), where i:j refers to the i:th to j:th rows
and k to the k:th column
There is often need to address part of a matrix. The idea should be
understood well. Below are three more examples
Note that the Colon Operator alone refers to the entire row or column
4. 14. 15. 1.
7. 6. 15. 9. 7. 6. 12.
11. 10. 6. C =
10.
A = 3.
-->A = M(2:3,2:3) B =
Operators (3/4):
the $ Operator
The $ Operator refers to the last value, -->M = testmatrix('magi',4)
$-1 to the value next to the last, etc. M =
The example to the right shows some 16. 2. 3. 13.
uses of the $ Operator 5. 11. 10. 8.
The $ Operator can be used to flip the 9. 7. 6. 12.
4. 14. 15. 1.
order of elements in a vector, as
shown below (an alternative method -->M($)
was demonstrated in Ex 1-3, Task 1) ans =
1.
-->M(1:$-1,$)
ans =
-->v = [3 4 5 6 7 8 9];
-->v($:-1:1) 13.
8.
12.
9. 8. 7. 6. 5. 4. 3.
ans =
Operators (4/4): the
Backslash Operator (\)
Backslash (\) denotes left matrix division. x=A\b is a solution to
A*x=b , which is important e.g. in control engineering
-->n = 4;
Assume that we have the column
-->A = m(:, ones(n,1))
vector m = (2:2:6); meaning that it A =
has three rows
2. 2. 2. 2.
4. 4. 4. 4.
We want to form a 3x4 matrix where 6. 6. 6. 6.
each column consists of the vector m
6 3
= 61 32 = 0 , meaning that it is singular
2 1
Elements: 1 2 3
Example 2-4 shows an additional application of strings
Strings (2/6): disp(),
string()
The most usual string display -->a = 125;
command is disp(), where the -->disp(['Was it ' string(a) 'that you said?'])
text has to be in quotation
marks: disp(text) or !Was it 125 that you said? !
disp([text])
Numeric data can be added to -->b = 521;
disp([]), but has to be -->disp(['No, I said ' mtlb_num2str(b) '!'])
converted to strings using the
function string() !No, I said 521 ! !
Scilab knows Matlabs conversion
command num2str(), but in the
form mtlb_num2str() -->disp('in action', 'LIFO', 'This is')
Leave out the square brackets
and the elements are displayed
as a column, starting with the last in action
(Last In First Out) LIFO
Commas are optional with square This is
brackets, but not with brackets
only
Strings (3/6): disp() vs.
mprintf()
-->disp('in action', 'LIFO', 'This is')
!z v+w !
Symbolic manipulation of mathematical ! !
!0 z*y-x*(v+w) !
objects can be performed using matrices
of character strings -->x=1; y=2; z=3; v=5; w=4;
-->evstr(tsc)
In the shown cases the function ans =
trianfml() performs symbolic
3. 9.
triangularization of the matrix sc, and the 0. - 3.
function evstr() evaluates the expression
tsc
Arrays: general
The term array refers to any
systematic arrangement of objects,
usually in rows and columns
(numeric arrays, diode arrays, + addition
antenna arrays, etc.)
- subtraction
Arrays have some important uses, .* multiplication
e.g. for building tables ./ right division
Arithmetic operations on arrays are .\ left division
done element-by-element, meaning .^ power
that addition and subtraction are
the same for arrays and matrices . unconjugated array transpose
matrices element-by-element to
form a 2x2 matrix of quotients
Right and left division
As shown in the table above, Scilab -->A = [1 2; 3 4]
allows left and right element-by- A =
element division (.\ and ./ 1. 2.
respectively) 3. 4.
The difference between the two is -->B = [5 6; 2 -3]
which of the two division elements is B =
the numerator and which the
5. 6.
denominator 2. - 3.
As shown by the examples, left
-->A.\B
division means that the element in the ans =
left matrix becomes the denominator,
with right division it is the nominator 5. 3.
0.6666667 - 0.75
-->A./B
The exponent function exp() is a ans =
special case in being defined as an
0.2 0.3333333
element-by-element operation 1.5 - 1.3333333
Dot Operator pitfalls
-->A = [1 2 3 4];
In practical simulations Scilab often
-->B = 1./A
flashes error messages due to wrong use B =
of the Dot Operatoror the absence of it
0.0333333
0.0666667
A particular problem is division with an 0.1
integer in the nominator. As shown to the 0.1333333
-->E = (2).*A
This is not an issue with multiplication E =
2. 4. 6. 8.
A few more functions
(1/5): modulo()
-->modulo(3,2) -->n=[1,2; 10,15]; m=[2,2; 3,5];
Then command modulo(n,m) -->modulo(n,m)
computes the reminder of n
divided by m (where n and m are
integers) 1.
ans =
1. 0.
With matrices modulo() computes 1. 0.
the reminder element-by-element
ans =
modulo() comes handy e.g. when x=input('Give a number :');
we need to check if a number is if modulo(x,2)==0 then
even or odd (the if-then-else- disp('Number is even');
else
end construct will be discussed in disp('Number is odd');
Chapter 11) end
subplot(132);
histplot(x,Exp,5)
legend(['Exponential'])
subplot(133);
histplot(x,Poi,13)
legend(['Poisson'])
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
6. Examples, Set 2
Adds to what we have learned
so far
Return to Contents
Example 2-1: solving an
equation system
The task is to solve the following system of equations:
x1 + 2x2 x3 = 1
-2x1 6x2 + 4x3 = -2
-x1 3x2 + 3x3 = 1
A = [1 2 -1; -2 -6 4; -1 -3 3];
In this case it can be done by b = [1; -2; 1];
making sure that the residual x = A\b
B Ax is exactly zero
// algebra1_check.sce /
// Make sure that b - Ax = 0 / x =
The altered code is renamed
algebra1_check.sce and saved residual = b - A*x
before being executed
R11 = 10
R22 = 12
R33 = 18
C = 1 0 , D = 0
Note the use of the function scf(number) (set current figure) to produce
two plots
Ex 2-3: comments (1/3)
Apart from demonstrating matrix operations, this example
introduced a number of new concepts:
definition of a linear system with the syslin() function, in which
the string c as input argument denotes continuous. The
initial state x0=[0;0] is not needed since x0=0 is the default
value, but it is there if we want to make changes
Scilab lacks a unit step function; the constant input signal is
constructed with a unit vector (using ones()) of length = t
simulation of the defined system was done by the csim()
function, with u, t, and sys as input arguments
csim() produces the output arguments y and x, which are used
by the plotting commands. Check Help for a detailed explanation
two plots are created since, with this particular system, x and y
would otherwise overlap. x and x are plotted automatically
the ax1=gca() and ax1.grid=[2,5] pair of commands tells that
we want a grid with blue vertical and red horizontal lines
Ex 2-3: comments (2/3)
For a linear system, we can use either a transfer function or state-
space representation. Their differences:
In common are block diagrams and their manipulations, poles and zeros
Ex 2-3: comments (3/3)
It is possible to shift between transfer functions and state-
space representation:
Return to Contents
The Graphics Window
Note: The Demonstration
feature has a good presentation
of plotting functions, but it also
contains obsolete ones
grayplot()
errbar()
plot3d()
fplot3d1()
Axes Editor
// multiple_plot.sce
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)')
Note: plot2d() h
plot2d(): syntax
as
also a slightly
different old syn
tax
The plot2d() syntax can be used as a guide for some other plot
commands, e.g. for fplot2d()and histplot()
plot2d() has the following arguments:
plot2d(logflag,x,y,optional arguments)
clear,clc,clf;
style = 5 produces a red graph
leg is empty (' ') in sine plot
x = 0:0.1:2*%pi; // x axis definition
y1 = sin(x); // Function 1
y2 = cos(x); // Function 2
style=-9 produces circle marks
style1 = 5; // style for sin A legend is added to the figure with the
strf1 = '174'; // strf second plot command
rect = [0,-1.2,2*%pi,1.2]; // rect
nax = [4,%pi,4,7]; // nax
plot2d(x,y1,style1,strf1,' ',rect,nax)
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):
plot2d(): demo with
matrices
The simple script below demonstrates the
plot2d() command when arguments x and
y are matrices, and the style is 1 and -1
scf() is used to
open a new -->x = [.5 .7 .9 1.3 1.7 1.8]';
Graphics
Window.
Otherwise the + -->scf();
marks of the
-->plot2d(x,y, style=-1)
second plot2d()
-->plot2d(x,y, style=1)
command would
-->y = [.1 .2 .75 1.5 2.1 2.4]';
be on top of the
first one
The command is clearer if arguments are
written in plain (style=-1) but, a shown in
earlier demos, the number alone is enough
fplot2d()
Below well plot a 3D graph of the sinc function sin(x)/x, using some of
the surface definition capabilities of plot3d()
clear,clc,clf;
x = linspace(-10,10,50);
y = linspace(-10,10,50);
[X,Y] = ndgrid(x,y); //Create array for xy grid
Z = 50*sin(sqrt(X.^2 + Y.^2))./sqrt(X.^2 + Y.^2);
plot3d(x,y,Z,leg="X@Y@Z",flag=[4,2,4])
If you click on the display button for surf() in the Help Browser, Scilab
first displays a number of alternatives and then crashes.
Contour plots: contour()
Lets return to the expression z = (2*x2 y2)exp(-x2 0.5*y2),
and plot its 2D contour (level/height curves)
It only requires the scripts plot command to be changed
// 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);
contour(x,y,Z,10)
Vector fields: champ()
The 2D vector field for the expression z = (2*x2 y2)exp(-x2 -
0.5*y2) can be visualized by changing the plot expression to
champ(), and adjusting the intervals in the linspace() functions:
// vector_field.sce
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)
Mixed contours and
vector fields
Vector fields 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
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);
champ(x,y,X,Y)
contour(x,y,Z,10)
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 defining the plane in case (below y =
-1) and by returning to 2D plotting:
// cutting.sce
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)
Mixed 2D/3D plots (1/2):
script
Scilab has its own ideas of what it should do if a contour() command
is added to the script of a 3D plot command (plot3d(), surf()). Trial
and error is needed
// hole.sce
clear,clc,clf;
function z = f(x, y)
z=2*x^2+y^2;
endfunction
x = linspace(-1,1,50);
y = linspace(-2,2,100);
z = (feval(x,y,f))'; // Evaluate function
z(75:90,20:35) = %nan; // Definition of hole There is Polish logic behind
surf(x,y,z) // Plot surface the z arguments that asks for
trial & error to get it right
subplot()
Subplots are a way of presenting multiple graphs on a single frame
The function subplot(m,n,p), or (mnp), splits the Graphics Window
into m rows and n columns, and the subplot in case occupies
position p. In the case of four subwindows, subplot(22p), the
position of p is as shown:
p=1 p=2
p=3 p=4
// subplot.sce x=linspace(-2,2,10);
y=linspace(-3,3,10);
// Presents different aspects of / [X,Y]=meshgrid(x,y);
// the function / Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2);
// z=(2x^2 - y^2)exp(-x^2 - 0.5y^2) / subplot(223)
// in four subplots / champ(x,y,X,Y)
clear,clc,clf; x=linspace(-2,2,50);
x=linspace(-2,2,30); y=linspace(-1,1,0);
y=linspace(-3,3,30); [X,Y]=meshgrid(x,y);
[X,Y]=meshgrid(x,y); Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2);
Z=(2*X.^2-Y.^2).*exp(-X.^2-0.5*Y.^2); subplot(224)
subplot(221) plot2d(X,Z,5)
surf(X,Y,Z)
subplot(222)
contour(x,y,Z,10) Note that only the plot function
has been repeated for (222)
subplot(): demo plot
There is
another
function for
subplots:
xsetech().
Check with
Help for
details
plot2d2(), plot2d3(),
plot2d4(): demo, script
// plot2dx.sce
subplot(224);
plot2d4(x,sinc(x),style=2) // Plot arrow style
xtitle('plot2d4')
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 are graphical presentationtypically rectangles
of one-dimensional data
Scilabs main function for plotting histograms is:
histplot(x,data,opt_arguments)
Bar diagrams, a common form of histograms, are given by:
bar(x,y,width,color,style)
or, for horizontal bars:
barh(x,y,width,color,style)
3-dimensional bar diagrams can be created by the command:
hist3d(z,opt_arguments)
and with added x and y vectors:
hist3d(list(z,x,y),opt_arguments)
Check Help for more details
Histograms: demo, script
The script(s) below are intended to demonstrate different
types of histograms, presented as (22p) subplots
// histogram_subplot.sce subplot(223)
hist3d(5*rand(8,4)) // 3D histogram
// Demonstration of histogram types /
// using subplots / subplot(224)
z=10*rand(3,4);
clear,clc,clf; x=[1 3 5 6];
subplot(221) y=[1 2 7 11 20];
data=rand(1,10000,'normal'); hist3d(list(z,x,y)) // 3D hist, add x/y vectors
histplot(20,data) // Traditional histogram
subplot(222)
y=[1 3 5 6 8];
z=[y;4 3 2 2 1]'; // Transpose necessary! The list() argument defines the
bar(z,0.7,'stacked') // on top of each other
distribution of random z values
over the x,y plane
Histograms: demo, plot
Old graphics syntax
(1/2): demo, script
// multiple_plots2.sce
Scilabs graphics
syntax changed with // Demonstration of a method for producing /
// three plots y1=f(x1), y2=f(x2),y3=f(x3) /
version 3.1. This // in the same frame. Note how the frame /
demo shows the old // is defined /
plot2d() syntax for a
clear,clc,clf;
case with three x1 = linspace(0,1,61);
plots, x2 = linspace(0,1,31);
x3 = linspace(0.1,0.9,12);
y1=f(x1), y2=f(x2) y1 = x1.*(1-x1).*cos(2*%pi*x1); // First graph
y2 = x2.*(1-x2); // Second graph
and y3=f(x3), y3 = x3.*(1-x3) + 0.1*(rand(x3)-0.5); // Third, as y2 with disturbance
in the same frame ymin = min([y1,y2,y3]); // Select minimum to define frame bottom
ymax = max([y1,y2,y3]); // Select maximum to define frame top
Note the frame dy = (ymax - ymin)*0.1; // Border for min/max
definition and rect = [0,ymin - dy,1,ymax+dy]; // Frame limits, start at 0
compare with the
plot2d(x1,y1,5,"011"," ",rect) // First call with frame definitions
method used in plot2d(x2,y2,2,"000") // Second call, only type/color (2) definition
Example 1-2 plot2d(x3,y3,-1,"000") // Third call, defines marks(-1)
xtitle("THREE GRAPHS PLOTTED IN THE SAME FRAME","Abscissa","Ordinate")
Old graphics syntax
(2/2): demo, plot
y3
y2
y1
Rotation surfaces
// rotation_surface.sce
The rotation // Plot the rotation surface created by /
surface is // the function y=2+sin(x) as it rotates /
// around the x-axis /
created by
multiplying clear,clc,clf;
the original // Define function to rotate:
function, //------------------------------------
x=-10:.01:10;
which is subplot(211)
redefined as plot2d(x,2+sin(x),5,rect=[-6.5,0,9,3])
2+sin(T), by // Rotate 2+sin(x) around y-axis:
.*sin(PHI) //--------------------------------------------
t=linspace(-6.5,9,60);
and phi=linspace(0,2*%pi,60);
.*cos(PHI) [T,PHI]=meshgrid(t,phi); // Create mesh
X=T;
Y=(2+sin(T)).*sin(PHI);
Z=(2+sin(T)).*cos(PHI);
subplot(212)
surf(X,Y,Z)
Logarithmic scale:
task & script
// log_plot.sce
Plot the Bode diagram for the
function // Plot the Bode diagram for the function /
100 // G(s) = 100/((s-10)(s-90)). Use the normal /
G(s) = // logarithmic x-axis and decibel scale on /
(s-10)(s-90) // the y-axis /
// handles_demo1.sce
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
does not work (took me hours to figure out)
Handles (5/12): demo,
behind the scene
-->gca()
// handles_demo1.sce
clear,clc,clf;
Change x-axis ticks & marks // Change x/y ticks & marks:
a.x_ticks = tlist(['ticks','locations','labels'],...
Change y-axis ticks & [0,%pi,2*%pi,3*%pi,4*%pi,14],...
['0','pi','2*pi3','3*pi','4*pi','14']);
marks a.y_ticks = tlist(['ticks','locations','labels'],...
[-0.5,-0.25,0,0.25,0.5],...
Final plot: ['-0.5','-0.25','0','0.25','0.5']);
x = sin(2*%pi*(0:6)/6);
y = cos(2*%pi*(0:6)/6);
plot2d(x,y,strf='011',rect=[-2,-2,2,2])
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
Scilab showed unexpected behavior with this script:
The background color could turn black with the command e=gce();
e.parent.background=34 . The gcf() handle revealed that the setting
was background=-2 and the handle command had no effect. The
definition color(grey) feels more stabile than its numeric counterpart
The Graphics Window did not always change when the script was
changed and executed. The background stayed grey even if
e.parent.background=color(grey) was deleted. When shifting
between two scripts on the Editor, the background color was exported to
the second script. The script had to be closed to get rid of the gray color
I found no way to add ticks & marks to the box. The Axes handle gca()
showed them as defined, but for some reason they are suppressed.
Help/axes_properties gives no explanation
Lessons learned: Do not exaggerate the extent to which you trade
ordinary plot functions (plot(), plot2d()) for handle commands
Programming pitfalls:
dont forget clf;
// ptifalls_1.sce
// Clear commands /
K = 100; a = 0; b = 0;
Change x = zeros(1,K); y = zeros(1,K);
for k = 1:K
and x(k) = a+k;
rerun 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); Plots are
for k = 1:K
x(k) = a+k;
superposed
y(k) = b-k^(0.5); without the
end
plot2d3(x,y,style=-1)
clf command
What to do with xset()?
Examples in Scilab literatureand in blog discussionsfrequently use the
function xset(). Its handy but obsolete, so what should we do about it?
The Help Browser recommends using the graphic objects representation
instead (set(), get(), handle commands)
Below are examples of how to substitute xset(). Note that xset() operates on
the current Entity level and gives the blue axes color, not the red graph
2. Modified script
1. Initial script x=-1:0.1:2.6 with Axes handle
with xset() plot2d(x,sin(2*x),5,rect=[-2,-2,3.6,2]) command
xset("color",2)
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])
3. Modified script a=gca();
set(a,"foreground",2)
with set() and
handle argument
xset(): a practical case
Example 6-2 (last set of examples) is adapted from Pinon.
Pinon The original
contained obsolete commands, in particular xset(). I substituted the
xset() commands with the following handle commands:
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...
Flawed error messages
Scilabs debugger shows strengths and flaws in the error messages
that invariably pop up before ones plot commands are right
Here are two error messages that I have got:
plot2d(x1,y1,style=5) // Function
!--error 999 plot2d:
first and second arguments have incompatible dimensions. The real problem was
at line 16 of exec file called by : that I had not used
exec("H:/Dr.EW/Writings/Scilab examples/derviative_2.sce"); the Dot Operator in
while executing a callback
the equation for y1
clc();
Bogus warning, Scilab crashed
and had to be reloaded to
erase the Console. This
while executing a callback occurred when I used two
Redefining permanent variable. deff() functions in tandem
!--error 13
More info on plotting
In the Help
Browser, Click:
Graphics Library,
and under it you find
info on e.g.
- 2D plots
- 3D plots
- axes_operations/
axes_properties
etc.
Now at least is the
time to get familiar
with the Help
Browser
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
8. Examples, Set 3
On plotting, handles, control
engineering, and user defined
functions
Return to Contents
Example 3-1: More
control engineering plots
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 first cases use the second-order transfer functions
script clear,clc,clf;
// Definition of systems:
//-------------------------------
s = poly(0,'s'); // Polynomial seed
The first two gain equations 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));
are given as ordinary Gain3 = poly(-5,'s')/poly([0,0,2000,200,25,1],'s','c');
polynomial expressions Gain4 = syslin('c',352*Gain3);
// Bode plot:
The third gain equation, to be //---------------
used in plotting Evans root subplot(221)
gainplot([Gain2;Gain1],0.01,100) // Magnitude plot
loci, is defined through its
roots // Nyquist plot:
//-------------------
subplot(222)
The Bode plot is only for the nyquist([Gain2;Gain1]) // Plot with Re and Im axes
gain, later the alternative
bode() will be demonstrated // Nichols chart (Black's diagram + iso-plots):
//-------------------------------------------------------------
subplot(223)
Scilab talks about Blacks black([Gain2;Gain1],0.01,100,[Gain2';Gain1'])
diagram rather than Nichols chart([-8 -6 -4],[20 50 80],list(1,0,5))
chart. Example 3-2 highlights // Evans root locus:
the difference between the two //-------------------------
subplot(224)
evans(Gain4,100) // Evans root locus for sys4
Ex 3-1: plot
clear,clc,clf;
The first vector argument of
chart() defines the iso-gain curves s = %s;
Gain = (2+3*s+s^2)/(1+3*s+2.5*s^2+s^3);
to be plotted system = syslin('c',Gain);
The second argument defines iso- black(system,.01,100) // Plot Black's diagram
phase curves chart([-8,-2,.5,3,6,12],[5,25,60,120],list(1,1,2,5))
// chart() adds iso-graphs
list() defines plotting properties
(the last argument does not have
any effect) History Quiz: Did Nichols base his
Check with Help for details chart on work by Black or by Hall?
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
Lets do a Bode plot using just
basic circuit theory and no Laplace
rubbish
Ex 3-4: // ---------------------------------------------------------------------------------/
// Plots the array factor of a linear antenna array with N elemnts, /
script
// spaced at d wavelengths, and main beam scanned at +60 degrees /
// ---------------------------------------------------------------------------------/
clear,clc,clf;
// Variables:
N = 10; // Number of radiating elements
This script is for the d1 = 0.45; // Element spacing in wavelengths
previous expression for d2 = 0.55; // Ditto
theta = [-%pi/2:0.01:%pi/2]'; // Half space, +/-90 deg
AF, but normalized theta_z = %pi/3; // Scan angle
(divided by N) to keep
// Define array factors:
the main beam value at f_phase1 = %pi*d1*(sin(theta)-sin(theta_z)); // Phase function
unity. The phase f_phase2 = %pi*d2*(sin(theta)-sin(theta_z)); // Ditto
AF_norm1 = abs((sin(N*f_phase1)./sin(f_phase1))/N);
functions have been // Normalized array factor (d=0.45)
defined separately in AF_norm2 = abs((sin(N*f_phase2)./sin(f_phase2))/N);
// Normalized array factor (d=0.55)
order to shorten the
expression for AF_norm // Plot functions:
subplot(211 // Linear plot (d=0.45,0.55)
plot2d(theta,[AF_norm1,AF_norm2], style=[2,5],...
The array factor is plotted leg="d = 0.55@d = 0.45")
xtitle("ANTENNA ARRAY FACTOR, N = 10, Beam angle = 60 deg",...
both in linear and polar "Theta (radians)","Normalized amplitude")
presentation 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
clear,clc,clf;
x=linspace(-10,10,50); // Linear space of x
This example is adapted from y=x; // Ditto for y
For comparison we first do a basic plot with plot2d() and then modify
the figure with handles
Ex 3-6: Lissajous figures,
script 1
// handles_demo2-1.sce
// Two Lissajous figures, sin(t) & cos(3t) and /
// sin(1.5t) & 0.5*cos(1.5t), with plot definitions /
// given by arguments of the plot2d() function /
Sine and cosine functions are
grouped into matrices clear,clc,clf;
There were huge problems when I first 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 define ticks, etc.
Lessons learned: Be sure that you now what you do with gce()!
*) You can use the function pair drawlater() and drawnow() to avoid the
flashing, as was done in Ex 3-5.
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
9. Converting Matlab
files
The embedded Matlab-to-Scilab
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 find Matlab to Scilab
Conversion Tips. You
will see a long list of the
m2sci_... type of
functions
Click on the first
subheading, Matlab-
Scilab equivalents, and
you get a list of Matlab
functions and their Scilab
equivalents (missing ones
are not included, like
text() and xlim()
mentioned below)
Using the integrated Matlab-
to-Scilab translator
Scilab can convert Matlabs .m files to .sci files, although we should
not expect the conversion to be fully successful every time. The
translated script may have to be modified manually
We start by opening the translator: *
*) It used to be possible to import Matlab files directly, but this option does not
exist any more.
M-to-S translator: the
process
The conversion tool opens
1. Click: (File name) Browse
and identify the file that you
want to translate
2. Click: (Directory name)
Browse to point out where to
put the translated script (and
associated products*)
3. Click: Convert
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
sinfi = ((fs/4)*(-Nfft/2:Nfft/2-1))/Nfft;
Gfi = mtlb_i(Gfi,1:Nfft/2,sqrt(Gfi(1:Nfft/2)));
Gfi = mtlb_i(Gfi,Nfft/2+1:Nfft,-sqrt(Gfi(Nfft/2+1:Nfft)));
Gfs = sqrt(Gfs);
M-to-S translator: script
(4/4)
Note that title() is an
// Plot Monopulse Antenna Pattern
alternative to xtitle()
plot(fi,Gfi,fi,Gfs);mtlb_grid;
Here come the last set(gca(),"data_bounds",matrix([-0.25,0.25,-0.8,1],2,-1));
warnings. The next ylabel("Amplitude");
xlabel("Angle - radians");
slide shows what title("Monopulse Antenna Patterns");
they mean // !! L.63: Matlab function text not yet converted,
original calling sequence used.
text(0.04,0.8,"Sum Pattern");
Well, lets see how // !! L.64: Matlab function text not yet converted,
original calling sequence used.
Scilab reacts by text(-0.22,0.6,"Difference Pattern");
executing the script...
M-to-S translator: plot
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
Based on this example one could say that the embedded Matlab-to-
Scilab translator is adequate
A legend has to be added manually to compensate for the missing
text() information*
The example demonstrates partly good programming practice by
declaring each logical entity. However, informative explanations could
be added
Another improvement is to use expressive variable names. Why not
talk about sampl_freq instead of fs, and what does wxna() stand
for?
Help sheds no light over the meaning of the second .sci files that the
conversion produces
*) 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
% beating sinusoidal tones
%
To the right is a Matlab code t = linspace(-1e-2,1e-2,1001);
(top) and its Scilab equivalent x = cos(2*pi*1500*t) +
(bottom). The way I did it: cos(2*pi*1300*t);
m = 2*cos(2*pi*100*t);
Checked visually for differences: plot( t, m, b:, t, -m, b:, t, x, k ),...
axis( [-0.01 0.01 -2.4 2.4] ),...
Comments: % // title( Beating between tones ),...
Built-in functions: pi %pi xlabel( Time (s) ),...
ylabel( Amplitude )
Plot commands are split up on
multiple rows. Indents are not
necessary, but a visual help // M-to-S_1-modulation.sce
Changed what I could, the run
// beating sinusoidal tones /
the script and let Scilabs
debugger yell about the rest cear,clc,clf;
t = linspace(-1e-2,1e-2,1001);
Checked frequently with Help x = cos(2*%pi*1500*t) + cos(2*%pi*1300*t);
(particularly Matlab-Scilab m = 2*cos(2*%pi*100*t);
plot( t, x.*m, rect = [-0.01 0.01 -2.4 2.4] )
equivalents) to understand the title( 'Beating between tones' )
error messages on the Console xlabel( 'Time (s)' )
ylabel( 'Amplitude' )
Manual conversion (2/6):
Case #1, plot
There were some problems
with this conversion:
I split up Matlabs long
plot() command, but the
abbreviated form did not
work in Scilab
First I changed Matlabs
axis() to rect(), then
swapped the preceding
argument part for x.*m.
Now plot() worked
The label commands gave
problems. The reason was
againthat I had copied
the Matlab code and the
quotation marks were
pasted incorrectly
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*
The pie() function also exists in Scilab, the difference is that Scilab
does not support Matlabs pielabel() function
// M-to-S_2-pie.sce
clear,clc,clf;
revenues = [31 36 18 8 7];
pie(revenues,['Income Tax';'Sales Tax';'Borrowing'; *) A more general sector chart
'Corporate Taxes';'Misc']); will be presented in Example 6-4
Manual conversion (4/6):
Case #3, script & plot
As a last case, lets look at a shifted sinc function
In this case the problem is that polardb() is an informal creation
by Matlab users which Scilab does not support
x = -(5*2*pi):.1:(5*2*pi);
th = linspace(-pi,pi,length(x));
rho=((1+sin(x)./x));
polardb(th,rho)
// M-to-S_3polarplot.sce
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)
Similar, but not the same as the
Matlab plot if radial units are in dB
Manual conversion (5/6):
Case #3, discussion
The polar plot with radial
units in dB looks rather
counterintuitive, since
its sidelobes appear to Linear plot
be pointing in the wrong
direction
// M-to-S_3polarplot.sce
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 defined
functions (UDFs), an expression that Scilab also does not know
An introductory demo
function A = triangle_area(a,b,c)
Recall Example 1-3 that introduced
the concept of user defined // The function 'triangle_area' calculates the /
functions (UDFs) // area of a triangle with side lengths a, b, c. /
funcprot(0)
Task: Write a function that p = (a+b+c)/2 // p = half perimeter
calculates the area of a triangle A = sqrt(p*(p-a)*(p-b)*(p-c))
with known side lengths endfunction
*) Here I use the term function since the code is independent and not called
by a main program.
Demo (1/2): // subroutine1.sce
script
// range [-5,5] and determine its positive root. /
// Assume we know the root lies in the range [1,2] /
// SUBROUTINE para():
Task: Compute & plot a //------------------------------
function y=para(x); // Subroutine declaration
parabola, find its y = x^2-x-1 // Equation (parabola))
positive root endfunction
// MAIN script:
Here the subroutine is //-------------------
called for the first time x = linspace(-5,5,100); // Range of interest
plot(x,para) // Call subroutine and plot
using the input xgrid; // Add grid
argument x
a=1; b=2; // Search limits
while b-a > 10^(-4) // Accuracy for searching root
Here the subroutine is called c = (a+b)/2; // Midpoint of limits
twice more, first with the if para(a)*para(c)>0 then // IF (lower)*(midpoint)
// is positive
input argument a, then b a=c; // THEN change lower limit
else
b=c; // ELSE change upper limit
Interesting way of finding end
the root location. Later well end
disp("The root lies between "... // Output root limits
do the same using fsolv() +string(a)+" and "+string(b))
Demo (2/2): plot,
printout & comments
This demo was borrowed from the
pamphlet Scilab pour les Lyces
Return to Contents
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:* Comparison operators:
for ... (if ... else) end == equal to
while ... (if/then/else) ... end < smaller than
if ... (elseif ... else) ... end
> greater than
select ... case (... else) ... end
break ... continue <= smaller or equal to
try ... catch ... end >= greater or equal to
<> or ~= not equal to
Logical operators:
& and Logical/Boolean constants:
| 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
The for ... end loop repeats a group of statements a predetermined
number of times. The general expression of for ... end is:
As seen here:
// for-end_demo.sce
1. 1. 1.
// Compute the square root and square /
// of odd integers from 1 to 8 /
n = 8;
square cannot for k = 1:2:n
be used as root = sqrt(k); 7. 2.6457513
variable name quadrat = k^2; 49.
disp([k, root, quadrat]) 5. 2.236068
since square() is end
a Scilab function 25.
3. 1.7320508
9.
for if else end
for ... end can be nested with if/else conditions to allow for
execution of alternate statements:
// --------------------------------------------------------------------------- /
// The script generates Gaussian noise around a fixed 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 /
// --------------------------------------------------------------------------- /
// Sort signal:
// ----------------
for j = 1:1:n
if signal(1,j) > ave+1 then // Default variance = +/-1
Note how the signal above = above + 1; // Count signal > mean+var
array is read elseif signal(1,j) < ave-1 // Default variance = +/-1
below = below +1; // Count signal < mean-var
element-by-element else // If within variance limits
as j goes from 1 to n within = within + 1; // mean-var <= signal <= mean+var
end
end
for if else end:
demo, script (3/3)
// Display result:
// --------------------
Display on the disp(['Result from generating', string(n), 'Gaussian distributed samples'])
disp(['(signals) with mean =' string(ave) 'and variance = 1:'])
Console: Total, disp([' -' string(within) ' samples were inside variance limits,'])
mean, and variance disp([' -' string(above) 'above upper variance limit, and'])
disp([' -' string(below) 'below lower limit'])
limits
// 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
This particular form y3 = (ave-1)*ones(1,n); // Array for lower variance limit
of multiple plots was rect = [0,ave-4,n+1,ave+4]; // Set pot window
plot2d(x,signal,2,"011"," ",rect) // Plot samples
discussed earlier and plot2d(x,y1,5,"000") // Plot mean value
is worth keeping in plot2d(x,y2,3,"000") // Plot upper variance limit
plot2d(x,y3,3,"000") // Plot upper variance limit
mind legend('signal','average','variance');
xtitle('GAUSSIAN RANDOM SAMPLES','Sample #','Sample value')
for if else end:
demo, print & plot
!Result from generating 500 Gaussian distributed samples !
It can be seen
that there are one
or two samples
outside the 3
limit, as should be
for if else end:
comments
Note how the random data is collected by the signal(:,n) array. Compare
this with the x = [x,k] construct that is used later in connection with the
discussion on break & continue
This example was a maddening experience: I just could not figure out how
to make the plot work. After hours of attempts I found the problem: I had
put the random function inside the for ... end loop
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 condition
// foo
// loop counter, i.e. count = count +1;
end -->k = 1;
while condition_1
if condition_2 then
// foo
else
// foo
end
// foo
end
The function on the next slide is for a game in which the user should
guess a random number that the computer draws. The game finishes
only with the correct guess
while if /then/else
end: demo
Save the script, load it
// game.sci into Scilab (on Editor),
// The function draws a random number in the / type the function name
// range [1,M] that the user should guess. / on the Console
// Game finishes when correct number is found /
clear,clc; -->guess_a_number
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 find
expressive text messages. Perhaps the following would be better in
the previous case:
guess = input(Now, Sir/Madame, type your guess: )
0.
n =
0. 0.
3.
n = n =
n =
3. 3.
6.
n = n =
n =
6. 6.
if (elseif/else) end
The if statement evaluates a logical expression (condition) and
executes a group of statements when the expression is true
The optional elseif and else keywords provide for the execution of
alternate groups of statements
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:
try
// foo
// If an error occurs in this part....
catch
// .... execution continues here
// foo
end
Return to Contents
Example 4-1: step
function, unit step (1/2)
Step functions are useful in
many practical applications
As mentioned in Ex 2-3, Scilab
lacks a separate function for Unit step:
creating (unit) steps, but we y
can form them indirectly (in Ex 1
2-3 it was done with a unit
vector)
Here we shall look at two cases 0
t0 t
where a step is needed
In the first demo a step is 0, t < t0
created with a user defined y(t) =
function that includes the sign() 1, t > t0
function (Help is of no help
here, you dont understand
what it says about sign())
Ex 4-1: step function, unit
step (2/2)
// step_sign.sce
// Plot a sign() fucntion that is shifted by 1 / Note how the sign()
// & compressed by 0.5 to give a unit step /
function is shifted (addition
clear,clc,clf; by 1) and compressed
funcprot(0);
(multiplied by 0.5) to get
x = linspace(-5,5,400); the required unit step
deff('y=u(x)','y=0.5*(1+sign(x))') // Define sign() function,
// shift & compress as needed
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
undefined. The KISS principle (Keep It Simple, Stupid) did not apply
in this case
Example 4-2: cones in a
3D space
This example is adapted from Chancelier et al., pp. 163-166
The script is quite complex with four subroutines and three separate
plotting structures, which makes it difficult to follow the transfer of
parameters. Changing an argument can have unexpected
consequences
Some aspects of the script have not been covered before and will be
left without detailed discussion here as well (see however Ex 4-3)
The object, a cone (the book mentions and shows a vase), is plotted
in three separate positions using lateral shifts, rotation, and non-
rotational dilation (homothety) of the objects
The cones are shaded using handles that are called through the
gce() command
Scilab functions used for the first time: diag(), eval3dp(),
graycolormap(), isoview(),* size()
*) The function isoview() is obsolete. The Help Browser recommends
using frameflag=4 instead.
Ex 4-2: script (1/4)
// cone_manipulation.sce
// ********************************************** //
vertical[] tells how to // The script generates and plots a cone with its //
// tip at the origin. It plots two copies of the //
move along the z axis in // cone, one shifted and one shifted & rotated //
later calculations. Note // //
the increasing and // ********************************************** //
Here we plot the basic // Plot basic cone with tip at the origin:
//----------------------------------------------------
cone, which has its tip in plot3d(xv,yv,zv)
the origin. The exterior e1=gce(); // Get Current Entity handle
and interior of the cone e1.color_mode = 24; // Object exterior: light grey
e1.hiddencolor = 30; // Object interior: dark grey
should have different
shades // ---- STEP 2: MANIPULATE & PLOT OTHER CONES ---- //
Second cone,
laterally shifted
and enlarged
Third cone,
laterally shifted
and rotated
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)
Example 4-3: how to
generate a cone
How was the cone in the // cone_creation.sce
previous example // A bare-bone eval3dp() script for plotting a 3D cone /
generated? The interplay
between the matrix clear,clc,clf;
vertical[], user defined vertical=[0,1,2,2.3,3,4]; // Vertical reach of 3D object
function cone(), and facet function [x,y,z]=cone(reach,Z) // Generation of a 3D object
generation function x=vertical(1,Z).*cos(reach) // Extension along x axis
eval3dp() are not too y=vertical(1,Z).*sin(reach) // Extension along y axis
z=vertical(1,Z).*ones(reach) // Vertical (z) extension
obvious endfunction
[xv,yv,zv]=eval3dp(cone,linspace(-%pi/1.5,%pi,20),1:5);
Lets simplify the case to a
bare minimum plot3d(xv,yv,zv,theta=60,alpha=70) // Plot object
e1=gce(); // Get current Entity handle
e1.color_mode = 24; // Object exterior: light grey
And look at the result on e1.hiddencolor = 30; // Object interior: dark grey
the next slide
Ex 4-3: plot
Dark gray interior (e1.hiddencolor = 30)
Z5 = 3
Box alignment
defined by theta Z4 = 2.3
and alpha in
plot3d() Z3 = 2
clear,clc;
The first check makes funcprot(0)
sure that the number
function voting
entered by the user is
>0 // Give input and check entered number:
//-------------------------------------------------------
The next check is to n = input('Give number of issues to vote on_ ');
make sure that n is an if n <= 0 do // # of votings must be > 0
disp('warning-----must be > 0');
integer abort;
end
Pay attention to the if n ~= int(n) do // n should be an integer
abort commands! disp('warning-----not an integer!');
abort;
end
Ex 4-4: script (2/2)
// Create n random numbers 0,1 or 2:
//--------------------------------------------------
Generation of random dt=getdate(); // Get initial seed
numbers in the similar rand('seed',1000*dt(9)+dt(10)); // Seed random generator
manner to Ex 1-3 votes = floor(3*rand(n,1)); // Generate votes (0,1, or 2)
endfunction
Ex 4-4: comments
Good old GO TO statement, where have you been all these yearsand why
do they give you such fancy names?
Example 4-5: nested
structures, script
// conditional.sce
This script contains an
if ... elseif ... else ... end // Climb up or down the scale depending on /
structure nested within an // input data ("u" or "d") without exceeding /
// the limits. The process ends when "e" is /
while ... end structure // pressed /
(read the title for an
explanation of what the scale = [1 2 3 4 5 6 7 8 9]'; // Define scale to climb
i = 1; // Preset counter
script does) strg = ' '; // strg = empty string
while strg ~= 'e' // Until the "e" key is hit
disp(scale(i,:)); // Display location on scale
Note how min() strg = input('Exit(e), Up(u), Down(d)?','string')
and max() if strg == 'u' then // If "u" is hit
while ... end
scale limits are i = max(i-1, 1); // One step down, until lowest
not exceeded 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
end // End of while statement
disp('you hit e=Exit') // Exit message
Example 4-5: 1.
Exit(e), Up(u), Down(d)?u
strg =
execution u
2.
Exit(e), Up(u), Down(d)?u
strg =
u
The scale counter i is preset to
3.
1 and increases/decreases Exit(e), Up(u), Down(d)?d
depending on the entered data strg =
d
Any input parameter except u, 2.
d, or e give an error message Exit(e), Up(u), Down(d)?6
strg =
6
The break command works well ---incorrect input---
in this case
2.
Exit(e), Up(u), Down(d)?u
strg =
Homework: Modify the script by using the u
Return to Contents
Math in earlier chapters
Chapter 3: Complex numbers, vectorized functions,
polynomials
Chapter 4: Trigonometric functions, random functions
Chapter 5: Matrices, matrix operations, matrix operators,
symbolic computing, random generators
Chapter 6: Linear equation systems with real coefficients
Chapter 7: 2D and 3D functions, vector fields, histograms,
rotation surfaces, logarithms, polar coordinates
Chapter 8: Polynomial expressions
Chapter 9: Application of matrices & trigonometric functions
Chapter 10: Arithmetic and algebra
Chapter 11: Logical expressions
Chapter 12: Step functions, application of 3D vector spaces
"Do not worry about your problems with mathematics, I assure you mine are
far greater. Albert Einstein
optim() & fsolve():
demo (1/4), the task
The functions optim() and fsolv() give us tools by which to investigate
nonlinear equations and/or equation systems:
3.1415927
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 Root mark in wrong place
Complex numbers:
demo, task
Complex numbers
have not been
discussed at any
length before, so lets
look at a practical
problem
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)
The initial step is as Ex // circuit3.sce
#5; the residual check // Complex mesh-current solution. The complex results are /
is at the end of the // converted from rectangular to polar values by computing /
script // their magnitude and phase. The clean() function is used /
// to eliminate computing errors around zero. /
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 definite integral -->deff('y=f(x)', 'y=6*x^2');
A= f(x) dx 18.
a A = -->deff('y=f(x)', 'y=sin(x)');
To solve the integral, first define -->A = intg(%pi/4, 3*%pi/4, f)
-->A = intg(-2,1,f)
the function y = f(x), e.g. using A =
L= {1 + [f (x)] } 2 1/2
dx -->L=intg(2,3,g)
L =
a
1.125
Lets compute the length of -->L=intg(3,4,g)
f(x) = x3/24 + 2x-1 from x=2 to L =
x=3 1.7083333
The task requires manual
derivation, which yields
f (x) = x2/8 - 2x-2
Numeric integration (3/6):
double integral, principle
d b
The function int2d () computes
the 2D area integral of a function
f(x,y) over a region consisting of
I= f(x,y) dx dy
c a
N triangles
y
D=a,d C=b,d
x and y must therefore be d
defined through triangulation
matrices X and Y, after which the ACD
command is ABC
c
[I,err] = int2d (X,Y,f) , A=a,c B=b,c
and Scilab returns the integration x
variable I and an estimation of a b
the error, err (not mandatory)
a a c c
The triangles are ABC and ACD, X= b b , Y= c d
as shown in the picture. Triangle b a
elements are inserted column- d d
wise in the matrices
ABC ACD ABC ACD
Numeric integration (4/6):
double integral, demo
-->deff('z=f(x,y)', 'z=y*cos(x)+x*sin(y)');
Lets compute the double
integral -->X = [0 %pi %pi; 0 %pi 0]
X =
2
0. 0.
I= (y cos(x) + x sin(y)) dx dy 3.1415927
3.1415927
3.1415927
0.
/2 0
-->Y = [%pi/2 %pi/2 2*%pi; %pi/2 2*%pi 2*%pi]
By looking at the integration Y =
limits of the function we find 1.5707963 1.5707963
the triangulation matrices X and 1.5707963 6.2831853
Y: 6.2831853 6.2831853
0 0 -->[I,err] = int2d(X,Y,f)
/2 /2 err =
X= , Y = /2 2
0 9.805D-11
2 2 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
clear,clc,clf;
9.887D-11
I = Same result, but a small difference
- 4.9348022
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
y0 = initial condition (normally a column vector)
t0 = initial time (normally 0)
t = vector of instances for which the solution has to be
computed, e.g. t = [0:0.01:10]
f(t,y) = function for which the solution has to be found, often
stated as [ydot] = f(t,y). Here t is a scalar, y a column vector,
and [ydot] a column vector with values of the derivative
ode() can also have optional arguments. See Help for
details
*) Sallet, G.: Ordinary Differential Equations with Scilab, <http://www.math.
univ-metz.fr/~sallet/ODE_Scilab.pdf> is an old but good text.
First-order ODEs: demo
Lets find the solution for the first-order homogenous ODE
x + x2 = t ,
with the initial condition x(0) = 1. Plot the solution for t [0,20]
Start by rewriting the function as x = -x 2 + t
Note how x is designated y in the deff() argument
// first-order_ODE.sce
clear,clc,clf;
funcprot(0)
The command
%ODEOPTIONS = odeoptions()
opens the GUI shown right. With
the help of it you can change
parameters for solving differential
equations. Examples:
Return to Contents
Example 5-1:
solving an equation (1/3)
This demo is based on Mkel
-->plot2d(x,[log(x), x.^2-
Lets solve the equation 7*x+10])
-->x = (0.01:0.01:8)';
ln(x) = x2-7x+10
-->x1=fsolve(1.8,f)
We can also check the error of x1 =
q 0 1 q 0
= 1 R + 1 u
i i
LC L L
Remember: x = Ax + Bu
Ex 5-2: ODE, series RLC
circuit (3/5), script
// series_RLC_ODE.sce
x = y x 0 1 x
y = -1 -1 y
y = -x y
together with a single phase portrait with the initial trajectory x(0) =
1 and y(0) = 1
The script can utilize either the ODE system (as Povy has done) or
the state-space representation. Well select the latter, in line with
earlier examples
Ex 5-3: // ode_phase_plane_m.sce
script
// The scripts plot the phase plane of the /
// equation system x'=y, y'=-x-y together with /
// a single phase portrait that satisfies the /
// initial condition x(0)=1, y(0)=1 /
clear,clc,clf;
funcprot(0);
The state-space function
is named firstorder() // First order transformation:
//--------------------------------------
The vector field is drawn A = [0 1;-1 -1]; // State vector
deff('[ss]=firstorder(t,x)',ss=A*x');
with fchamp()
// Create & draw slope (vector) field:
ode() has only one //-------------------------------------------------
argument (and accepts z = linspace(-1.5,1.5,10);
fchamp(firstorder,0,z,z) // Draw vector field
only one name) for the
initial condition x and // Create phase portrait:
//-------------------------------
y are renamed x(1) and x0 = [1;1]; // Initial condition
x(2) respectively, as t = linspace(0,30,300);
[x] = ode(x0,0,t,firstorder); // [x]=state variable vector
shown in the arguments // with x=x(1), y=x(2)
for plot2d()
// 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
i = i+2 j = j+2
endfunction
Ex 5-4: Simpsons rule,
script & result
// Define integration parameters:
Now comes the function f(x,y) //--------------------------------------------
that we want to integrate. We x0 = 0; // Lower bound for x
xn = %pi; // Upper bound for x
start by defining integration limits n = 100; // # of subintervals of x
and steps y0 = %pi/2; // Lower bound for y
ym = 2*%pi; // Upper bound for y
An interesting problem emerges: m = 100; // # of subintervals of y
How should one define the calling // Define function & calculate integral:
argument f(x,y)? If it is entered //---------------------------------------------------
deff('[z]=f(x,y)','z = y*cos(x)+x*sin(y)');
as f(x,y)=y*cos(x)+ x*sin(y), I = simpson_double(x0,xn,n,y0,ym,m,f)
Scilab will complain that x and y messagebox('The result of the double integral is:
'+string(I))
are not defined. The solution is
deff()
And finally: the answer as
displayed on the Message box
(the last digit of the earlier demo
was more accurate) The exact answer is
-2/2 = -4.934802199...
Ex 5-4: Simpsons rule,
discussion
I had big problems with this one. Scilab repeatedly insisted on
coming up with the wrong answer. I tried to find the error in several
ways:
Checked manually that the earlier answer (- 4.9348022, or 2/2) was
correct
Changed trigonometric functions to exponential equivalents at no avail
Checked the algorithm by comparing with solved examples from math
and Matlab books
Finally, when I plugged in the equation in the now several times
changed script, the result came out right. Most likely I had written
sin(x) instead of cos(x).....
Lessons learned: Its hard to see bugs in ones own program
Another thing: The script uses nested loops (for i = ...; for j = ...; ...
end; end;). This should be avoided in Scilab as far as possible,
because the performance is poor in such cases
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Return to Contents
Introduction
Scilabs GUI interface was updated with version 5. Old tutorials (e.g.
Campbell et al.) are therefore of limited value
Brief discussions of GUIs can be found in Kubitzki and in Antonelli &
Chiaverini (you can read Scilab scripts in German and Italian even if
you dont speak the language)
Although the GUI interface has improved, the Scilab team still cannot
be proud of their achievement
GUIs is a large subject; the Help Browser identifies about 50 GUI-
related functions. Well be able to cover only a part of them (as
always)
We have earlier seen cases with the dialogue box (x_dialog() in Ex.
1-3) and the messagebox (messagebox() in Ex. 5-4)
The first discussion below is about how to tailor Scilabs windows
Following that we shall look at some user defined dialog windows. A
real GUI is presented in Example 6-1
Tailoring windows (1/2)
There are four main functions for tailoring either the Console or the
Graphics Window:
Create
-->addmenu('Graphics',['New window','Clear window','Close window'])
-->Graphics = ['scf()','clf()','xdel()']
Graphics =
// uicontrol-1.sce /
clc; xdel();
Command Feature
messagebox() Message presentation (see Demo 2, Cases 1, 2 & 7)
x_choose() Alternative selectable from list (Demo 2, Case 3)
x_choices() As previous but with multiple choices (Demo2, Case 5)
x_dialog() Window with multi-line dialog (Demo 2, Case 4)
x_mdialog() As previous but with multiple string parameters
x_matrix() Vector/matrix input window (Demo 2, Case 6)
list()* Creates a list of objects (Demo 2, Case 5)
Case
2. 4: x_dialog() with input transformed
from string to matrix
ans =
--
>ans=x_choose(['Alpha','Beta','Delta','Gamma'],'
Double-click on one:')
6. Change
5. 4. matrix as needed, click OK
1. 2. 3.
GUI demo 2: creating
pop-up windows (3/5)
// x-choices_demo.sce
Pick your
choices, click
OK, and
Scilab returns
the answer as
a vector*
*) Scilab 5.1.1 returns the answer automatically,
3. 2. 1. with 5.3.1 & 5.3.2 it must be asked for (a bug?)
GUI demo 2: creating
pop-up windows (4/5)
Case 6: Compute determinant for a
matrix A that is given by x_matrix().
The assumption is a 3x3 identity matrix
// x-matrix_demo.sce
// screensize_demo.sce
clear,clc,clf;
Return to Contents
File handling:
introduction
In engineering, data on external files often originate in automated
measurements. The data has to be read by Scilab before it can be
processed. Well focus our discussion on this aspect of file handling
Scilab has a set of commands for file handling, beginning with the
commands mopen() that opens a file, and mclose() that closes it.
Between those two we use e.g.:*
*) 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.
File handling: demo 1
(1/5), introduction
Open write file: fd, path, name
In this demo Scilab creates the data
file that is then read; later well se
Write data into file how to read from text files created
by other programs
Close write file, w
Script sequences are shown to the
right. The script demonstrates the
Open file for reading, r use of the functions mopen(),
mclose(), mfprintf(), mseek(), and
Define contents to read (whole file) mfscanf()
Pay attention to the following steps:
Return pointer to beginning of file open as w file, close w file, open
as r file, close r file. The stack
Define data to read pointer moves down as we write into
the file and must be returned to the
top before we begin to read
Close file
File handling: demo 1
(2/5), script
Create the text (.txt)
file with mopen(). fd
// file_exercise1.sce
= file descriptor.
Note the argument // The script demonstrates the process of 1) creating a text file /
w (write) that is //
//
on Scilab, 2) closing it, 3) opening it again to be written into,
4) writing the actual data into the file, 5) reading certain
/
/
used to create a // pieces of data from the file, and 6) closing the read file, /
new file // Notice that both close operations are necessary! /
data (in this case // Create and open a text file for the exercise:
created by t) using //-------------------------------------------------------------
mfprintf(). Note the fd = mopen('H:\Dr.EW\Writings\Scilab examples\file_exercise1.txt','w');
odd argument // Create data and write into the exercise file:
%6.3f\n' that //-------------------------------------------------------------
t = (1:1:18)'; // Integers from 1 to 18
defines the output mfprintf(fd,'%6.3f\n',t);
size (explained
below)
File handling: demo 1
(3/5), script cont..
// Close exercise file:
After that the file //---------------------------
has to be closed mclose(fd);
1. - 7.3 20.1
2. - 7.8 19.8 -->[G,text] = fscanfMat('I:\file_spreadsheet_demo5.csv')
3. - 8.3 19.5 text =
4. - 7.6 19.5
5. - 5. 19.7 Reading Outdoor Indoor
6. - 3.3 20. G =
7. - 1.9 20.2
8. 0.1 20.6 1. - 7.3 20.1
9. 1.2 21.1 2. - 7.8 19.8 Note: If you work
10. 0.4 21.3 3. - 8.3 19.5 with MS Excel you use
11. - 2.1 21. 4. - 7.6 19.5
12. - 3.6 20.7 5. - 5. 19.7 of course the
6. - 3.3 20. ending .txt instead
7. - 1.9 20.2 of .csv (CSV stands
8. 0.1 20.6
for Comma Separated
M = fscanfMat() 9.
10.
1.2
0.4
21.1
21.3 Variable)
11. - 2.1 21.
12. - 3.6 20.7
Spreadsheet data (4/7):
script for plotting (1/2)
// spreadsheet_data_plot.sce
The fscanfMat()
command cannot be // The script reads data from the test file /
// file_spreadsheet_demo5.csv, determines its /
split on two rows // length,and plots its two measurement sets /
(even if it is not
needed in this case) clear,clc,clf;
Which means that each value that we want to print is declared with
an optional text, the format to be printed in (both within a single pair
of quotation marks), and the value to be printed
Format declarations are given on the next slide
The format demo two slides down should give a better grasp of what
it all means. If you ask me, it looks really messy...
The fprintfMat() command is used to write a matrix in a file. See
Help for details
Format definitions
Recall the arguments %6.3f\n and %f in File handling Demo
1. They are part of a set of format definitions:
%d for integers (e.g. 1230)
%f for floating point presentation (e.g. 12.30987)
%e for exponentials (e.g. 1.2345e+002)
%s for text (string) presentation (e.g. Hello World!)
%6.3f to define the output size
the 6 is for the total number of figures
the 3 is for the number of figures after the decimal point
\n go to a new line
\t use a horizontal tabulator
Some definition combinations, like %6.3f\n, are possible
Format demo:
script (1/2)
This demo aims at clarifying the use of format declarations:
// file_format_demo.sce
clear,clc;
Remember
to close!
mfscanf(), fscanfMat()
We used mfscanf() in Demo 1 to read (scan) data from a file. Two
examples of its use:
contents = mfscanf(-1, fd, %f). With this argument it reads the whole
contents of the file and formats it
four_values = mscanf(fd, %f %f %f %f). Reads the four first data in
the file
After reading data, the stack pointer remains where it is and we must use
the mseek(n,f) command to shift it to a new location. The first row in
the stack is numbered 0, as indicated by mseek(0,fd) in Demo 1
In the discussion of spreadsheet data we used the fscanfMat()
function to read the data contained in a .csv file. The function has
two alternative call sequences:
fscanMat(filepath,<opt_arg>) to read the numeric part only of scalar
matrix data in a text file
[M,text] = fscanfMat(filepath,<opt_arg>) to read the data and include
the first non-numeric lines
The default optional argument is %1g. Check with Help for other options
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
17. Animation
A brief introduction to creating
dynamic graphics
Return to Contents
Introduction
Animations are a sequence of plots on the Graphics Window;
executed by showing a plot, freezing it while an incremental shift is
being calculated, and then swapping the old plot for the new one.*
With correct speed and increments it gives the illusion of continuous
movement
There are two main modes for creating animations:
Real time mode. The animation runs while the script is being executed,
with the speed being determined by the incremental shifts and computer
speed. The execution can be influenced (slowed down) by the
realtimeinit() and realtime() functions
Playback mode. Possible in Matlab with the getframe and movie
commands, but Scilab lacks this alternative
A tool for producing animations is the pixmap handle command and
the show_pixmap() function. Example 6-2, however, does not use
the pixmap command
*) 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 (2/4): moving
pie, script
// animation_ball.sce
clear,clc,clf();
This demo is adapted from
Chancelier et al. f=gcf();
f.pixmap='on'; // Double buffer mode
Its an attempt to f.pixel_drawing_mode='nor'; // NOR mode
f.background=color("lightblue");
demonstrate the use of the
XOR command in ax=gca();
f.pixel_drawing_mode= ax.data_bounds=[0,-4;14,10]; // Plot limits
xor, here NOR instead of ax.margins=[.1 .1 .1 .1]; // Plot framed
XOR for reasons told below ax.background=color("lightgrey");
max_pos = 10; // Max position of rectangles
The rectangles move on top
k=%nan; // Auxiliary parameter
of a grey background xfrect(k,k,4,4); // First black rectangle
e1 = gce();
The rectangles are drawn with xfrect(max_pos-k,max_pos-k,4,4); // Second rectangle
xfrect() without color code, e2=gce();
they are therefore black
for k=linspace(1,10,200) // Animation loop
e1.data(1:2)=k;
The rectangles move e2.data(1:2)=max_pos-k;
diagonally from corner to show_pixmap() //Show double buffer
corner in 200 steps end
Demo 2 (2/2): frozen plot
Here is the animation in progress.
The NOR function does its job, but
otherwise something is quite
wrong: We do not have black
rectangles moving across a light
grey background
The problem is that the command
f.pixel_drawing_mode=nor
operates on the whole screen, not
just on the moving rectangles as
intended by Chancelier et al. For
that reason the XOR operation
they use is even worse than NOR
I decided to leave the demo in this
state. Those who are interested
can find a better solution in Steers
Scilab Graphics, p. 28
Demo 3 (1/3): a 3D
object, script (1/2)
Now well look at a // rotating_surface.sce
geometrically more // The 3D surface is first rotated and then /
challenging object, a 3D // tilted, after which its position is locked /
plot that moves both in
clear,clc,clf;
azimuth and elevation
// Initialize:
//--------------
Data bounds are not f=gcf();
defined separately, they are f.pixmap="on";
clear_pixmap();
changing with surface mesh t=%pi/20*(-20:20); // Bounds & mesh resolution
resolution
// First plot command, defines labels:
//-------------------------------------------------
The first plot command only plot3d1(t,t,sin(t)'*cos(t),%nan,%nan,..
defines axes labels 'x_axis@y_axis@z_axis');
Demo 3 (2/3): a 3D
object, script (2/2)
The surface rotates around
the z axis, starting at 45 and
finishing at 100, while the
tilt angle is constant at 45 // Set speed and turn object:
//--------------------------------------
step = 2; // Step size --> 1/speed
When finished rotating, the for angle1 = 25:step:100, // Rotate loop
plot3d1(t,t,sin(t)'*cos(t),angle1,45)
surface tilts around the x axis show_pixmap();
from 45 up to 80, with the end
rotation angle constant at for angle2 = 45:step:80, // Tilt loop
plot3d1(t,t,sin(t)'*cos(t),100,angle2)
100 show_pixmap();
end
With my 1.6 GHz laptop the f.pixmap="off";
animation does not run
perfectly smoothly, the jumps
from step to step are
noticeable
Demo 3 (3/3): a 3D
object, plot
The surface has reached
its destination: rotated to
100 (azimuth) and tilted
to 80 (elevation)
..
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 definition):
"Always program as if the person who will be maintaining your program is a violent
psychopath that knows where you live.
Martin Golding
Programming pitfalls
(1/4)
Computer programs cannot be tested to guarantee 100% reliability.
There is the danger of both hidden andin retrospectobvious
bugs.* Avoiding common programming pitfalls should be a
minimum goal and requires that we are familiar with them
Basic Scilab tutorials do not pay much attention to programming
pitfalls. Eine Einfhrung in Scilab by Bruno Pinon (original in
French, for me German is far easier) is an exception. Its last chapter
briefly discusses programming pitfalls. Worth taking a look at
A search on the web for Matlab pitfalls provides some hints. There
is also a useful discussion in Chapter 9 of Hahn, Valentine: Essential
Matlab for Engineers and Scientists, 3rd ed., Butterworth-Heine-
mann, 2007
*) 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 errors can broadly be grouped into the following types
Logical errors, meaning errors in the algorithm used to solve a problem
Syntax errors, meaning mistakes in the construction of Scilab statements
Rounding errors, meaning errors due to limited computer accuracy
Logical errors are mostly the result of our limited understanding of
the problem at hand and/or our limited knowledge of algorithms in
general and Scilab in particular
Syntax errors are generally speaking due to human limitations:
oversight, carelessness, forgetfulness, and the like. Typical cases are
misspelling, mismatched quote marks, wrong type of arguments, etc.
Rounding errors arise from truncations due to hardware limitations,
digitization of mathematical functions, converting between decimal
and binary mathematics, etc.
There is also a fourth type, namely errors made by Scilab system
designers and programmers. They show up as bugs, performance
limitations, poor user interfaces, and the like
Programming pitfalls
(3/4): error messages
Incompatible vector lengths
would be a better error message
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 file
ATOMS (2/6): whats
available
This is the ATOMS
main window. Texts
overlap a bit, but
basically it is a list
of contents
Go ahead and try to
find something of
interest, even if
there isnt much for
us engineers
Another problem is
that there is little
information about
what the modules
really can do for us
ATOMS (3/6): install
I decided to try
Stphanie
Motteletts
Plotting library
(this version
gives problems
with a Vista PC!)
Click on Install
An installation
message opens
at the bottom,
and after a good
while Scilab tells
that the module
has been
installed
ATOMS (4/6): new info
clear,clc,clf;
[X,Y]=meshgrid(-2:0.2:2,-1:0.2:1);
Z=cos(X.*Y);
surf(X,Y,Z);
hold on
[U,V,W] = surfnorm(X,Y,Z);
quiver3(X,Y,Z,U,V,W,'r');
Legend 'Surface normals'
colormap gray
hold off
Building a script library
Over time we accumulate a huge number of programs. How should
we administer them, how can we later find what we need?
This presentation demonstrates alternative ways of commenting
scriptsa most important subject when a program has to be
modified in the future
Pay attention to program names. Descriptive names help to identify
individual programs among other programs in a large file
Build your library of Scilab scripts in a logical manner. In this work I
have partly saved scripts on a thumb stick drive, in the file
H:\Dr.EW\Writings\Scilab examples\, under the assumption that this
presentation points to where to find a particular script. This is not a
the way to do it continuously, so give your own documentation
system a thoughtincluding the backup solution!
One option is to maintain a spreadsheet catalogue of programs with
information on what a specific script does, where it is located, which
functions it contains, etc. An advanced solution is documentation
software of the type used in requirements management
Dr.E
Dr.E
W
W
Johnny
JohnnyHeikell
Heikell
Return to Contents
Example 6-1: user
defined GUI, introduction
This example is a modification of START
the similar in Antonelli, Chiaverini:
Introduzione a Scilab 5.3, pp. 74-
80 Create initial GUI
The task is to create a GUI in the
Graphics Window (GW). The GUI
consists of No
Any changes?
A sine plot Implement
A slider for changing the angular Yes changes
frequency of the plot
EXIT pressed?
Two radiobuttons by which the No
properties of the plotted graph can
Yes
be changed
An exit button that closes the GUI Close GUI
The process is shown as a flow
diagram to the right
END
Ex 6-1: user defined GUI,
script (1/6) // GUI_italian.sce
script/
new_GUI_data(); // GOTO new_GUI_data()
endfunction
xdel();
funcprot(0);
The Main program // Define window size & position:
first deletes an //--------------------------------------------
existing GW screen_size = get(0,"screensize_px"); // Find computer screen size
size_x = .7*screen_size(3); // .7*screensize_px 3rd element
size_y = .7*screen_size(4); // .7*screensize_px 4th element
The size and location h_graph = scf(0); // Open Graphics Window
of the new GW is h_graph.figure_size = [size_x size_y]; // Define GW size
defined as a function h_graph.figure_position =... // Position GW in the...
[size_x/5 size_y/6]; // middle of the screen
of the total screen
size // Open GUI with inital plot:
//-------------------------------------
Here we pick up the initial_GUI();
initial plot that comes // Add EXIT button:
in the GW (GUI) //-------------------------
h_stop = uicontrol (h_graph,...
The next thing that "style","pushbutton",... // Declare pushbutton
"string","EXIT",... // Pushbutton label
we add to the GUI is "fontsize",14,...
the EXIT button. Note "backgroundColor",[1 0 0],... // Red button RGB
how many arguments "foregroundColor",[1 1 1],... // White label RGB
"position",[85 size_y-210 50 50],...
the uicontrol() "callback","xdel(0)"); // CLOSE GW if button pushed
function has
Ex 6-1: user defined GUI,
script (4/6)
Here is the uicontrol()
command that controls // Add slider & label:
the slider //--------------------------
h_slider= uicontrol(h_graph,...
strcat() is a function "style","slider",... // Declare slider
that we have not met "Min",0,... // Slider start value
"Max",100,... // Slider end value
before. Note that w and "value",50,... // Initial slider value
rad/s are surrounded by "position",[10 size_y-270 180 20],... // Slider size & location
double asterisks (' ' w ' "callback","update_slider();... // GOTO to update_slider()
foo = strcat([ ' w = ' string(h_slider.value/10)...
' and ' ' rad/s ' ' ), not ' rad/s ']);h_text_slider.string = foo");
by quotation marks slidelbl = strcat(["w = 5 rad/s"]); // Define initial label
h_text_slider = uicontrol(h_graph,...
(strings within a string) "style","text",... // Declare text
"horizontalalignment","center",... // Position in reserved field
This is the initial label "string",slidelbl,... // Add slider label
below the slider "fontsize",14,...
"backgroundColor",[1 1 1],... // White background
And the uicontrol() that "position",[10 size_y-310 180 20]); // Field size & location
takes care of label
changes
Ex 6-1: user defined GUI,
script (5/6)
The first radiobutton // Add radiobutton for graph style:
controls the style of //---------------------------------------------
h_radio1 = uicontrol(h_graph,...
the plotted sine curve "style","radiobutton",... // Declare radiobutton
(a solid line is the "Min",0,...
default, turns to a bar "Max",1,...
"value",0,... // Initial button value
graph when the "backgroundColor",[1 1 1],...
radiobutton is clicked) "position",[10 size_y-350 20 20],...
"callback","update_radio()"); // GOTO to update_radio()
The commands are h_text_radio1 = uicontrol(h_graph,...
"style","text",... // Declare button text
quite similar to the "horizontalalignment","left",...
ones of the slider, "string","-Change graph style",...
except that the foo "backgroundColor",[.8 .8 .8],... // Gray background
"fontsize",14,...
command is missing "position",[40 size_y-350 140 25]); // Field size & location
Notice the callback statements. They are the beasts that make us jump
up to (GOTO) the subroutine in case (here to update_radio())
Ex 6-1: user defined GUI,
script (6/6)
The second // Add radiobutton for graph color:
//----------------------------------------------
radiobutton controls h_radio2 = uicontrol(h_graph,...
the color of the "style","radiobutton",... // Declare radiobutton
"Min",0,...
plotted sine curve "Max",1,...
(black is the default, "value",0,... // Initial button value
turns to blue when "backgroundColor",[1 1 1],...
"position",[10 size_y-380 20 20],...
radiobutton is clicked) "callback","update_radio()"); // GOTO to update_radio()
h_radio2_txt = uicontrol(h_graph,...
This is mostly a "style","text",... // Declare button text
repetition of the "horizontalalignment","left",...
"string","-Change graph color",...
commands for the "backgroundColor",[.8 .8 .8],... // Gray background
first radiobutton, but "fontsize",14,...
the position in the GW "position",[40 size_y-380 140 25]); // Field size & location
is different // **** END MAIN **** //
Ex 6-1: user defined GUI,
and here it is
Click on
EXIT and
the window
closes
w clicked
down to 2
rad/s
Both
radiobuttons
have been
clicked
Problem: Scilab experiences a lockup if you drag the slider. The plot freezes
and the Consol reports that the current handle no longer exists
Ex 6-1: discussion
I copy-pasted the script from Antonelli & Chiaverini into Scilabs
Editor
The script had to be cleaned up and some redundancies could be
removed
I added the second radiobutton and organized the script in what I
thought was a more logical fashion
When I executed the script it opened up as expected, but the slider
was missing
After a frustrating weekend I did the whole thing from the beginning,
but now in steps. The error was that I had moved the if-then-end
construct in function new_GUI_data() after the plot2d() command
Lessons learned: Do the job stepwise and test as you progress
As for the lockup, my guess is that Scilab runs into a conflict
situation when it should update the handle and the previous update
still is in progress
Example 6-2: animation of a
waltzing polygon (1/4)
// animation_pincon_m2.sce
This demo is based on
Pinons Eine //------------------------------------------------------------------------------/
// The script plots the track of a blue polygon (rectangle) /
Einfhrung in Scilab // 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 /
The original contained // by changing element values in the matrix polygon. Changing /
errors, obsolete // theta arguments in the matrix align gives different effects /
//------------------------------------------------------------------------------/
functions, and redundant
commands. For instance, clear,clc,clf;
I transformed xset()
// Basic parameters:
functions to handle //----------------------
graphics commands (as steps = 100; // Steps per circular loop
blength = 0.6; // Basic length of polygon
explained in Chapter 7) width = 0.3; // Basic width of polygon
radius = 0.6; // Radius of circular loop
revolutions = 1; // Number of loops to run
Ex 6-2: animation of a
waltzing polygon (2/4)
The matrix polygon
defines length & width
of edges. Change them // Basic equations & definitions:
to different values and //------------------------------------
the rectangle is modified t = linspace(0,revolutions*2*%pi,steps)';
to a different polygon x_axis = radius*cos(t); // x-axis of circular loop
y_axis = radius*sin(t); // y-axis of circular loop
polygon = [-blength/2 blength/2 blength/2 -blength/2;...
Note the use of the -width/2 -width/2 width/2 width/2];
%inf constant to fill // Defines corners of polygon
missing arguments in
plot2d() // Set scale for isometric plot:
//---------------------------------
plot2d(%inf,%inf,frameflag=3, rect=[-1,-1,1,1], axesflag=0)
h=gca() declares h as a h = gca();
handle xtitle('Waltzing polygon')
h.background = 1; // Set background to black
The handle is first used
to set the background
color
Ex 6-2: animation of a
waltzing polygon (3/4)
The matrix align turns
the polygon into a new
angle. Change theta // Plot rectangle as it waltzes its loop:
values to see some //-------------------------------------------
turns = 3; // Number of turns per loop
interesting effects for i=1:steps
theta = turns*t(i); // Angle of polygon alignment
align = [cos(theta) -sin(theta);...
Here the handle is used sin(theta) cos(theta)]*polygon;
to set the fill color of // Realigns polygon
the polygon; the h.foreground = 2; // Set fill color to red
xfpoly(align(1,:)+x_axis(i), align(2,:)+y_axis(i))
process is executed by // Fills polygon with defined color
xfpoly() h.foreground = 5; // Change to blue for border
h.thickness = 3; // Set border thickness to 3
xpoly(align(1,:)+x_axis(i), align(2,:)+y_axis(i),'lines',1)
Next the handle defines // Draws polygon border in defined color
the border color; in this end
case the executing
function is xpoly()
Ex 6-2: animation of a
waltzing polygon (4/4)
cos(y)
Steps begin to show in the gray
scale if the color map definition
is changed to linspace(0,1,32),
where the argument 32 stands
for halved color resolution
chart, script
// Plots four colored sectors in predifined /
// directions and with predifined widths /
clear,clc,clf;
clear;clc,clf;
1(t) = 1(0)+a1t5+a2t4+a3t3+
+a4t2+a5t // Initial values, angles in degrees:
//---------------------------------------------
2(t) = 2(0)+b1t5+b2t4+b3t3+ tf = 2; // Finish time
theta10 = -19*%pi/180; // Theta 1 start position
+b4t2+b5t theta1tf = 43*%pi/180; // Theta 1 final position
theta20 = 44*%pi/180; // Theta 2 start position
Matrix equations are set up theta2tf = 151*%pi/180; // Theta 2 final position
and solved for coefficient
vectors (a, b), using given // Equations for a coefficients (velocity
// constraints have been taken into account):
initial values (0) and final //------------------------------------------------------------
values (tf), and the results T = [ tf^5 tf^4 tf^3
5*tf^4 4*tf^3 3*tf^2 // Angular velocity
are used to plot the path of 20*tf^3 12*tf^2 6*tf ]; // Angular acceleration
the robot hand c = [ theta1tf - theta10; 0; 0 ]; // Theta 1 movement
a = T\c // Coefficient vector a
disp(['Coefficients for theta1 motion:'])
disp([string(a')])
Ex 6-5: Robot arm (4/6),
Scilab conversion (2/2)
// Equations for b coefficients:
//---------------------------------------
By requiring that velocity d = [ theta2tf - theta20; 0; 0 ]; // Theta 2 movement
b= T\d // Coefficient vector b
and acceleration at t=0 be disp(['Coefficients for theta2 motion:'])
zero, the polynomial disp([string(b')])
coefficients a5 and a4
// Equations of motion:
become zero. This limits the //------------------------------
size of the T matrix L1 = 4; // Length of upper arm [feet]
L2 = 3; // Length of lower arm [feet]
(previous slide) to 3x3 t = linspace(0, 2, 401); // Computation steps
tq = [ t.^5; t.^4; t.^3 ];
The computed coefficient theta1 = theta10 + a'*tq; // Base motor angular speed
theta2 = theta20 + b'*tq; // Elbow motor angular speed
vectors a and b are used x1 = L1*cos(theta1) + L2*cos(theta1 + theta2); // x1 position
to define angular x2 = L1*sin(theta1) + L2*sin(theta1 + theta2); // x2 position
speeds, based upon
// Plot path of hand, add labels & legend:
which the hand position //------------------------------------------------------
is defined in x1 and x2 plot(x1,x2),..
coordinates 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)
Ex 6-5: Robot arm (5/6),
plot & display
20. Adieu
Final words to accompany you in
your struggle for survival of the
fittest
Return to Contents
Thats it, Folks!
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
Learning = hard brainwork + a tough rear end
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
When I think over what I have said, I envy dumb people.
Seneca (4 B.C.A.D. 65).