Professional Documents
Culture Documents
Programming With Scilab: Nfoclearinghouse
Programming With Scilab: Nfoclearinghouse
By
Gilberto E. Urroz, Ph.D., P.E.
Distributed by
i nfoClearinghouse.com
A "zip" file containing all of the programs in this document (and other
SCILAB documents at InfoClearinghouse.com) can be downloaded at the
following site:
http://www.engineering.usu.edu/cee/faculty/gurro/Software_Calculators/Scil
ab_Docs/ScilabBookFunctions.zip
2
2
3
3
Functions in SCILAB
Global and local variables
Special function commands
Debugging
An example of a function - Calculation of Frobenius norm of a matrix.
5
6
6
7
8
Input/Output in SCILAB
Saving and loading variables.
Unformatted output to the screen
Unformatted output to a file
Working with files.
Writing to files.
Reading from the keyboard
Reading from files
9
9
9
9
10
10
11
12
12
13
13
14
15
15
16
17
18
18
Exercises
19
Download at InfoClearinghouse.com
Programming is the basic skill for implementing numerical methods. In this chapter we
describe the fundamental programming constructs used in SCILAB and present examples of
their applications to some elementary numerical methods. The second part of this chapter is
dedicated at exploring input/output functions provided by SCILAB including operations with
files. Finally, manipulation of strings in SCILAB is presented.
<>
SCILAB logical operators are
==
<
>
<=
>=
or ~=
&
|
~
equal to
less than
greater than
less than or equal to
greater than or equal to
not equal to
and
or
not
Download at InfoClearinghouse.com
Loops in SCILAB
SCILAB includes For and While loops. The For loop is similar to the DO loop in FORTRAN or the
FOR..NEXT loop in Visual Basic. The basic construct for the For loop is:
for index = starting_value : increment : end_value, statements, end
for index = starting_value : end_value, statements, end
For and while loops can be terminated with the command break, for example, try the
following:
for j = 1:10, disp(j), if j>5 then break, end, end <enter>
Download at InfoClearinghouse.com
Note that since x is a row vector (actually a matrix with n = 1 row and m = 7 columns), the size
function provides you with an array of two values in the statement [n,m] = size(x). Then, m
is used in the for loop and in the calculation of xbar.
As an alternative to using a row (or column) vector is the use of lists. A list is a collection of
data objects not necessarily of the same type. In the following example we limit ourselves to
using lists of numbers. To define a list we use the list command, for example, try:
y = list(0., 1., 2., 3., 4., 6.) <enter>
size(y) <enter>
In this case, the size of the list, unlike that of a vector or matrix, is provided as a single
number. A modified version of the script in program1.txt is shown below. Type this file into
program2.txt and save it in the bin sub-directory under the SCILAB directory:
//Same as program1.txt, but using lists
clear
//erase all variables
x = list(10., -1., 3., 5., -7., 4., 2.);
suma = 0;
n = size(x);
for j = 1:n
suma = suma + x(j);
end
xbar = suma/n;
n
xbar
Download at InfoClearinghouse.com
Functions in SCILAB
Functions are procedures that may take input arguments and return zero, one or more values.
Functions are defined either on line, using the deff command, or as a separate file that needs
to be loaded using the getf command. Following some examples of on-line functions are
presented:
deff('[z]=Euler(r,theta)','z=r*exp(%i*theta)') <enter>
Euler(1.0,-%pi/2) <enter>
deff('[r,theta]=cartpol(x,y)',['r=sqrt(x^2+y^2)'; 'theta=atan(y,x)']) <enter>
[radius,angle] = cartpol(3., 4.) <enter>
These functions could have been defined by using the Define User Function option in SCILAB's
Functions menu. For example, select this option and enter the following (your reply is shown
in italics):
(1)
(2)
(3)
(4)
Where fname is the function name, [y1,,yn] is an array of output values, and x1,,xm are the
input values. Type in the following function into a file called sphecart.txt using a text editor
(e.g., NOTEPAD, or PFE):
function [x,y,z] = sphecart(r,theta,rho)
//conversion from spherical to Cartesian coordinates
x = r*cos(rho)*cos(theta)
y = r*cos(rho)*sin(theta)
z = r*sin(rho)
Download at InfoClearinghouse.com
Notice that SCILAB on-line functions are similar to FORTRAN function declarations, while
SCILAB functions defined in files are similar to FORTRAN or Visual Basic function sub-programs
or subroutines. The main difference is that FORTRAN and Visual Basic functions can only return
one value, while SCILAB functions can return zero, one or more values.
Since rho is defined in the calling environment, even though that value is missing in the calling
sequence to the function sphercart, it takes the value of rho in the calling environment.
Note that it is not possible to call a function if one of the parameters in the calling sequence is
not defined. Try the following:
clear
getf('sphercart.txt') <enter>
theta = %pi/3 <enter>
[x,y,z]=sphercart(10.0,%pi/3,rho) <enter>
Because rho is not defined in this case, the function can not be evaluated.
Download at InfoClearinghouse.com
Debugging
The simplest way to debug a SCILAB function is to use a pause command in the function. When
this command is encountered the function stops and the prompt -1-> is shown. This indicates
a different "level" of calculation that can be used to recall variable values including global
variables from the calling environment, experiment with operations, produce a graph if
needed, etc. Using a second pause will produce a new level characterized by the prompt -2>, and so on. The function resumes execution by typing the command return or resume, at
which point the variables used at the higher level prompts are cleared. Execution of the
function can be interrupted with the command abort.
An additional feature for debugging that is available in SCILAB is the insertion of breakpoints in
the function. These are pre-identified points in the function to which you can access during
the function execution to check the values of the variables or perform other operations. Check
the commands setbpt, delbpt, and disbpt.
You can also trap errors during the function execution by using the commands errclear and
errcatch. Check these commands using SCILAB help. At a higher level of expertise in SCILAB
debugging the user can try the function debug(i) where i = 0, 1, 2, 3, 4, denotes a debugging
level. Check out the debug function using help.
Download at InfoClearinghouse.com
|| A || F =
i =1 j =1
ij
The function AbsM(A), listed below, calculates the Frobenius norm of a matrix:
function [v]=AbsM(A)
// This function calculates the Frobenius norm of a matrix
// First obtain the matrix size
[n m] = size(A);
// Then initialize suma and add terms a(i,j)^2
suma = 0;
for i = 1:n
for j = 1:m
suma = suma + A(i,j)^2;
end
end;
// take square root and show result
v = sqrt(suma);
// end of the function
Within SCILAB try the following commands to load and run the function for a particular case:
clear <enter>
getf('AbsM.txt') <enter>
R = [1. 3. 4. 2. <enter>
3. -2. 5. -7. <enter>
1. 3. 4. 5. ] <enter>
AbsM(R) <enter>
Functions are defined throughout the book in relation to different mathematical subjects, i.e.,
vectors, matrices, integrals, differential equations, etc. The following sections of this chapter
deal with the subjects of input/output and string manipulation in SCILAB.
Download at InfoClearinghouse.com
Input/Output in SCILAB
Saving and loading variables.
To save variables in a file use the command save. Let's try some examples:
A = [1. 2. 3.; -3. 4. 5.; 2. 4. 5.; 1. 3. 2.]; b = 1:10; <enter>
A <enter>
b <enter>
save('DataAb.dat', A,b)<enter>
Next, using NOTEPAD or PDE, open the file DataAB.dat in sub-directory bin of SCILAB.
You will notice that you cannot see the numbers in the file. That is because they have
been saved in a binary format. Let's clear the variables in SCILAB and re-load the
values of A and b using the command load:
clear <enter>
load('DataAb.dat') <enter>
A <enter>
b <enter>
Download at InfoClearinghouse.com
Next, using NOTEPAD open the files data1.txt and data2.txt. Notice that the output
includes all the identifiers and brackets (!) provided by SCILAB.
status:
access:
format:
string,
"formatted" : for a formatted file (default)
"unformatted" : binary record.
recl:
unit:
err:
Once a file is open it can be used for input (read function) or output (write function).
Some examples of file opening, input and output are shown below.
Writing to files.
The following programs use the values of x, y, A, and r defined above. In these
examples we open and write to files, and close them. Notice that this command is
oriented towards printing matrices -- one at a time -- therefore, as shown in Example
2, it is better if you put together your data into a matrix before printing it. Notice also
that the format part, which is enclosed between quotes, is basically a FORTRAN
format.
Download at InfoClearinghouse.com
10
Example 1.
Example 2.
Example 3. Including labels. Note: labels are written separated from the variables
u = file('open','data3.txt','new')<enter>
write(u,A,'(3f10.6)') <enter>
file('close',u)<enter>
x1 = 0:0.5:10 <enter>
x2 = x1^2 <enter>
B = [x1',x2'] <enter>
m = file('open','data4.txt','new')<enter>
write(m,B,'(2(f10.6,2x))') <enter>
file('close',m)<enter>
Download at InfoClearinghouse.com
11
2.0
3.0
4.0
5.0
6.0
7.0
4.0
9.0
16.0
25.0
36.0
49.0
If you know the number of rows (n=6, in this case). To read the matrix of values, use:
u=file('open','signal.txt','old') <enter>
A=read(u,6,3); <enter>
A<enter>
If the number of rows is unknown using n=-1 will ensure that the entire file is read. It
is assumed that the file contains only the matrix of interest. For example,
file('rewind',u) <enter>
B = read(u,-1,3); <enter>
B <enter>
file('close',u) <enter>
Download at InfoClearinghouse.com
12
1 3 5
String concatenation
The joining of two or more strings is called concatenation. The plus symbol (+), when placed
between two strings concatenates the strings into a single one. In the next example variables
s1, s2, and s3 are defined and concatenated:
-->s1 = 'The result from '
s1 =
The result from
-->s2 = 'multiplication '
s2 =
multiplication
-->s3 = 'is given below.'
s3 =
is given below.
-->sOut = s1 + s2 + s3
sOut =
The result from multiplication is given below.
String functions
The function length determines the number of characters in a given string, for example:
-->length(sOut)
ans =
46.
The function part allows the extraction of characters from a given string. For example, to
extract the first character of a string use:
-->part('abcd',1)
ans =
a
The next command extracts the first and second character of a string:
-->part('abcd',[1,2])
ans =
ab
Download at InfoClearinghouse.com
13
ans
ac
To extract a series of character, the characters positions in the string are indicated as a
sequence of values in the vector representing the second argument to function part:
-->part(sOut,[4:1:15])
ans =
result from
The function strindex (string index), with a typical call of the form strindex(string1,string2)
determines the position of the first occurrence of sub-string string2 within string1. For
example,
-->strindex(sOut,'mult')
ans =
17.
Once the position of a sub-string has been determined you can use the function part to extract
that sub-string or other sub-string starting at that position. For example, this function call
extracts characters 17 to 24 of string sOut:
-->part(sOut,[17:24])
ans =
multipli
The function strsubst (string substitution), with a typical call of the form
strsubst(string1,string2,string3)
replaces sub-string string2 with sub-string string3 within string string1. For example, the next
call to function strsubst replaces the sub-string multiplication with division within
string sOut:
-->strsubst(sOut,'multiplication','division')
ans =
The result from division is given below.
Download at InfoClearinghouse.com
14
ans
The sum is 7
The following command produces an array or vector of strings. The strings in the vector
represent the numbers from 1 to 5.
-->sNum = string(1:5)
sNum =
!1
An attempt to add the first two elements of vector sNum produces instead their concatenation,
verifying that the elements are indeed strings, and not numbers:
-->sNum(1)+sNum(2)
ans =
12
1.
2.
3.
4.
5. !
The plus sign (+) applied to the two first elements of nNum would add, rather than
concatenate, those elements:
-->nNum(1) + nNum(2)
ans =
3.
Download at InfoClearinghouse.com
15
The function evstr can be used to evaluate numerically any string representing number
operations. Some examples are shown below:
-->evstr('2+2')
ans =
4.
-->evstr('sin(%pi/6) + 1/3')
ans =
.8333333
The following example uses function evstr to evaluate the numerical values defined in the
elements of a vector. This particular example uses the values of a couple of variables, s and
m, which must be defined before attempting the evaluation of the strings.
-->s = 2, m = 3
s =
2.
=
3.
2.
1.4142136
5. !
Although the statement a=1 is executed through the use of execstr, no output is produced. To
check that the statement was indeed executed, request that SCILAB show the value of a:
-->a
a =
1.
You can use execstr to evaluate a series of commands by placing the commands in an array or
vector:
-->execstr(['a=1','b=2','a+b'])
Once again, no output is shown, so the result from the last element in the vector is lost, but
variable b (from the second element in the vector) was indeed stored:
Download at InfoClearinghouse.com
16
-->b
b =
2.
2.
3.
1.4142136
5. !
The following example shows the execution of a small program whose lines are presented as
string elements of a vector:
-->execstr(['a=2' 'x=[]' 'for j = 1:4' 'x = [x a^j]' 'end'])
2.
4.
8.
16.
-->for j = 1:m, 'distance no. ' + string(j) + ' is ' + string(d(j)) + '.', end
ans =
distance no. 1 is
ans =
.5.
distance no. 2 is
ans =
.75.
distance no. 3 is 1.
ans =
distance no. 4 is 1.25.
ans =
distance no. 5 is 1.5.
Download at InfoClearinghouse.com
17
.5.
distance no. 2 is
.75.
distance no. 3 is 1.
distance no. 4 is 1.25.
distance no. 5 is 1.5.
The function disp can be used to display any result, not only strings. The following example
shows the function disp used with string as well as numerical output:
-->a = 2; A = [2,3;-1,4]; B = a*A;
-->disp('Matrix B is:'), disp(B)
Matrix B is:
!
4.
! - 2.
6. !
8. !
__________________________________________________________________________________
__________________________________________________________________________________
Download at InfoClearinghouse.com
18
Exercises
[1]. Write a SCILAB function to calculate the factorial of an integer number:
n! = n(n-1)(n-2)321
[2]. Write a SCILAB function to calculate the standard deviation of the data contained in a
vector x = [x1 x2 x3].
s=
1 n
(x k x )2 ,
n 1 k =1
s=
1 n
xk .
n k =1
0
,
elsewhere
Download at InfoClearinghouse.com
19
C (n, k ) =
n!
.
k!(n k )!
Write a SCILAB function that produces a table of binomial coefficients for n = 1, 2, , 5. Use
the function developed in exercise [1] to calculate factorials of integer numbers.
[8]. Write a SCILAB program to define a function given by
[10]. Write a SCILAB function that request from the user the values of the initial position
(x0,y0) of a projectile, the initial velocity given as a magnitude v0, and an angle 0, and the
acceleration of gravity g (see figure below). The function also requests from the user an
initial time t0, a time increment t, and an ending time tf. The function produces a table of
values of the velocity components vx = v0 cos(0), vy = v0 cos(0), the magnitude of the velocity,
v = (vx2+vy2)1/2, the position of the projectile, x = xo + v0 cos(0)t, y = yo + v0 sin(0)t - gt2/2, and
the distance of the projectile from the launching point, r0 = ((x-x0)2+(y-y0)2)1/2. The function
also produces plots of x - vs. - t, y - vs. - t, r0 - vs. - t, and y - vs. -x in different graphic
windows. [Note: to generate a new graphics window use the SCILAB command ->xset(window,j) where j is the window number.]
Download at InfoClearinghouse.com
20
[11]. Suppose you want to plot the function r() = 3.5(1 - cos(2 )). Write a SCILAB function
that generates values of from 0 to 2, calculates the values of r, and the Cartesian
coordinates x = r cos(), y = r sin(), and prints a table showing those values, i.e., , r, x, and
y. The function also produces a plot of y-vs.-x.
Download at InfoClearinghouse.com
21
Kreysig, E., 1983, "Advanced Engineering Mathematics - Fifth Edition," John Wiley & Sons, New York.
Lindfield, G. and J. Penny, 2000, "Numerical Methods Using Matlab," Prentice Hall, Upper Saddle River, New Jersey.
Magrab, E.B., S. Azarm, B. Balachandran, J. Duncan, K. Herold, and G. Walsh, 2000, "An Engineer's Guide to
MATLAB", Prentice Hall, Upper Saddle River, N.J., U.S.A.
McCuen, R.H., 1989,Hydrologic Analysis and Design - second edition, Prentice Hall, Upper Saddle River, New Jersey.
Middleton, G.V., 2000, "Data Analysis in the Earth Sciences Using Matlab," Prentice Hall, Upper Saddle River, New
Jersey.
Montgomery, D.C., G.C. Runger, and N.F. Hubele, 1998, "Engineering Statistics," John Wiley & Sons, Inc.
Newland, D.E., 1993, "An Introduction to Random Vibrations, Spectral & Wavelet Analysis - Third Edition," Longman
Scientific and Technical, New York.
Nicols, G., 1995, Introduction to Nonlinear Science, Cambridge University Press, Cambridge CB2 2RU, U.K.
Parker, T.S. and L.O. Chua, , "Practical Numerical Algorithms for Chaotic Systems, 1989, Springer-Verlag, New York.
Peitgen, H-O. and D. Saupe (editors), 1988, "The Science of Fractal Images," Springer-Verlag, New York.
Peitgen, H-O., H. Jrgens, and D. Saupe, 1992, "Chaos and Fractals - New Frontiers of Science," Springer-Verlag, New
York.
Press, W.H., B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, 1989, Numerical Recipes - The Art of Scientific
Computing (FORTRAN version), Cambridge University Press, Cambridge CB2 2RU, U.K.
Raghunath, H.M., 1985, "Hydrology - Principles, Analysis and Design," Wiley Eastern Limited, New Delhi, India.
Recktenwald, G., 2000, "Numerical Methods with Matlab - Implementation and Application," Prentice Hall, Upper
Saddle River, N.J., U.S.A.
Rothenberg, R.I., 1991, "Probability and Statistics," Harcourt Brace Jovanovich College Outline Series, Harcourt Brace
Jovanovich, Publishers, San Diego, CA.
Sagan, H., 1961,"Boundary and Eigenvalue Problems in Mathematical Physics," Dover Publications, Inc., New York.
Spanos, A., 1999,"Probability Theory and Statistical Inference - Econometric Modeling with Observational Data,"
Cambridge University Press, Cambridge CB2 2RU, U.K.
Spiegel, M. R., 1971 (second printing, 1999), "Schaum's Outline of Theory and Problems of Advanced Mathematics for
Engineers and Scientists," Schaum's Outline Series, McGraw-Hill, New York.
Tanis, E.A., 1987, "Statistics II - Estimation and Tests of Hypotheses," Harcourt Brace Jovanovich College Outline
Series, Harcourt Brace Jovanovich, Publishers, Fort Worth, TX.
Tinker, M. and R. Lambourne, 2000, "Further Mathematics for the Physical Sciences," John Wiley & Sons, LTD.,
Chichester, U.K.
Tolstov, G.P., 1962, "Fourier Series," (Translated from the Russian by R. A. Silverman), Dover Publications, New York.
Tveito, A. and R. Winther, 1998, "Introduction to Partial Differential Equations - A Computational Approach," Texts in
Applied Mathematics 29, Springer, New York.
Urroz, G., 2000, "Science and Engineering Mathematics with the HP 49 G - Volumes I & II", www.greatunpublished.com,
Charleston, S.C.
Urroz, G., 2001, "Applied Engineering Mathematics with Maple", www.greatunpublished.com, Charleston, S.C.
Winnick, J., , "Chemical Engineering Thermodynamics - An Introduction to Thermodynamics for Undergraduate
Engineering Students," John Wiley & Sons, Inc., New York.
Download at InfoClearinghouse.com
22