58
Appendix B Programming with Scilab Module contents B.1 Introduction .................... 226 B.2 Getting started with Scilab ........... 227 B.3 Variables ....................... 229 B.4 Arithmetic expressions .............. 232 B.4.1 Precedence .................... 232 B.4.2 Matrix arithmetic ................ 233 B.4.3 Array arithmetic ................. 235 B.5 Built–in functions ................. 237 B.5.1 Arithmetic functions ............... 237 B.5.2 Utility functions ................. 240 B.6 Visualising data in Scilab ............. 241 B.6.1 Plotting mathematical functions from within Scilab ...................... 241 B.6.2 Adding titles,labels and legends to the plot . . 244 B.6.3 Plotting numeric data stored in an ASCII file . 247 B.7 Script files ...................... 248 B.7.1 Script input and output ............. 250 B.7.2 Formatting script files .............. 257 B.8 Function files .................... 260 B.8.1 Local variables .................. 265 B.9 Control structures ................. 265 B.9.1 Relational operations ............... 266 B.9.2 Logical operations ................ 267 B.9.3 Branch controls (conditional statements) .... 269 B.9.4 Iteration controls (explicit loops) ........ 273 B.9.5 Implicit loops ................... 278 B.9.6 Using functions and scripts together ...... 279 B.10 Numerical programming ............. 280 B.10.1 Modular Programs ................ 280 B.10.2 Debugging ..................... 281 This module will lead you through numerical programming using Scilab. When studying this module 1 , peruse all of the appendix first so that you have some idea of what can be found in it should you need it in the course of writing programs for the other modules. 1 Everything in this module will be required when implementing the numerical methods discussed in the rest of the course. Use this module as a reference throughout the rest of the course. 225

Programming With Scilab

Embed Size (px)

DESCRIPTION

Programming With Scilab

Citation preview

Page 1: Programming With Scilab

Appendix B Programming with Scilab

Module contents

B1 Introduction 226

B2 Getting started with Scilab 227

B3 Variables 229

B4 Arithmetic expressions 232

B41 Precedence 232

B42 Matrix arithmetic 233

B43 Array arithmetic 235

B5 Builtndashin functions 237

B51 Arithmetic functions 237

B52 Utility functions 240

B6 Visualising data in Scilab 241

B61 Plotting mathematical functions from withinScilab 241

B62 Adding titleslabels and legends to the plot 244

B63 Plotting numeric data stored in an ASCII file 247

B7 Script files 248

B71 Script input and output 250

B72 Formatting script files 257

B8 Function files 260

B81 Local variables 265

B9 Control structures 265

B91 Relational operations 266

B92 Logical operations 267

B93 Branch controls (conditional statements) 269

B94 Iteration controls (explicit loops) 273

B95 Implicit loops 278

B96 Using functions and scripts together 279

B10 Numerical programming 280

B101 Modular Programs 280

B102 Debugging 281

This module will lead you through numerical programming usingScilab When studying this module1 peruse all of the appendixfirst so that you have some idea of what can be found in it shouldyou need it in the course of writing programs for the other modules

1 Everything in this module will be required when implementing the numericalmethods discussed in the rest of the course Use this module as a referencethroughout the rest of the course

225

226 Appendix B Programming with Scilab

Then in conjunction with the numerical modules in the StudyBook you should refer to this appendix repeatedly as you attemptthe programming exercises throughout the course This way yourprogramming skills will build up through writing programs Youcannot learn how to write programs through reading alone anymore than you can learn how to drive a car from a manual

B1 Introduction

Scilab is an interactive programming environment It allows theuser to interact directly with the Scilab interpreter through acommand window Commands typed in at the command windoware executed immediately Coupled with the rich graphical capa-bilities of Scilab the immediacy of the command window makesit a good tool for data visualisation and investigating ideas andconcepts

Using Scilab for numerical methods requires you to develop skillin writing functions to perform various algorithms Not only mustyou have it clear in your mind what has to be done (the algorithm)but you also need to analyse carefully which of the tasks will beuseful stand-alone tools

Functions are used repeatedly in their area of application either tosupply answers to well defined problems or to build other functionsto answer work specific problems The important thing about afunction is that having identified a well known task what dataare required to complete the task and a way (or algorithm) forcompleting the task all this information is stored away and can berecalled at will If written carefully functions are reusable acrossprojects and problems

The skill of writing an effective function cannot be acquired byjust reading text like this module To develop skills in writing nu-merical programs requires more than reading it requires you towrite programs and to learn from the experience of writing pro-grams We recommend that this module be used as a referencethroughout the course Everything in this module will be requiredwhen implementing the numerical methods discussed in the courseYour skill as a Scilab programmer should develop as the courseprogresses and you are called on to write more complex programsAs you write and use functions you will begin to appreciate thefeatures that make a particular function useful and what featureslimit a functionrsquos usefulness

When data is to be collected from the console or file there shouldbe special functions designed to do just that jobmdashthey may presenton-screen menus boxes to be filled in icons to be clicked on and soforth Designing a user interface is a whole area of study in itselfScilab does provide some interface tools which lead to quite a

B2 Getting started with Scilab 227

professional looking product but it would take us the whole courseto master these and for the most part we will leave this activity toother courses Ours will be a study of efficient numerical techniquesand display of results will be plain and simple that is why thiscourse is called High Performance Numerical Computing

B2 Getting started with Scilab

Starting Scilab will give a command window similar to the oneshown in Figure B1 Commands are entered at the cursor (--gt)Each command is executed when either the return or enter key ispressed Any command execution can to be interrupted by pressinginterrupt a running command

Ctrl amp C keys together To exit Scilab simply type exit orquit at the command prompt2 Earlier commands executed inquitexit

a session can be recalled using the up (uarr)down (darr) keys on thekeyboard Once recalled the command can either be edited usingthe keyboard or re-executed by pressing the returnenter key Itis also possible to combine multiple commands on the one commandline by separating the commands using either a comma () or asemi-colon () The semi-colon () suppress any output from thesuppressing output from a

command command being executed

Figure B1 The default Scilab Command Window

Help about commands and functions can be obtained by typinghelp at the command plot This will bring up a window where youhelp

2 Note as with all commands in Scilab this will not be executed until eitherthe return or entry is pressed

228 Appendix B Programming with Scilab

can search for help on version topics Note you can short-cut thiswindow if you know the name of the command or function for whichyou require help by typing help command or function name atthe command prompt For example to get help on the log func-tion you would simply type help log at the command promptIn Scilab it is also possible to search for commands andor func-tions which contain certain keywords using the apropos commandapropos

As example the command apropos(rsquologarithmrsquo) will list all thecommands in Scilab relating to logarithms

Example B1 Sample commands in Scilab

--gt3^2-5-632

ans =

0

--gt3^2-5-6(32)

ans =

3

--gt42^2+1

ans =

17

--gtsin(pi2)

ans =

1

--gtsqrt(25)

ans =

5

--gtsqrt(-4)

ans =

2i

--gta1=5b1=3c1=sqrt(a1+b1)

a1 =

5

b1 =

3

c1 =

28284271

--gtans

ans =

2i

--gtt=linspace(0pi26)

t =

0 03141593 06283185 09424778 12566371 15707963

--gty=cos(t)

y =

1 09510565 08090170 05877853 03090170 6123D-17

Example B1 illustrates an important feature of the Scilab com-putational engine If an expression is just typed in and evaluatedthe answer is stored in a special variable called ans This vari-ans

B3 Variables 229

able contains the value of last unassigned (see sectB3 for details onhow variables are assigned) evaluation performed Hence the valuestored in ans changes each time an unassigned calculation is per-formed in Scilab as illustrated in Example B1 Consequentlyif you intend to reuse values of calculations you should store theresults in a variable (see sectB3) to avoid the possible of using theincorrect result

Activity BA To familiarise yourself with some of the basic features of rarrScilab and how to use it for elementary arithmetic andas a sophisticated calculator try some of the examples inExample B1 Make sure you understand what Scilabdid to calculate the answer Also as you work throughthe appendix attempt all the examples and exercises asyou come to them

B3 Variables

Variables are used in a programming language as tags to memorylocations in the computer The data stored in the memory locationis accessed using the variable name in the program The variableis not attached to the data but the memory location This meansthat the value contained within a variable can change

In languages such as C every variable must be declared before it isused specifying both its name and its type The name and type ofvariables do not need to be pre-declared in Scilab In Scilab anyvariable can take integer real complex scalar string or matrixvalues Languages that pre-declare variables have clearly statedat the start of a program or function the type of every variableused The Scilab interpreterrsquos liberal approach to variable typeshas both advantages and disadvantages

The equality sign (=) is used to assign the values to a variableassigning values to

variables This is an unfortunate choice of symbol and means that when wewant to test whether two quantities are equal or not we cannot usethe equal symbol = but must use the more cumbersome == Thus5+2 == 3+4 is true but 5+2 = 3+4 is a syntax error In Scilabprograms the equals sign does not have its mathematical meaningIt is an assignment operator The statement to the right of theequals sign is evaluated and the result is placed in the memorylocation tagged by the variable name on the left For example thestatement x = 3 + 5 means Scilab evaluates the statement onthe right and stores the result in the memory location tagged bythe variable x This means that the statement 3+ 5 = x whichis equivalent to x= 3 + 5 in mathematics will lead to an errormessage in Scilab

The following are examples of variable types in Scilab (it is notcomplete but contains all the variable types that you will encounter

230 Appendix B Programming with Scilab

in this course)

x = 3 Assign the scalar integer value 3 to the variable x

x = 7297e17 Assign the scalar real value 7297 times 1017 to the variable xThe number has been defined using the scientific exponentnotation The number following the e is the power of 10 tomultiply the number in front of the e Either e or E can beused

x = rsquoNorthrsquo Assign the string North to the variable x Strings of char-acters are defined by surrounding the characters with apos-trophes The construct rsquoSouthrsquo defines a constant stringcontaining the characters South

x = 05100 Assign the row vector containing 21 elements from 0 to 100in steps of 5 to the variable x

x = [12 13 25 67] Assign the 2times 2 matrix to the variable x so that

x =

[12 13

25 67

]

x = 51+i63 Assign the complex number 51+ i63 to the variable x

Variable names can be of any length but must be unique withinthe first 31 characters Variable names in Scilab are case sensi-tive that is the variables time and Time are distinct Howeverfunctions and scripts (which we discuss later) are stored in sepa-rate files (with extension sce) outside the interpreter and may ormay not be case sensitive depending on the outside environment(in a dos environment for example they will not be)

Scilab allows overloading of names This means that if you choosea name that has been predefined by Scilab you loose the builtin meaning For example cos = 634 defines a scalar variablecos but it is also the same name for the Scilab cosine functionThe variable assignment means that the cosine function will nolonger be accessible in this session All references to the name coswill assume the variable not the function Take care not to usevariable names that might disable built in functions or constantsthat you may need later When writing scripts for others to usethe names of all variables that will be over-written by the runningof the script must be listed for easy reference (and one shouldread these references before running any script) This is one ofthe reasons why it is nearly always preferable to write functionsrather than scripts Variables defined in the course of runninga functionrsquos algorithm remain local to the function and do notover-write workspace variables

The results of all calculations should be assigned to a variable sothat this value can be used later If this is not done the result

B3 Variables 231

Table B1 Special variables and constants in ScilabName Description

pi The value of π to the precession of the machineis returned

i Recognised as theradicminus1

inf This is Scilabrsquos representation of infin This is arecognised value in a variable and typically ap-pears as a result of division by zero or logarithmof zero

nan Stands for Not a Number This is a recognisedvalue in a variable and appears as a result ofa mathematically undefined operation such asdivision of zero by zero or infinminusinfin

eps Floating point relative accuracy That is epsreturns the smallest difference resolvable be-tween two floating point numbers For examplethe next largest representable number beyond10 is 10+eps Scilab cannot represent anyfloating point number that falls between 10 and10+eps

ans This variable contains the last computed expres-sion that was not stored in a variable

date This variable contains a string representation oftodayrsquos date in the format dd-mmm-yyyy Forexample 01-Apr-2000

232 Appendix B Programming with Scilab

Table B2 Scilab Arithmetic OperatorsOperator Meaning Scilab

^ Exponentiation xy x^y

Multiply xtimes y xy

Right Division xy = xy xy

Left Division yx = xy yx

+ Addition x+ y x+y

- Subtraction xminus y x-y

of a calculation will be stored in a special variable called ans (seeans

Table B1) The value stored in this variable is overridden the nexttime a calculation is done that is not assigned to a variable Thismeans that the result from the previous calculation is then lost

B4 Arithmetic expressions

Table B2 lists the basic arithmetic operators to be found in ScilabWith the exception of the left division operator the arithmetic op-erators in Scilab follow standard notation

B41 Precedence

When more than one operation appears in a mathematical state-ment the programming language needs to define in which order theoperations must be performed or the precedence That is whichparts are evaluated first

If precedence was not defined then the same statement can be eval-uated to a different result for example is 186+3 equal to 2 oris 186+3 equal to 6 The first statement is evaluated from theright using the precedence rule that usually applies in mathemat-ical statements that is work from right to left as for example inlsquosin log tan xrsquo where we start with a value of x compute the tan-gent of that value (tan x) then take the logarithm of the resultingnumber (log(tan x)) and finally take the sine of what this deliv-ers However it is usual (because it is much easier to write poly-nomials with this convention) to give multiplication and divisionprecedence over addition and subtraction The second statementrecognises the precedence of the division over addition and evalu-ates it first Right to left precedence has a much simpler parsingtree than schemes which give precedence to particular operatorsbut the common arithmetic precedences are so widely acceptedand expected that most computer language designers will not riskthe possible lsquoconsumer backlashrsquo that breaking with this traditionwould involve So with every computer language one must searchout and learn the precedence rules that it adopts The usual arith-metic precedences will normally be observed but note that even

B4 Arithmetic expressions 233

Table B3 Precedence of arithmetic expressionsOperator Precedence Order of evaluation

() 1 Left to right innermost first 2 Left to right 3 Left to right 4 Right to left

+ minus 5 Left to right

they are not unambiguous For example which divide has prece-dence in 41632 Working right to left one would get the answerof 8 but Scilab returns (the decimal for) 1128 mdashit works fromleft to right Table B3 lists the operators and their precedencevalue

The rules for evaluation of operators are as follows

bull Operators having high precedence (low numerical value) willbe evaluated before those having a low precedence (high nu-merical value)

bull If an expression contains more than one operator at the samelevel of precedence then the left-to-right rule of evaluationapply

Parentheses () always have the highest precedence Whateveris within the parentheses is evaluated first This means when indoubt about the order of any statement place parentheses aroundthe statement to ensure that the operations are performed in theorder you expect

B42 Matrix arithmetic

One of the strengths of Scilab is its ability to execute matrixarithmetic3 Matrix arithmetic must be implemented in other lan-guages with many lines of code or special functions Scilab isespecially designed to handle matrix arithmetic The representsmatrix multiplication or scalar multiplication of a matrix if one ofthe arguments is a scalar Since scalars are 1times1 matrices ordinaryscalar multiplication can also be performed by the operator Thedot product of two vectors however requires that the first vectorbe a row vector and the second a column vector To multiply thecorresponding elements in two vectors together requires a differentoperator so that

gt a = [2 3 4] b = [6 7 8]

a b

ans =

12 21 32

3 Remember vectors are examples of matrices A column vector of length nis an example of a ntimes 1 matrix

234 Appendix B Programming with Scilab

However because it is a matrix operation

gt a + b

ans =

8 10 40

The standard arithmetic operators described in Table B2 are alsoused with matrices The normal rules of matrix addition subtrac-tion and multiplication apply

The left and right division of matrices are also generalisations ofscalar division Right division BA is roughly the same as Binv(A)Left division AB is roughly the same as inv(A)B The differenceis in how the division is performed Different algorithms are usedwhen A or B are square or not

Scilab also defines a transpose operator for matrices The trans-pose of the matrix A is Arsquo For example if

A =

[25 63

12 09

] then A prime =

[25 12

63 09

]

Accessing matrix elements

Individual elements of a matrix can accessed and used in state-ments by specifying the matrix index of an element The index ofan element is its position in the matrix For example consider thefollowing matrix

A =

6 minus1 4

3 5 7

minus3 6 1

Define this in Scilab with the command

A=[ 6 -1 4 3 5 7 -3 6 7]

to display the contents of matrix A in Scilab just type the variablename A To display or use one element from the matrix specify theelement For example A(13) specifies the element in the first rowand third column that is 4 for the above matrix

To change a specific entry just assign a value to it For example

A(31)=-9

changes the value of the third row first column element from -3

to -9

To display or use a whole row or column use the operator Forexample

gt A(2)

ans =

3 5 7

gt A(2)

B4 Arithmetic expressions 235

ans =

-1

5

6

It is also possible to pick out a sub-matrix by the specifying the rowand column entries required For example To pick out the sub-matrix of A containing the elementsA11 A13 A21 A23 the commandA(12123) could be used as shown below

gt A(12123)

ans =

6 4

3 7

Note 123 means from 1 to 3 in steps of 2 This technique alongwith the assignment operator can be used for values of whole rowscolumns or sub-matrices in one command For example

gt A(12123)=[10111213]

A =

10 -1 11

12 5 13

-3 6 7

Note that the elements A11 A13 A21 A23 now contain the values10 11 12 and 13 respectively instead of their previous values

Index notation is logically an unfortunate phenomenon since itclashes with standard function notation On the face of it A(3)

should be the value of a function called A with input 3 but whenit is interpreted as index notation A is a variable However indexnotation is so familiar and useful to those familiar with classicalmathematical notation that many developers of mathematical soft-ware are not prepared to risk a ldquoconsumer backlashrdquo to providinga functional way of extracting elements from an array such as forexample 3 pick A to pick out the third element of A Similarlywe as teachers feel we would be doing students a disservice if wefailed to introduce them to the index notation that abounds inmathematical texts usually in the form of subscripting as in A3Logic does not always win an argument In the commercial worldof computing an established user base carries more weight thanmathematical logic just as in mathematics tradition may well alsofly in the face of logical consistency

B43 Array arithmetic

Scilab has two forms of arithmetic operations that can be usedwith matrices matrix arithmetic or array arithmetic Matrix arith-metic follows the normal rules of matrix algebra Array arithmeticwhich is also called element-by-element arithmetic is where oper-ations are performed on matrices element by element

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 2: Programming With Scilab

226 Appendix B Programming with Scilab

Then in conjunction with the numerical modules in the StudyBook you should refer to this appendix repeatedly as you attemptthe programming exercises throughout the course This way yourprogramming skills will build up through writing programs Youcannot learn how to write programs through reading alone anymore than you can learn how to drive a car from a manual

B1 Introduction

Scilab is an interactive programming environment It allows theuser to interact directly with the Scilab interpreter through acommand window Commands typed in at the command windoware executed immediately Coupled with the rich graphical capa-bilities of Scilab the immediacy of the command window makesit a good tool for data visualisation and investigating ideas andconcepts

Using Scilab for numerical methods requires you to develop skillin writing functions to perform various algorithms Not only mustyou have it clear in your mind what has to be done (the algorithm)but you also need to analyse carefully which of the tasks will beuseful stand-alone tools

Functions are used repeatedly in their area of application either tosupply answers to well defined problems or to build other functionsto answer work specific problems The important thing about afunction is that having identified a well known task what dataare required to complete the task and a way (or algorithm) forcompleting the task all this information is stored away and can berecalled at will If written carefully functions are reusable acrossprojects and problems

The skill of writing an effective function cannot be acquired byjust reading text like this module To develop skills in writing nu-merical programs requires more than reading it requires you towrite programs and to learn from the experience of writing pro-grams We recommend that this module be used as a referencethroughout the course Everything in this module will be requiredwhen implementing the numerical methods discussed in the courseYour skill as a Scilab programmer should develop as the courseprogresses and you are called on to write more complex programsAs you write and use functions you will begin to appreciate thefeatures that make a particular function useful and what featureslimit a functionrsquos usefulness

When data is to be collected from the console or file there shouldbe special functions designed to do just that jobmdashthey may presenton-screen menus boxes to be filled in icons to be clicked on and soforth Designing a user interface is a whole area of study in itselfScilab does provide some interface tools which lead to quite a

B2 Getting started with Scilab 227

professional looking product but it would take us the whole courseto master these and for the most part we will leave this activity toother courses Ours will be a study of efficient numerical techniquesand display of results will be plain and simple that is why thiscourse is called High Performance Numerical Computing

B2 Getting started with Scilab

Starting Scilab will give a command window similar to the oneshown in Figure B1 Commands are entered at the cursor (--gt)Each command is executed when either the return or enter key ispressed Any command execution can to be interrupted by pressinginterrupt a running command

Ctrl amp C keys together To exit Scilab simply type exit orquit at the command prompt2 Earlier commands executed inquitexit

a session can be recalled using the up (uarr)down (darr) keys on thekeyboard Once recalled the command can either be edited usingthe keyboard or re-executed by pressing the returnenter key Itis also possible to combine multiple commands on the one commandline by separating the commands using either a comma () or asemi-colon () The semi-colon () suppress any output from thesuppressing output from a

command command being executed

Figure B1 The default Scilab Command Window

Help about commands and functions can be obtained by typinghelp at the command plot This will bring up a window where youhelp

2 Note as with all commands in Scilab this will not be executed until eitherthe return or entry is pressed

228 Appendix B Programming with Scilab

can search for help on version topics Note you can short-cut thiswindow if you know the name of the command or function for whichyou require help by typing help command or function name atthe command prompt For example to get help on the log func-tion you would simply type help log at the command promptIn Scilab it is also possible to search for commands andor func-tions which contain certain keywords using the apropos commandapropos

As example the command apropos(rsquologarithmrsquo) will list all thecommands in Scilab relating to logarithms

Example B1 Sample commands in Scilab

--gt3^2-5-632

ans =

0

--gt3^2-5-6(32)

ans =

3

--gt42^2+1

ans =

17

--gtsin(pi2)

ans =

1

--gtsqrt(25)

ans =

5

--gtsqrt(-4)

ans =

2i

--gta1=5b1=3c1=sqrt(a1+b1)

a1 =

5

b1 =

3

c1 =

28284271

--gtans

ans =

2i

--gtt=linspace(0pi26)

t =

0 03141593 06283185 09424778 12566371 15707963

--gty=cos(t)

y =

1 09510565 08090170 05877853 03090170 6123D-17

Example B1 illustrates an important feature of the Scilab com-putational engine If an expression is just typed in and evaluatedthe answer is stored in a special variable called ans This vari-ans

B3 Variables 229

able contains the value of last unassigned (see sectB3 for details onhow variables are assigned) evaluation performed Hence the valuestored in ans changes each time an unassigned calculation is per-formed in Scilab as illustrated in Example B1 Consequentlyif you intend to reuse values of calculations you should store theresults in a variable (see sectB3) to avoid the possible of using theincorrect result

Activity BA To familiarise yourself with some of the basic features of rarrScilab and how to use it for elementary arithmetic andas a sophisticated calculator try some of the examples inExample B1 Make sure you understand what Scilabdid to calculate the answer Also as you work throughthe appendix attempt all the examples and exercises asyou come to them

B3 Variables

Variables are used in a programming language as tags to memorylocations in the computer The data stored in the memory locationis accessed using the variable name in the program The variableis not attached to the data but the memory location This meansthat the value contained within a variable can change

In languages such as C every variable must be declared before it isused specifying both its name and its type The name and type ofvariables do not need to be pre-declared in Scilab In Scilab anyvariable can take integer real complex scalar string or matrixvalues Languages that pre-declare variables have clearly statedat the start of a program or function the type of every variableused The Scilab interpreterrsquos liberal approach to variable typeshas both advantages and disadvantages

The equality sign (=) is used to assign the values to a variableassigning values to

variables This is an unfortunate choice of symbol and means that when wewant to test whether two quantities are equal or not we cannot usethe equal symbol = but must use the more cumbersome == Thus5+2 == 3+4 is true but 5+2 = 3+4 is a syntax error In Scilabprograms the equals sign does not have its mathematical meaningIt is an assignment operator The statement to the right of theequals sign is evaluated and the result is placed in the memorylocation tagged by the variable name on the left For example thestatement x = 3 + 5 means Scilab evaluates the statement onthe right and stores the result in the memory location tagged bythe variable x This means that the statement 3+ 5 = x whichis equivalent to x= 3 + 5 in mathematics will lead to an errormessage in Scilab

The following are examples of variable types in Scilab (it is notcomplete but contains all the variable types that you will encounter

230 Appendix B Programming with Scilab

in this course)

x = 3 Assign the scalar integer value 3 to the variable x

x = 7297e17 Assign the scalar real value 7297 times 1017 to the variable xThe number has been defined using the scientific exponentnotation The number following the e is the power of 10 tomultiply the number in front of the e Either e or E can beused

x = rsquoNorthrsquo Assign the string North to the variable x Strings of char-acters are defined by surrounding the characters with apos-trophes The construct rsquoSouthrsquo defines a constant stringcontaining the characters South

x = 05100 Assign the row vector containing 21 elements from 0 to 100in steps of 5 to the variable x

x = [12 13 25 67] Assign the 2times 2 matrix to the variable x so that

x =

[12 13

25 67

]

x = 51+i63 Assign the complex number 51+ i63 to the variable x

Variable names can be of any length but must be unique withinthe first 31 characters Variable names in Scilab are case sensi-tive that is the variables time and Time are distinct Howeverfunctions and scripts (which we discuss later) are stored in sepa-rate files (with extension sce) outside the interpreter and may ormay not be case sensitive depending on the outside environment(in a dos environment for example they will not be)

Scilab allows overloading of names This means that if you choosea name that has been predefined by Scilab you loose the builtin meaning For example cos = 634 defines a scalar variablecos but it is also the same name for the Scilab cosine functionThe variable assignment means that the cosine function will nolonger be accessible in this session All references to the name coswill assume the variable not the function Take care not to usevariable names that might disable built in functions or constantsthat you may need later When writing scripts for others to usethe names of all variables that will be over-written by the runningof the script must be listed for easy reference (and one shouldread these references before running any script) This is one ofthe reasons why it is nearly always preferable to write functionsrather than scripts Variables defined in the course of runninga functionrsquos algorithm remain local to the function and do notover-write workspace variables

The results of all calculations should be assigned to a variable sothat this value can be used later If this is not done the result

B3 Variables 231

Table B1 Special variables and constants in ScilabName Description

pi The value of π to the precession of the machineis returned

i Recognised as theradicminus1

inf This is Scilabrsquos representation of infin This is arecognised value in a variable and typically ap-pears as a result of division by zero or logarithmof zero

nan Stands for Not a Number This is a recognisedvalue in a variable and appears as a result ofa mathematically undefined operation such asdivision of zero by zero or infinminusinfin

eps Floating point relative accuracy That is epsreturns the smallest difference resolvable be-tween two floating point numbers For examplethe next largest representable number beyond10 is 10+eps Scilab cannot represent anyfloating point number that falls between 10 and10+eps

ans This variable contains the last computed expres-sion that was not stored in a variable

date This variable contains a string representation oftodayrsquos date in the format dd-mmm-yyyy Forexample 01-Apr-2000

232 Appendix B Programming with Scilab

Table B2 Scilab Arithmetic OperatorsOperator Meaning Scilab

^ Exponentiation xy x^y

Multiply xtimes y xy

Right Division xy = xy xy

Left Division yx = xy yx

+ Addition x+ y x+y

- Subtraction xminus y x-y

of a calculation will be stored in a special variable called ans (seeans

Table B1) The value stored in this variable is overridden the nexttime a calculation is done that is not assigned to a variable Thismeans that the result from the previous calculation is then lost

B4 Arithmetic expressions

Table B2 lists the basic arithmetic operators to be found in ScilabWith the exception of the left division operator the arithmetic op-erators in Scilab follow standard notation

B41 Precedence

When more than one operation appears in a mathematical state-ment the programming language needs to define in which order theoperations must be performed or the precedence That is whichparts are evaluated first

If precedence was not defined then the same statement can be eval-uated to a different result for example is 186+3 equal to 2 oris 186+3 equal to 6 The first statement is evaluated from theright using the precedence rule that usually applies in mathemat-ical statements that is work from right to left as for example inlsquosin log tan xrsquo where we start with a value of x compute the tan-gent of that value (tan x) then take the logarithm of the resultingnumber (log(tan x)) and finally take the sine of what this deliv-ers However it is usual (because it is much easier to write poly-nomials with this convention) to give multiplication and divisionprecedence over addition and subtraction The second statementrecognises the precedence of the division over addition and evalu-ates it first Right to left precedence has a much simpler parsingtree than schemes which give precedence to particular operatorsbut the common arithmetic precedences are so widely acceptedand expected that most computer language designers will not riskthe possible lsquoconsumer backlashrsquo that breaking with this traditionwould involve So with every computer language one must searchout and learn the precedence rules that it adopts The usual arith-metic precedences will normally be observed but note that even

B4 Arithmetic expressions 233

Table B3 Precedence of arithmetic expressionsOperator Precedence Order of evaluation

() 1 Left to right innermost first 2 Left to right 3 Left to right 4 Right to left

+ minus 5 Left to right

they are not unambiguous For example which divide has prece-dence in 41632 Working right to left one would get the answerof 8 but Scilab returns (the decimal for) 1128 mdashit works fromleft to right Table B3 lists the operators and their precedencevalue

The rules for evaluation of operators are as follows

bull Operators having high precedence (low numerical value) willbe evaluated before those having a low precedence (high nu-merical value)

bull If an expression contains more than one operator at the samelevel of precedence then the left-to-right rule of evaluationapply

Parentheses () always have the highest precedence Whateveris within the parentheses is evaluated first This means when indoubt about the order of any statement place parentheses aroundthe statement to ensure that the operations are performed in theorder you expect

B42 Matrix arithmetic

One of the strengths of Scilab is its ability to execute matrixarithmetic3 Matrix arithmetic must be implemented in other lan-guages with many lines of code or special functions Scilab isespecially designed to handle matrix arithmetic The representsmatrix multiplication or scalar multiplication of a matrix if one ofthe arguments is a scalar Since scalars are 1times1 matrices ordinaryscalar multiplication can also be performed by the operator Thedot product of two vectors however requires that the first vectorbe a row vector and the second a column vector To multiply thecorresponding elements in two vectors together requires a differentoperator so that

gt a = [2 3 4] b = [6 7 8]

a b

ans =

12 21 32

3 Remember vectors are examples of matrices A column vector of length nis an example of a ntimes 1 matrix

234 Appendix B Programming with Scilab

However because it is a matrix operation

gt a + b

ans =

8 10 40

The standard arithmetic operators described in Table B2 are alsoused with matrices The normal rules of matrix addition subtrac-tion and multiplication apply

The left and right division of matrices are also generalisations ofscalar division Right division BA is roughly the same as Binv(A)Left division AB is roughly the same as inv(A)B The differenceis in how the division is performed Different algorithms are usedwhen A or B are square or not

Scilab also defines a transpose operator for matrices The trans-pose of the matrix A is Arsquo For example if

A =

[25 63

12 09

] then A prime =

[25 12

63 09

]

Accessing matrix elements

Individual elements of a matrix can accessed and used in state-ments by specifying the matrix index of an element The index ofan element is its position in the matrix For example consider thefollowing matrix

A =

6 minus1 4

3 5 7

minus3 6 1

Define this in Scilab with the command

A=[ 6 -1 4 3 5 7 -3 6 7]

to display the contents of matrix A in Scilab just type the variablename A To display or use one element from the matrix specify theelement For example A(13) specifies the element in the first rowand third column that is 4 for the above matrix

To change a specific entry just assign a value to it For example

A(31)=-9

changes the value of the third row first column element from -3

to -9

To display or use a whole row or column use the operator Forexample

gt A(2)

ans =

3 5 7

gt A(2)

B4 Arithmetic expressions 235

ans =

-1

5

6

It is also possible to pick out a sub-matrix by the specifying the rowand column entries required For example To pick out the sub-matrix of A containing the elementsA11 A13 A21 A23 the commandA(12123) could be used as shown below

gt A(12123)

ans =

6 4

3 7

Note 123 means from 1 to 3 in steps of 2 This technique alongwith the assignment operator can be used for values of whole rowscolumns or sub-matrices in one command For example

gt A(12123)=[10111213]

A =

10 -1 11

12 5 13

-3 6 7

Note that the elements A11 A13 A21 A23 now contain the values10 11 12 and 13 respectively instead of their previous values

Index notation is logically an unfortunate phenomenon since itclashes with standard function notation On the face of it A(3)

should be the value of a function called A with input 3 but whenit is interpreted as index notation A is a variable However indexnotation is so familiar and useful to those familiar with classicalmathematical notation that many developers of mathematical soft-ware are not prepared to risk a ldquoconsumer backlashrdquo to providinga functional way of extracting elements from an array such as forexample 3 pick A to pick out the third element of A Similarlywe as teachers feel we would be doing students a disservice if wefailed to introduce them to the index notation that abounds inmathematical texts usually in the form of subscripting as in A3Logic does not always win an argument In the commercial worldof computing an established user base carries more weight thanmathematical logic just as in mathematics tradition may well alsofly in the face of logical consistency

B43 Array arithmetic

Scilab has two forms of arithmetic operations that can be usedwith matrices matrix arithmetic or array arithmetic Matrix arith-metic follows the normal rules of matrix algebra Array arithmeticwhich is also called element-by-element arithmetic is where oper-ations are performed on matrices element by element

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 3: Programming With Scilab

B2 Getting started with Scilab 227

professional looking product but it would take us the whole courseto master these and for the most part we will leave this activity toother courses Ours will be a study of efficient numerical techniquesand display of results will be plain and simple that is why thiscourse is called High Performance Numerical Computing

B2 Getting started with Scilab

Starting Scilab will give a command window similar to the oneshown in Figure B1 Commands are entered at the cursor (--gt)Each command is executed when either the return or enter key ispressed Any command execution can to be interrupted by pressinginterrupt a running command

Ctrl amp C keys together To exit Scilab simply type exit orquit at the command prompt2 Earlier commands executed inquitexit

a session can be recalled using the up (uarr)down (darr) keys on thekeyboard Once recalled the command can either be edited usingthe keyboard or re-executed by pressing the returnenter key Itis also possible to combine multiple commands on the one commandline by separating the commands using either a comma () or asemi-colon () The semi-colon () suppress any output from thesuppressing output from a

command command being executed

Figure B1 The default Scilab Command Window

Help about commands and functions can be obtained by typinghelp at the command plot This will bring up a window where youhelp

2 Note as with all commands in Scilab this will not be executed until eitherthe return or entry is pressed

228 Appendix B Programming with Scilab

can search for help on version topics Note you can short-cut thiswindow if you know the name of the command or function for whichyou require help by typing help command or function name atthe command prompt For example to get help on the log func-tion you would simply type help log at the command promptIn Scilab it is also possible to search for commands andor func-tions which contain certain keywords using the apropos commandapropos

As example the command apropos(rsquologarithmrsquo) will list all thecommands in Scilab relating to logarithms

Example B1 Sample commands in Scilab

--gt3^2-5-632

ans =

0

--gt3^2-5-6(32)

ans =

3

--gt42^2+1

ans =

17

--gtsin(pi2)

ans =

1

--gtsqrt(25)

ans =

5

--gtsqrt(-4)

ans =

2i

--gta1=5b1=3c1=sqrt(a1+b1)

a1 =

5

b1 =

3

c1 =

28284271

--gtans

ans =

2i

--gtt=linspace(0pi26)

t =

0 03141593 06283185 09424778 12566371 15707963

--gty=cos(t)

y =

1 09510565 08090170 05877853 03090170 6123D-17

Example B1 illustrates an important feature of the Scilab com-putational engine If an expression is just typed in and evaluatedthe answer is stored in a special variable called ans This vari-ans

B3 Variables 229

able contains the value of last unassigned (see sectB3 for details onhow variables are assigned) evaluation performed Hence the valuestored in ans changes each time an unassigned calculation is per-formed in Scilab as illustrated in Example B1 Consequentlyif you intend to reuse values of calculations you should store theresults in a variable (see sectB3) to avoid the possible of using theincorrect result

Activity BA To familiarise yourself with some of the basic features of rarrScilab and how to use it for elementary arithmetic andas a sophisticated calculator try some of the examples inExample B1 Make sure you understand what Scilabdid to calculate the answer Also as you work throughthe appendix attempt all the examples and exercises asyou come to them

B3 Variables

Variables are used in a programming language as tags to memorylocations in the computer The data stored in the memory locationis accessed using the variable name in the program The variableis not attached to the data but the memory location This meansthat the value contained within a variable can change

In languages such as C every variable must be declared before it isused specifying both its name and its type The name and type ofvariables do not need to be pre-declared in Scilab In Scilab anyvariable can take integer real complex scalar string or matrixvalues Languages that pre-declare variables have clearly statedat the start of a program or function the type of every variableused The Scilab interpreterrsquos liberal approach to variable typeshas both advantages and disadvantages

The equality sign (=) is used to assign the values to a variableassigning values to

variables This is an unfortunate choice of symbol and means that when wewant to test whether two quantities are equal or not we cannot usethe equal symbol = but must use the more cumbersome == Thus5+2 == 3+4 is true but 5+2 = 3+4 is a syntax error In Scilabprograms the equals sign does not have its mathematical meaningIt is an assignment operator The statement to the right of theequals sign is evaluated and the result is placed in the memorylocation tagged by the variable name on the left For example thestatement x = 3 + 5 means Scilab evaluates the statement onthe right and stores the result in the memory location tagged bythe variable x This means that the statement 3+ 5 = x whichis equivalent to x= 3 + 5 in mathematics will lead to an errormessage in Scilab

The following are examples of variable types in Scilab (it is notcomplete but contains all the variable types that you will encounter

230 Appendix B Programming with Scilab

in this course)

x = 3 Assign the scalar integer value 3 to the variable x

x = 7297e17 Assign the scalar real value 7297 times 1017 to the variable xThe number has been defined using the scientific exponentnotation The number following the e is the power of 10 tomultiply the number in front of the e Either e or E can beused

x = rsquoNorthrsquo Assign the string North to the variable x Strings of char-acters are defined by surrounding the characters with apos-trophes The construct rsquoSouthrsquo defines a constant stringcontaining the characters South

x = 05100 Assign the row vector containing 21 elements from 0 to 100in steps of 5 to the variable x

x = [12 13 25 67] Assign the 2times 2 matrix to the variable x so that

x =

[12 13

25 67

]

x = 51+i63 Assign the complex number 51+ i63 to the variable x

Variable names can be of any length but must be unique withinthe first 31 characters Variable names in Scilab are case sensi-tive that is the variables time and Time are distinct Howeverfunctions and scripts (which we discuss later) are stored in sepa-rate files (with extension sce) outside the interpreter and may ormay not be case sensitive depending on the outside environment(in a dos environment for example they will not be)

Scilab allows overloading of names This means that if you choosea name that has been predefined by Scilab you loose the builtin meaning For example cos = 634 defines a scalar variablecos but it is also the same name for the Scilab cosine functionThe variable assignment means that the cosine function will nolonger be accessible in this session All references to the name coswill assume the variable not the function Take care not to usevariable names that might disable built in functions or constantsthat you may need later When writing scripts for others to usethe names of all variables that will be over-written by the runningof the script must be listed for easy reference (and one shouldread these references before running any script) This is one ofthe reasons why it is nearly always preferable to write functionsrather than scripts Variables defined in the course of runninga functionrsquos algorithm remain local to the function and do notover-write workspace variables

The results of all calculations should be assigned to a variable sothat this value can be used later If this is not done the result

B3 Variables 231

Table B1 Special variables and constants in ScilabName Description

pi The value of π to the precession of the machineis returned

i Recognised as theradicminus1

inf This is Scilabrsquos representation of infin This is arecognised value in a variable and typically ap-pears as a result of division by zero or logarithmof zero

nan Stands for Not a Number This is a recognisedvalue in a variable and appears as a result ofa mathematically undefined operation such asdivision of zero by zero or infinminusinfin

eps Floating point relative accuracy That is epsreturns the smallest difference resolvable be-tween two floating point numbers For examplethe next largest representable number beyond10 is 10+eps Scilab cannot represent anyfloating point number that falls between 10 and10+eps

ans This variable contains the last computed expres-sion that was not stored in a variable

date This variable contains a string representation oftodayrsquos date in the format dd-mmm-yyyy Forexample 01-Apr-2000

232 Appendix B Programming with Scilab

Table B2 Scilab Arithmetic OperatorsOperator Meaning Scilab

^ Exponentiation xy x^y

Multiply xtimes y xy

Right Division xy = xy xy

Left Division yx = xy yx

+ Addition x+ y x+y

- Subtraction xminus y x-y

of a calculation will be stored in a special variable called ans (seeans

Table B1) The value stored in this variable is overridden the nexttime a calculation is done that is not assigned to a variable Thismeans that the result from the previous calculation is then lost

B4 Arithmetic expressions

Table B2 lists the basic arithmetic operators to be found in ScilabWith the exception of the left division operator the arithmetic op-erators in Scilab follow standard notation

B41 Precedence

When more than one operation appears in a mathematical state-ment the programming language needs to define in which order theoperations must be performed or the precedence That is whichparts are evaluated first

If precedence was not defined then the same statement can be eval-uated to a different result for example is 186+3 equal to 2 oris 186+3 equal to 6 The first statement is evaluated from theright using the precedence rule that usually applies in mathemat-ical statements that is work from right to left as for example inlsquosin log tan xrsquo where we start with a value of x compute the tan-gent of that value (tan x) then take the logarithm of the resultingnumber (log(tan x)) and finally take the sine of what this deliv-ers However it is usual (because it is much easier to write poly-nomials with this convention) to give multiplication and divisionprecedence over addition and subtraction The second statementrecognises the precedence of the division over addition and evalu-ates it first Right to left precedence has a much simpler parsingtree than schemes which give precedence to particular operatorsbut the common arithmetic precedences are so widely acceptedand expected that most computer language designers will not riskthe possible lsquoconsumer backlashrsquo that breaking with this traditionwould involve So with every computer language one must searchout and learn the precedence rules that it adopts The usual arith-metic precedences will normally be observed but note that even

B4 Arithmetic expressions 233

Table B3 Precedence of arithmetic expressionsOperator Precedence Order of evaluation

() 1 Left to right innermost first 2 Left to right 3 Left to right 4 Right to left

+ minus 5 Left to right

they are not unambiguous For example which divide has prece-dence in 41632 Working right to left one would get the answerof 8 but Scilab returns (the decimal for) 1128 mdashit works fromleft to right Table B3 lists the operators and their precedencevalue

The rules for evaluation of operators are as follows

bull Operators having high precedence (low numerical value) willbe evaluated before those having a low precedence (high nu-merical value)

bull If an expression contains more than one operator at the samelevel of precedence then the left-to-right rule of evaluationapply

Parentheses () always have the highest precedence Whateveris within the parentheses is evaluated first This means when indoubt about the order of any statement place parentheses aroundthe statement to ensure that the operations are performed in theorder you expect

B42 Matrix arithmetic

One of the strengths of Scilab is its ability to execute matrixarithmetic3 Matrix arithmetic must be implemented in other lan-guages with many lines of code or special functions Scilab isespecially designed to handle matrix arithmetic The representsmatrix multiplication or scalar multiplication of a matrix if one ofthe arguments is a scalar Since scalars are 1times1 matrices ordinaryscalar multiplication can also be performed by the operator Thedot product of two vectors however requires that the first vectorbe a row vector and the second a column vector To multiply thecorresponding elements in two vectors together requires a differentoperator so that

gt a = [2 3 4] b = [6 7 8]

a b

ans =

12 21 32

3 Remember vectors are examples of matrices A column vector of length nis an example of a ntimes 1 matrix

234 Appendix B Programming with Scilab

However because it is a matrix operation

gt a + b

ans =

8 10 40

The standard arithmetic operators described in Table B2 are alsoused with matrices The normal rules of matrix addition subtrac-tion and multiplication apply

The left and right division of matrices are also generalisations ofscalar division Right division BA is roughly the same as Binv(A)Left division AB is roughly the same as inv(A)B The differenceis in how the division is performed Different algorithms are usedwhen A or B are square or not

Scilab also defines a transpose operator for matrices The trans-pose of the matrix A is Arsquo For example if

A =

[25 63

12 09

] then A prime =

[25 12

63 09

]

Accessing matrix elements

Individual elements of a matrix can accessed and used in state-ments by specifying the matrix index of an element The index ofan element is its position in the matrix For example consider thefollowing matrix

A =

6 minus1 4

3 5 7

minus3 6 1

Define this in Scilab with the command

A=[ 6 -1 4 3 5 7 -3 6 7]

to display the contents of matrix A in Scilab just type the variablename A To display or use one element from the matrix specify theelement For example A(13) specifies the element in the first rowand third column that is 4 for the above matrix

To change a specific entry just assign a value to it For example

A(31)=-9

changes the value of the third row first column element from -3

to -9

To display or use a whole row or column use the operator Forexample

gt A(2)

ans =

3 5 7

gt A(2)

B4 Arithmetic expressions 235

ans =

-1

5

6

It is also possible to pick out a sub-matrix by the specifying the rowand column entries required For example To pick out the sub-matrix of A containing the elementsA11 A13 A21 A23 the commandA(12123) could be used as shown below

gt A(12123)

ans =

6 4

3 7

Note 123 means from 1 to 3 in steps of 2 This technique alongwith the assignment operator can be used for values of whole rowscolumns or sub-matrices in one command For example

gt A(12123)=[10111213]

A =

10 -1 11

12 5 13

-3 6 7

Note that the elements A11 A13 A21 A23 now contain the values10 11 12 and 13 respectively instead of their previous values

Index notation is logically an unfortunate phenomenon since itclashes with standard function notation On the face of it A(3)

should be the value of a function called A with input 3 but whenit is interpreted as index notation A is a variable However indexnotation is so familiar and useful to those familiar with classicalmathematical notation that many developers of mathematical soft-ware are not prepared to risk a ldquoconsumer backlashrdquo to providinga functional way of extracting elements from an array such as forexample 3 pick A to pick out the third element of A Similarlywe as teachers feel we would be doing students a disservice if wefailed to introduce them to the index notation that abounds inmathematical texts usually in the form of subscripting as in A3Logic does not always win an argument In the commercial worldof computing an established user base carries more weight thanmathematical logic just as in mathematics tradition may well alsofly in the face of logical consistency

B43 Array arithmetic

Scilab has two forms of arithmetic operations that can be usedwith matrices matrix arithmetic or array arithmetic Matrix arith-metic follows the normal rules of matrix algebra Array arithmeticwhich is also called element-by-element arithmetic is where oper-ations are performed on matrices element by element

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 4: Programming With Scilab

228 Appendix B Programming with Scilab

can search for help on version topics Note you can short-cut thiswindow if you know the name of the command or function for whichyou require help by typing help command or function name atthe command prompt For example to get help on the log func-tion you would simply type help log at the command promptIn Scilab it is also possible to search for commands andor func-tions which contain certain keywords using the apropos commandapropos

As example the command apropos(rsquologarithmrsquo) will list all thecommands in Scilab relating to logarithms

Example B1 Sample commands in Scilab

--gt3^2-5-632

ans =

0

--gt3^2-5-6(32)

ans =

3

--gt42^2+1

ans =

17

--gtsin(pi2)

ans =

1

--gtsqrt(25)

ans =

5

--gtsqrt(-4)

ans =

2i

--gta1=5b1=3c1=sqrt(a1+b1)

a1 =

5

b1 =

3

c1 =

28284271

--gtans

ans =

2i

--gtt=linspace(0pi26)

t =

0 03141593 06283185 09424778 12566371 15707963

--gty=cos(t)

y =

1 09510565 08090170 05877853 03090170 6123D-17

Example B1 illustrates an important feature of the Scilab com-putational engine If an expression is just typed in and evaluatedthe answer is stored in a special variable called ans This vari-ans

B3 Variables 229

able contains the value of last unassigned (see sectB3 for details onhow variables are assigned) evaluation performed Hence the valuestored in ans changes each time an unassigned calculation is per-formed in Scilab as illustrated in Example B1 Consequentlyif you intend to reuse values of calculations you should store theresults in a variable (see sectB3) to avoid the possible of using theincorrect result

Activity BA To familiarise yourself with some of the basic features of rarrScilab and how to use it for elementary arithmetic andas a sophisticated calculator try some of the examples inExample B1 Make sure you understand what Scilabdid to calculate the answer Also as you work throughthe appendix attempt all the examples and exercises asyou come to them

B3 Variables

Variables are used in a programming language as tags to memorylocations in the computer The data stored in the memory locationis accessed using the variable name in the program The variableis not attached to the data but the memory location This meansthat the value contained within a variable can change

In languages such as C every variable must be declared before it isused specifying both its name and its type The name and type ofvariables do not need to be pre-declared in Scilab In Scilab anyvariable can take integer real complex scalar string or matrixvalues Languages that pre-declare variables have clearly statedat the start of a program or function the type of every variableused The Scilab interpreterrsquos liberal approach to variable typeshas both advantages and disadvantages

The equality sign (=) is used to assign the values to a variableassigning values to

variables This is an unfortunate choice of symbol and means that when wewant to test whether two quantities are equal or not we cannot usethe equal symbol = but must use the more cumbersome == Thus5+2 == 3+4 is true but 5+2 = 3+4 is a syntax error In Scilabprograms the equals sign does not have its mathematical meaningIt is an assignment operator The statement to the right of theequals sign is evaluated and the result is placed in the memorylocation tagged by the variable name on the left For example thestatement x = 3 + 5 means Scilab evaluates the statement onthe right and stores the result in the memory location tagged bythe variable x This means that the statement 3+ 5 = x whichis equivalent to x= 3 + 5 in mathematics will lead to an errormessage in Scilab

The following are examples of variable types in Scilab (it is notcomplete but contains all the variable types that you will encounter

230 Appendix B Programming with Scilab

in this course)

x = 3 Assign the scalar integer value 3 to the variable x

x = 7297e17 Assign the scalar real value 7297 times 1017 to the variable xThe number has been defined using the scientific exponentnotation The number following the e is the power of 10 tomultiply the number in front of the e Either e or E can beused

x = rsquoNorthrsquo Assign the string North to the variable x Strings of char-acters are defined by surrounding the characters with apos-trophes The construct rsquoSouthrsquo defines a constant stringcontaining the characters South

x = 05100 Assign the row vector containing 21 elements from 0 to 100in steps of 5 to the variable x

x = [12 13 25 67] Assign the 2times 2 matrix to the variable x so that

x =

[12 13

25 67

]

x = 51+i63 Assign the complex number 51+ i63 to the variable x

Variable names can be of any length but must be unique withinthe first 31 characters Variable names in Scilab are case sensi-tive that is the variables time and Time are distinct Howeverfunctions and scripts (which we discuss later) are stored in sepa-rate files (with extension sce) outside the interpreter and may ormay not be case sensitive depending on the outside environment(in a dos environment for example they will not be)

Scilab allows overloading of names This means that if you choosea name that has been predefined by Scilab you loose the builtin meaning For example cos = 634 defines a scalar variablecos but it is also the same name for the Scilab cosine functionThe variable assignment means that the cosine function will nolonger be accessible in this session All references to the name coswill assume the variable not the function Take care not to usevariable names that might disable built in functions or constantsthat you may need later When writing scripts for others to usethe names of all variables that will be over-written by the runningof the script must be listed for easy reference (and one shouldread these references before running any script) This is one ofthe reasons why it is nearly always preferable to write functionsrather than scripts Variables defined in the course of runninga functionrsquos algorithm remain local to the function and do notover-write workspace variables

The results of all calculations should be assigned to a variable sothat this value can be used later If this is not done the result

B3 Variables 231

Table B1 Special variables and constants in ScilabName Description

pi The value of π to the precession of the machineis returned

i Recognised as theradicminus1

inf This is Scilabrsquos representation of infin This is arecognised value in a variable and typically ap-pears as a result of division by zero or logarithmof zero

nan Stands for Not a Number This is a recognisedvalue in a variable and appears as a result ofa mathematically undefined operation such asdivision of zero by zero or infinminusinfin

eps Floating point relative accuracy That is epsreturns the smallest difference resolvable be-tween two floating point numbers For examplethe next largest representable number beyond10 is 10+eps Scilab cannot represent anyfloating point number that falls between 10 and10+eps

ans This variable contains the last computed expres-sion that was not stored in a variable

date This variable contains a string representation oftodayrsquos date in the format dd-mmm-yyyy Forexample 01-Apr-2000

232 Appendix B Programming with Scilab

Table B2 Scilab Arithmetic OperatorsOperator Meaning Scilab

^ Exponentiation xy x^y

Multiply xtimes y xy

Right Division xy = xy xy

Left Division yx = xy yx

+ Addition x+ y x+y

- Subtraction xminus y x-y

of a calculation will be stored in a special variable called ans (seeans

Table B1) The value stored in this variable is overridden the nexttime a calculation is done that is not assigned to a variable Thismeans that the result from the previous calculation is then lost

B4 Arithmetic expressions

Table B2 lists the basic arithmetic operators to be found in ScilabWith the exception of the left division operator the arithmetic op-erators in Scilab follow standard notation

B41 Precedence

When more than one operation appears in a mathematical state-ment the programming language needs to define in which order theoperations must be performed or the precedence That is whichparts are evaluated first

If precedence was not defined then the same statement can be eval-uated to a different result for example is 186+3 equal to 2 oris 186+3 equal to 6 The first statement is evaluated from theright using the precedence rule that usually applies in mathemat-ical statements that is work from right to left as for example inlsquosin log tan xrsquo where we start with a value of x compute the tan-gent of that value (tan x) then take the logarithm of the resultingnumber (log(tan x)) and finally take the sine of what this deliv-ers However it is usual (because it is much easier to write poly-nomials with this convention) to give multiplication and divisionprecedence over addition and subtraction The second statementrecognises the precedence of the division over addition and evalu-ates it first Right to left precedence has a much simpler parsingtree than schemes which give precedence to particular operatorsbut the common arithmetic precedences are so widely acceptedand expected that most computer language designers will not riskthe possible lsquoconsumer backlashrsquo that breaking with this traditionwould involve So with every computer language one must searchout and learn the precedence rules that it adopts The usual arith-metic precedences will normally be observed but note that even

B4 Arithmetic expressions 233

Table B3 Precedence of arithmetic expressionsOperator Precedence Order of evaluation

() 1 Left to right innermost first 2 Left to right 3 Left to right 4 Right to left

+ minus 5 Left to right

they are not unambiguous For example which divide has prece-dence in 41632 Working right to left one would get the answerof 8 but Scilab returns (the decimal for) 1128 mdashit works fromleft to right Table B3 lists the operators and their precedencevalue

The rules for evaluation of operators are as follows

bull Operators having high precedence (low numerical value) willbe evaluated before those having a low precedence (high nu-merical value)

bull If an expression contains more than one operator at the samelevel of precedence then the left-to-right rule of evaluationapply

Parentheses () always have the highest precedence Whateveris within the parentheses is evaluated first This means when indoubt about the order of any statement place parentheses aroundthe statement to ensure that the operations are performed in theorder you expect

B42 Matrix arithmetic

One of the strengths of Scilab is its ability to execute matrixarithmetic3 Matrix arithmetic must be implemented in other lan-guages with many lines of code or special functions Scilab isespecially designed to handle matrix arithmetic The representsmatrix multiplication or scalar multiplication of a matrix if one ofthe arguments is a scalar Since scalars are 1times1 matrices ordinaryscalar multiplication can also be performed by the operator Thedot product of two vectors however requires that the first vectorbe a row vector and the second a column vector To multiply thecorresponding elements in two vectors together requires a differentoperator so that

gt a = [2 3 4] b = [6 7 8]

a b

ans =

12 21 32

3 Remember vectors are examples of matrices A column vector of length nis an example of a ntimes 1 matrix

234 Appendix B Programming with Scilab

However because it is a matrix operation

gt a + b

ans =

8 10 40

The standard arithmetic operators described in Table B2 are alsoused with matrices The normal rules of matrix addition subtrac-tion and multiplication apply

The left and right division of matrices are also generalisations ofscalar division Right division BA is roughly the same as Binv(A)Left division AB is roughly the same as inv(A)B The differenceis in how the division is performed Different algorithms are usedwhen A or B are square or not

Scilab also defines a transpose operator for matrices The trans-pose of the matrix A is Arsquo For example if

A =

[25 63

12 09

] then A prime =

[25 12

63 09

]

Accessing matrix elements

Individual elements of a matrix can accessed and used in state-ments by specifying the matrix index of an element The index ofan element is its position in the matrix For example consider thefollowing matrix

A =

6 minus1 4

3 5 7

minus3 6 1

Define this in Scilab with the command

A=[ 6 -1 4 3 5 7 -3 6 7]

to display the contents of matrix A in Scilab just type the variablename A To display or use one element from the matrix specify theelement For example A(13) specifies the element in the first rowand third column that is 4 for the above matrix

To change a specific entry just assign a value to it For example

A(31)=-9

changes the value of the third row first column element from -3

to -9

To display or use a whole row or column use the operator Forexample

gt A(2)

ans =

3 5 7

gt A(2)

B4 Arithmetic expressions 235

ans =

-1

5

6

It is also possible to pick out a sub-matrix by the specifying the rowand column entries required For example To pick out the sub-matrix of A containing the elementsA11 A13 A21 A23 the commandA(12123) could be used as shown below

gt A(12123)

ans =

6 4

3 7

Note 123 means from 1 to 3 in steps of 2 This technique alongwith the assignment operator can be used for values of whole rowscolumns or sub-matrices in one command For example

gt A(12123)=[10111213]

A =

10 -1 11

12 5 13

-3 6 7

Note that the elements A11 A13 A21 A23 now contain the values10 11 12 and 13 respectively instead of their previous values

Index notation is logically an unfortunate phenomenon since itclashes with standard function notation On the face of it A(3)

should be the value of a function called A with input 3 but whenit is interpreted as index notation A is a variable However indexnotation is so familiar and useful to those familiar with classicalmathematical notation that many developers of mathematical soft-ware are not prepared to risk a ldquoconsumer backlashrdquo to providinga functional way of extracting elements from an array such as forexample 3 pick A to pick out the third element of A Similarlywe as teachers feel we would be doing students a disservice if wefailed to introduce them to the index notation that abounds inmathematical texts usually in the form of subscripting as in A3Logic does not always win an argument In the commercial worldof computing an established user base carries more weight thanmathematical logic just as in mathematics tradition may well alsofly in the face of logical consistency

B43 Array arithmetic

Scilab has two forms of arithmetic operations that can be usedwith matrices matrix arithmetic or array arithmetic Matrix arith-metic follows the normal rules of matrix algebra Array arithmeticwhich is also called element-by-element arithmetic is where oper-ations are performed on matrices element by element

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 5: Programming With Scilab

B3 Variables 229

able contains the value of last unassigned (see sectB3 for details onhow variables are assigned) evaluation performed Hence the valuestored in ans changes each time an unassigned calculation is per-formed in Scilab as illustrated in Example B1 Consequentlyif you intend to reuse values of calculations you should store theresults in a variable (see sectB3) to avoid the possible of using theincorrect result

Activity BA To familiarise yourself with some of the basic features of rarrScilab and how to use it for elementary arithmetic andas a sophisticated calculator try some of the examples inExample B1 Make sure you understand what Scilabdid to calculate the answer Also as you work throughthe appendix attempt all the examples and exercises asyou come to them

B3 Variables

Variables are used in a programming language as tags to memorylocations in the computer The data stored in the memory locationis accessed using the variable name in the program The variableis not attached to the data but the memory location This meansthat the value contained within a variable can change

In languages such as C every variable must be declared before it isused specifying both its name and its type The name and type ofvariables do not need to be pre-declared in Scilab In Scilab anyvariable can take integer real complex scalar string or matrixvalues Languages that pre-declare variables have clearly statedat the start of a program or function the type of every variableused The Scilab interpreterrsquos liberal approach to variable typeshas both advantages and disadvantages

The equality sign (=) is used to assign the values to a variableassigning values to

variables This is an unfortunate choice of symbol and means that when wewant to test whether two quantities are equal or not we cannot usethe equal symbol = but must use the more cumbersome == Thus5+2 == 3+4 is true but 5+2 = 3+4 is a syntax error In Scilabprograms the equals sign does not have its mathematical meaningIt is an assignment operator The statement to the right of theequals sign is evaluated and the result is placed in the memorylocation tagged by the variable name on the left For example thestatement x = 3 + 5 means Scilab evaluates the statement onthe right and stores the result in the memory location tagged bythe variable x This means that the statement 3+ 5 = x whichis equivalent to x= 3 + 5 in mathematics will lead to an errormessage in Scilab

The following are examples of variable types in Scilab (it is notcomplete but contains all the variable types that you will encounter

230 Appendix B Programming with Scilab

in this course)

x = 3 Assign the scalar integer value 3 to the variable x

x = 7297e17 Assign the scalar real value 7297 times 1017 to the variable xThe number has been defined using the scientific exponentnotation The number following the e is the power of 10 tomultiply the number in front of the e Either e or E can beused

x = rsquoNorthrsquo Assign the string North to the variable x Strings of char-acters are defined by surrounding the characters with apos-trophes The construct rsquoSouthrsquo defines a constant stringcontaining the characters South

x = 05100 Assign the row vector containing 21 elements from 0 to 100in steps of 5 to the variable x

x = [12 13 25 67] Assign the 2times 2 matrix to the variable x so that

x =

[12 13

25 67

]

x = 51+i63 Assign the complex number 51+ i63 to the variable x

Variable names can be of any length but must be unique withinthe first 31 characters Variable names in Scilab are case sensi-tive that is the variables time and Time are distinct Howeverfunctions and scripts (which we discuss later) are stored in sepa-rate files (with extension sce) outside the interpreter and may ormay not be case sensitive depending on the outside environment(in a dos environment for example they will not be)

Scilab allows overloading of names This means that if you choosea name that has been predefined by Scilab you loose the builtin meaning For example cos = 634 defines a scalar variablecos but it is also the same name for the Scilab cosine functionThe variable assignment means that the cosine function will nolonger be accessible in this session All references to the name coswill assume the variable not the function Take care not to usevariable names that might disable built in functions or constantsthat you may need later When writing scripts for others to usethe names of all variables that will be over-written by the runningof the script must be listed for easy reference (and one shouldread these references before running any script) This is one ofthe reasons why it is nearly always preferable to write functionsrather than scripts Variables defined in the course of runninga functionrsquos algorithm remain local to the function and do notover-write workspace variables

The results of all calculations should be assigned to a variable sothat this value can be used later If this is not done the result

B3 Variables 231

Table B1 Special variables and constants in ScilabName Description

pi The value of π to the precession of the machineis returned

i Recognised as theradicminus1

inf This is Scilabrsquos representation of infin This is arecognised value in a variable and typically ap-pears as a result of division by zero or logarithmof zero

nan Stands for Not a Number This is a recognisedvalue in a variable and appears as a result ofa mathematically undefined operation such asdivision of zero by zero or infinminusinfin

eps Floating point relative accuracy That is epsreturns the smallest difference resolvable be-tween two floating point numbers For examplethe next largest representable number beyond10 is 10+eps Scilab cannot represent anyfloating point number that falls between 10 and10+eps

ans This variable contains the last computed expres-sion that was not stored in a variable

date This variable contains a string representation oftodayrsquos date in the format dd-mmm-yyyy Forexample 01-Apr-2000

232 Appendix B Programming with Scilab

Table B2 Scilab Arithmetic OperatorsOperator Meaning Scilab

^ Exponentiation xy x^y

Multiply xtimes y xy

Right Division xy = xy xy

Left Division yx = xy yx

+ Addition x+ y x+y

- Subtraction xminus y x-y

of a calculation will be stored in a special variable called ans (seeans

Table B1) The value stored in this variable is overridden the nexttime a calculation is done that is not assigned to a variable Thismeans that the result from the previous calculation is then lost

B4 Arithmetic expressions

Table B2 lists the basic arithmetic operators to be found in ScilabWith the exception of the left division operator the arithmetic op-erators in Scilab follow standard notation

B41 Precedence

When more than one operation appears in a mathematical state-ment the programming language needs to define in which order theoperations must be performed or the precedence That is whichparts are evaluated first

If precedence was not defined then the same statement can be eval-uated to a different result for example is 186+3 equal to 2 oris 186+3 equal to 6 The first statement is evaluated from theright using the precedence rule that usually applies in mathemat-ical statements that is work from right to left as for example inlsquosin log tan xrsquo where we start with a value of x compute the tan-gent of that value (tan x) then take the logarithm of the resultingnumber (log(tan x)) and finally take the sine of what this deliv-ers However it is usual (because it is much easier to write poly-nomials with this convention) to give multiplication and divisionprecedence over addition and subtraction The second statementrecognises the precedence of the division over addition and evalu-ates it first Right to left precedence has a much simpler parsingtree than schemes which give precedence to particular operatorsbut the common arithmetic precedences are so widely acceptedand expected that most computer language designers will not riskthe possible lsquoconsumer backlashrsquo that breaking with this traditionwould involve So with every computer language one must searchout and learn the precedence rules that it adopts The usual arith-metic precedences will normally be observed but note that even

B4 Arithmetic expressions 233

Table B3 Precedence of arithmetic expressionsOperator Precedence Order of evaluation

() 1 Left to right innermost first 2 Left to right 3 Left to right 4 Right to left

+ minus 5 Left to right

they are not unambiguous For example which divide has prece-dence in 41632 Working right to left one would get the answerof 8 but Scilab returns (the decimal for) 1128 mdashit works fromleft to right Table B3 lists the operators and their precedencevalue

The rules for evaluation of operators are as follows

bull Operators having high precedence (low numerical value) willbe evaluated before those having a low precedence (high nu-merical value)

bull If an expression contains more than one operator at the samelevel of precedence then the left-to-right rule of evaluationapply

Parentheses () always have the highest precedence Whateveris within the parentheses is evaluated first This means when indoubt about the order of any statement place parentheses aroundthe statement to ensure that the operations are performed in theorder you expect

B42 Matrix arithmetic

One of the strengths of Scilab is its ability to execute matrixarithmetic3 Matrix arithmetic must be implemented in other lan-guages with many lines of code or special functions Scilab isespecially designed to handle matrix arithmetic The representsmatrix multiplication or scalar multiplication of a matrix if one ofthe arguments is a scalar Since scalars are 1times1 matrices ordinaryscalar multiplication can also be performed by the operator Thedot product of two vectors however requires that the first vectorbe a row vector and the second a column vector To multiply thecorresponding elements in two vectors together requires a differentoperator so that

gt a = [2 3 4] b = [6 7 8]

a b

ans =

12 21 32

3 Remember vectors are examples of matrices A column vector of length nis an example of a ntimes 1 matrix

234 Appendix B Programming with Scilab

However because it is a matrix operation

gt a + b

ans =

8 10 40

The standard arithmetic operators described in Table B2 are alsoused with matrices The normal rules of matrix addition subtrac-tion and multiplication apply

The left and right division of matrices are also generalisations ofscalar division Right division BA is roughly the same as Binv(A)Left division AB is roughly the same as inv(A)B The differenceis in how the division is performed Different algorithms are usedwhen A or B are square or not

Scilab also defines a transpose operator for matrices The trans-pose of the matrix A is Arsquo For example if

A =

[25 63

12 09

] then A prime =

[25 12

63 09

]

Accessing matrix elements

Individual elements of a matrix can accessed and used in state-ments by specifying the matrix index of an element The index ofan element is its position in the matrix For example consider thefollowing matrix

A =

6 minus1 4

3 5 7

minus3 6 1

Define this in Scilab with the command

A=[ 6 -1 4 3 5 7 -3 6 7]

to display the contents of matrix A in Scilab just type the variablename A To display or use one element from the matrix specify theelement For example A(13) specifies the element in the first rowand third column that is 4 for the above matrix

To change a specific entry just assign a value to it For example

A(31)=-9

changes the value of the third row first column element from -3

to -9

To display or use a whole row or column use the operator Forexample

gt A(2)

ans =

3 5 7

gt A(2)

B4 Arithmetic expressions 235

ans =

-1

5

6

It is also possible to pick out a sub-matrix by the specifying the rowand column entries required For example To pick out the sub-matrix of A containing the elementsA11 A13 A21 A23 the commandA(12123) could be used as shown below

gt A(12123)

ans =

6 4

3 7

Note 123 means from 1 to 3 in steps of 2 This technique alongwith the assignment operator can be used for values of whole rowscolumns or sub-matrices in one command For example

gt A(12123)=[10111213]

A =

10 -1 11

12 5 13

-3 6 7

Note that the elements A11 A13 A21 A23 now contain the values10 11 12 and 13 respectively instead of their previous values

Index notation is logically an unfortunate phenomenon since itclashes with standard function notation On the face of it A(3)

should be the value of a function called A with input 3 but whenit is interpreted as index notation A is a variable However indexnotation is so familiar and useful to those familiar with classicalmathematical notation that many developers of mathematical soft-ware are not prepared to risk a ldquoconsumer backlashrdquo to providinga functional way of extracting elements from an array such as forexample 3 pick A to pick out the third element of A Similarlywe as teachers feel we would be doing students a disservice if wefailed to introduce them to the index notation that abounds inmathematical texts usually in the form of subscripting as in A3Logic does not always win an argument In the commercial worldof computing an established user base carries more weight thanmathematical logic just as in mathematics tradition may well alsofly in the face of logical consistency

B43 Array arithmetic

Scilab has two forms of arithmetic operations that can be usedwith matrices matrix arithmetic or array arithmetic Matrix arith-metic follows the normal rules of matrix algebra Array arithmeticwhich is also called element-by-element arithmetic is where oper-ations are performed on matrices element by element

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 6: Programming With Scilab

230 Appendix B Programming with Scilab

in this course)

x = 3 Assign the scalar integer value 3 to the variable x

x = 7297e17 Assign the scalar real value 7297 times 1017 to the variable xThe number has been defined using the scientific exponentnotation The number following the e is the power of 10 tomultiply the number in front of the e Either e or E can beused

x = rsquoNorthrsquo Assign the string North to the variable x Strings of char-acters are defined by surrounding the characters with apos-trophes The construct rsquoSouthrsquo defines a constant stringcontaining the characters South

x = 05100 Assign the row vector containing 21 elements from 0 to 100in steps of 5 to the variable x

x = [12 13 25 67] Assign the 2times 2 matrix to the variable x so that

x =

[12 13

25 67

]

x = 51+i63 Assign the complex number 51+ i63 to the variable x

Variable names can be of any length but must be unique withinthe first 31 characters Variable names in Scilab are case sensi-tive that is the variables time and Time are distinct Howeverfunctions and scripts (which we discuss later) are stored in sepa-rate files (with extension sce) outside the interpreter and may ormay not be case sensitive depending on the outside environment(in a dos environment for example they will not be)

Scilab allows overloading of names This means that if you choosea name that has been predefined by Scilab you loose the builtin meaning For example cos = 634 defines a scalar variablecos but it is also the same name for the Scilab cosine functionThe variable assignment means that the cosine function will nolonger be accessible in this session All references to the name coswill assume the variable not the function Take care not to usevariable names that might disable built in functions or constantsthat you may need later When writing scripts for others to usethe names of all variables that will be over-written by the runningof the script must be listed for easy reference (and one shouldread these references before running any script) This is one ofthe reasons why it is nearly always preferable to write functionsrather than scripts Variables defined in the course of runninga functionrsquos algorithm remain local to the function and do notover-write workspace variables

The results of all calculations should be assigned to a variable sothat this value can be used later If this is not done the result

B3 Variables 231

Table B1 Special variables and constants in ScilabName Description

pi The value of π to the precession of the machineis returned

i Recognised as theradicminus1

inf This is Scilabrsquos representation of infin This is arecognised value in a variable and typically ap-pears as a result of division by zero or logarithmof zero

nan Stands for Not a Number This is a recognisedvalue in a variable and appears as a result ofa mathematically undefined operation such asdivision of zero by zero or infinminusinfin

eps Floating point relative accuracy That is epsreturns the smallest difference resolvable be-tween two floating point numbers For examplethe next largest representable number beyond10 is 10+eps Scilab cannot represent anyfloating point number that falls between 10 and10+eps

ans This variable contains the last computed expres-sion that was not stored in a variable

date This variable contains a string representation oftodayrsquos date in the format dd-mmm-yyyy Forexample 01-Apr-2000

232 Appendix B Programming with Scilab

Table B2 Scilab Arithmetic OperatorsOperator Meaning Scilab

^ Exponentiation xy x^y

Multiply xtimes y xy

Right Division xy = xy xy

Left Division yx = xy yx

+ Addition x+ y x+y

- Subtraction xminus y x-y

of a calculation will be stored in a special variable called ans (seeans

Table B1) The value stored in this variable is overridden the nexttime a calculation is done that is not assigned to a variable Thismeans that the result from the previous calculation is then lost

B4 Arithmetic expressions

Table B2 lists the basic arithmetic operators to be found in ScilabWith the exception of the left division operator the arithmetic op-erators in Scilab follow standard notation

B41 Precedence

When more than one operation appears in a mathematical state-ment the programming language needs to define in which order theoperations must be performed or the precedence That is whichparts are evaluated first

If precedence was not defined then the same statement can be eval-uated to a different result for example is 186+3 equal to 2 oris 186+3 equal to 6 The first statement is evaluated from theright using the precedence rule that usually applies in mathemat-ical statements that is work from right to left as for example inlsquosin log tan xrsquo where we start with a value of x compute the tan-gent of that value (tan x) then take the logarithm of the resultingnumber (log(tan x)) and finally take the sine of what this deliv-ers However it is usual (because it is much easier to write poly-nomials with this convention) to give multiplication and divisionprecedence over addition and subtraction The second statementrecognises the precedence of the division over addition and evalu-ates it first Right to left precedence has a much simpler parsingtree than schemes which give precedence to particular operatorsbut the common arithmetic precedences are so widely acceptedand expected that most computer language designers will not riskthe possible lsquoconsumer backlashrsquo that breaking with this traditionwould involve So with every computer language one must searchout and learn the precedence rules that it adopts The usual arith-metic precedences will normally be observed but note that even

B4 Arithmetic expressions 233

Table B3 Precedence of arithmetic expressionsOperator Precedence Order of evaluation

() 1 Left to right innermost first 2 Left to right 3 Left to right 4 Right to left

+ minus 5 Left to right

they are not unambiguous For example which divide has prece-dence in 41632 Working right to left one would get the answerof 8 but Scilab returns (the decimal for) 1128 mdashit works fromleft to right Table B3 lists the operators and their precedencevalue

The rules for evaluation of operators are as follows

bull Operators having high precedence (low numerical value) willbe evaluated before those having a low precedence (high nu-merical value)

bull If an expression contains more than one operator at the samelevel of precedence then the left-to-right rule of evaluationapply

Parentheses () always have the highest precedence Whateveris within the parentheses is evaluated first This means when indoubt about the order of any statement place parentheses aroundthe statement to ensure that the operations are performed in theorder you expect

B42 Matrix arithmetic

One of the strengths of Scilab is its ability to execute matrixarithmetic3 Matrix arithmetic must be implemented in other lan-guages with many lines of code or special functions Scilab isespecially designed to handle matrix arithmetic The representsmatrix multiplication or scalar multiplication of a matrix if one ofthe arguments is a scalar Since scalars are 1times1 matrices ordinaryscalar multiplication can also be performed by the operator Thedot product of two vectors however requires that the first vectorbe a row vector and the second a column vector To multiply thecorresponding elements in two vectors together requires a differentoperator so that

gt a = [2 3 4] b = [6 7 8]

a b

ans =

12 21 32

3 Remember vectors are examples of matrices A column vector of length nis an example of a ntimes 1 matrix

234 Appendix B Programming with Scilab

However because it is a matrix operation

gt a + b

ans =

8 10 40

The standard arithmetic operators described in Table B2 are alsoused with matrices The normal rules of matrix addition subtrac-tion and multiplication apply

The left and right division of matrices are also generalisations ofscalar division Right division BA is roughly the same as Binv(A)Left division AB is roughly the same as inv(A)B The differenceis in how the division is performed Different algorithms are usedwhen A or B are square or not

Scilab also defines a transpose operator for matrices The trans-pose of the matrix A is Arsquo For example if

A =

[25 63

12 09

] then A prime =

[25 12

63 09

]

Accessing matrix elements

Individual elements of a matrix can accessed and used in state-ments by specifying the matrix index of an element The index ofan element is its position in the matrix For example consider thefollowing matrix

A =

6 minus1 4

3 5 7

minus3 6 1

Define this in Scilab with the command

A=[ 6 -1 4 3 5 7 -3 6 7]

to display the contents of matrix A in Scilab just type the variablename A To display or use one element from the matrix specify theelement For example A(13) specifies the element in the first rowand third column that is 4 for the above matrix

To change a specific entry just assign a value to it For example

A(31)=-9

changes the value of the third row first column element from -3

to -9

To display or use a whole row or column use the operator Forexample

gt A(2)

ans =

3 5 7

gt A(2)

B4 Arithmetic expressions 235

ans =

-1

5

6

It is also possible to pick out a sub-matrix by the specifying the rowand column entries required For example To pick out the sub-matrix of A containing the elementsA11 A13 A21 A23 the commandA(12123) could be used as shown below

gt A(12123)

ans =

6 4

3 7

Note 123 means from 1 to 3 in steps of 2 This technique alongwith the assignment operator can be used for values of whole rowscolumns or sub-matrices in one command For example

gt A(12123)=[10111213]

A =

10 -1 11

12 5 13

-3 6 7

Note that the elements A11 A13 A21 A23 now contain the values10 11 12 and 13 respectively instead of their previous values

Index notation is logically an unfortunate phenomenon since itclashes with standard function notation On the face of it A(3)

should be the value of a function called A with input 3 but whenit is interpreted as index notation A is a variable However indexnotation is so familiar and useful to those familiar with classicalmathematical notation that many developers of mathematical soft-ware are not prepared to risk a ldquoconsumer backlashrdquo to providinga functional way of extracting elements from an array such as forexample 3 pick A to pick out the third element of A Similarlywe as teachers feel we would be doing students a disservice if wefailed to introduce them to the index notation that abounds inmathematical texts usually in the form of subscripting as in A3Logic does not always win an argument In the commercial worldof computing an established user base carries more weight thanmathematical logic just as in mathematics tradition may well alsofly in the face of logical consistency

B43 Array arithmetic

Scilab has two forms of arithmetic operations that can be usedwith matrices matrix arithmetic or array arithmetic Matrix arith-metic follows the normal rules of matrix algebra Array arithmeticwhich is also called element-by-element arithmetic is where oper-ations are performed on matrices element by element

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 7: Programming With Scilab

B3 Variables 231

Table B1 Special variables and constants in ScilabName Description

pi The value of π to the precession of the machineis returned

i Recognised as theradicminus1

inf This is Scilabrsquos representation of infin This is arecognised value in a variable and typically ap-pears as a result of division by zero or logarithmof zero

nan Stands for Not a Number This is a recognisedvalue in a variable and appears as a result ofa mathematically undefined operation such asdivision of zero by zero or infinminusinfin

eps Floating point relative accuracy That is epsreturns the smallest difference resolvable be-tween two floating point numbers For examplethe next largest representable number beyond10 is 10+eps Scilab cannot represent anyfloating point number that falls between 10 and10+eps

ans This variable contains the last computed expres-sion that was not stored in a variable

date This variable contains a string representation oftodayrsquos date in the format dd-mmm-yyyy Forexample 01-Apr-2000

232 Appendix B Programming with Scilab

Table B2 Scilab Arithmetic OperatorsOperator Meaning Scilab

^ Exponentiation xy x^y

Multiply xtimes y xy

Right Division xy = xy xy

Left Division yx = xy yx

+ Addition x+ y x+y

- Subtraction xminus y x-y

of a calculation will be stored in a special variable called ans (seeans

Table B1) The value stored in this variable is overridden the nexttime a calculation is done that is not assigned to a variable Thismeans that the result from the previous calculation is then lost

B4 Arithmetic expressions

Table B2 lists the basic arithmetic operators to be found in ScilabWith the exception of the left division operator the arithmetic op-erators in Scilab follow standard notation

B41 Precedence

When more than one operation appears in a mathematical state-ment the programming language needs to define in which order theoperations must be performed or the precedence That is whichparts are evaluated first

If precedence was not defined then the same statement can be eval-uated to a different result for example is 186+3 equal to 2 oris 186+3 equal to 6 The first statement is evaluated from theright using the precedence rule that usually applies in mathemat-ical statements that is work from right to left as for example inlsquosin log tan xrsquo where we start with a value of x compute the tan-gent of that value (tan x) then take the logarithm of the resultingnumber (log(tan x)) and finally take the sine of what this deliv-ers However it is usual (because it is much easier to write poly-nomials with this convention) to give multiplication and divisionprecedence over addition and subtraction The second statementrecognises the precedence of the division over addition and evalu-ates it first Right to left precedence has a much simpler parsingtree than schemes which give precedence to particular operatorsbut the common arithmetic precedences are so widely acceptedand expected that most computer language designers will not riskthe possible lsquoconsumer backlashrsquo that breaking with this traditionwould involve So with every computer language one must searchout and learn the precedence rules that it adopts The usual arith-metic precedences will normally be observed but note that even

B4 Arithmetic expressions 233

Table B3 Precedence of arithmetic expressionsOperator Precedence Order of evaluation

() 1 Left to right innermost first 2 Left to right 3 Left to right 4 Right to left

+ minus 5 Left to right

they are not unambiguous For example which divide has prece-dence in 41632 Working right to left one would get the answerof 8 but Scilab returns (the decimal for) 1128 mdashit works fromleft to right Table B3 lists the operators and their precedencevalue

The rules for evaluation of operators are as follows

bull Operators having high precedence (low numerical value) willbe evaluated before those having a low precedence (high nu-merical value)

bull If an expression contains more than one operator at the samelevel of precedence then the left-to-right rule of evaluationapply

Parentheses () always have the highest precedence Whateveris within the parentheses is evaluated first This means when indoubt about the order of any statement place parentheses aroundthe statement to ensure that the operations are performed in theorder you expect

B42 Matrix arithmetic

One of the strengths of Scilab is its ability to execute matrixarithmetic3 Matrix arithmetic must be implemented in other lan-guages with many lines of code or special functions Scilab isespecially designed to handle matrix arithmetic The representsmatrix multiplication or scalar multiplication of a matrix if one ofthe arguments is a scalar Since scalars are 1times1 matrices ordinaryscalar multiplication can also be performed by the operator Thedot product of two vectors however requires that the first vectorbe a row vector and the second a column vector To multiply thecorresponding elements in two vectors together requires a differentoperator so that

gt a = [2 3 4] b = [6 7 8]

a b

ans =

12 21 32

3 Remember vectors are examples of matrices A column vector of length nis an example of a ntimes 1 matrix

234 Appendix B Programming with Scilab

However because it is a matrix operation

gt a + b

ans =

8 10 40

The standard arithmetic operators described in Table B2 are alsoused with matrices The normal rules of matrix addition subtrac-tion and multiplication apply

The left and right division of matrices are also generalisations ofscalar division Right division BA is roughly the same as Binv(A)Left division AB is roughly the same as inv(A)B The differenceis in how the division is performed Different algorithms are usedwhen A or B are square or not

Scilab also defines a transpose operator for matrices The trans-pose of the matrix A is Arsquo For example if

A =

[25 63

12 09

] then A prime =

[25 12

63 09

]

Accessing matrix elements

Individual elements of a matrix can accessed and used in state-ments by specifying the matrix index of an element The index ofan element is its position in the matrix For example consider thefollowing matrix

A =

6 minus1 4

3 5 7

minus3 6 1

Define this in Scilab with the command

A=[ 6 -1 4 3 5 7 -3 6 7]

to display the contents of matrix A in Scilab just type the variablename A To display or use one element from the matrix specify theelement For example A(13) specifies the element in the first rowand third column that is 4 for the above matrix

To change a specific entry just assign a value to it For example

A(31)=-9

changes the value of the third row first column element from -3

to -9

To display or use a whole row or column use the operator Forexample

gt A(2)

ans =

3 5 7

gt A(2)

B4 Arithmetic expressions 235

ans =

-1

5

6

It is also possible to pick out a sub-matrix by the specifying the rowand column entries required For example To pick out the sub-matrix of A containing the elementsA11 A13 A21 A23 the commandA(12123) could be used as shown below

gt A(12123)

ans =

6 4

3 7

Note 123 means from 1 to 3 in steps of 2 This technique alongwith the assignment operator can be used for values of whole rowscolumns or sub-matrices in one command For example

gt A(12123)=[10111213]

A =

10 -1 11

12 5 13

-3 6 7

Note that the elements A11 A13 A21 A23 now contain the values10 11 12 and 13 respectively instead of their previous values

Index notation is logically an unfortunate phenomenon since itclashes with standard function notation On the face of it A(3)

should be the value of a function called A with input 3 but whenit is interpreted as index notation A is a variable However indexnotation is so familiar and useful to those familiar with classicalmathematical notation that many developers of mathematical soft-ware are not prepared to risk a ldquoconsumer backlashrdquo to providinga functional way of extracting elements from an array such as forexample 3 pick A to pick out the third element of A Similarlywe as teachers feel we would be doing students a disservice if wefailed to introduce them to the index notation that abounds inmathematical texts usually in the form of subscripting as in A3Logic does not always win an argument In the commercial worldof computing an established user base carries more weight thanmathematical logic just as in mathematics tradition may well alsofly in the face of logical consistency

B43 Array arithmetic

Scilab has two forms of arithmetic operations that can be usedwith matrices matrix arithmetic or array arithmetic Matrix arith-metic follows the normal rules of matrix algebra Array arithmeticwhich is also called element-by-element arithmetic is where oper-ations are performed on matrices element by element

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 8: Programming With Scilab

232 Appendix B Programming with Scilab

Table B2 Scilab Arithmetic OperatorsOperator Meaning Scilab

^ Exponentiation xy x^y

Multiply xtimes y xy

Right Division xy = xy xy

Left Division yx = xy yx

+ Addition x+ y x+y

- Subtraction xminus y x-y

of a calculation will be stored in a special variable called ans (seeans

Table B1) The value stored in this variable is overridden the nexttime a calculation is done that is not assigned to a variable Thismeans that the result from the previous calculation is then lost

B4 Arithmetic expressions

Table B2 lists the basic arithmetic operators to be found in ScilabWith the exception of the left division operator the arithmetic op-erators in Scilab follow standard notation

B41 Precedence

When more than one operation appears in a mathematical state-ment the programming language needs to define in which order theoperations must be performed or the precedence That is whichparts are evaluated first

If precedence was not defined then the same statement can be eval-uated to a different result for example is 186+3 equal to 2 oris 186+3 equal to 6 The first statement is evaluated from theright using the precedence rule that usually applies in mathemat-ical statements that is work from right to left as for example inlsquosin log tan xrsquo where we start with a value of x compute the tan-gent of that value (tan x) then take the logarithm of the resultingnumber (log(tan x)) and finally take the sine of what this deliv-ers However it is usual (because it is much easier to write poly-nomials with this convention) to give multiplication and divisionprecedence over addition and subtraction The second statementrecognises the precedence of the division over addition and evalu-ates it first Right to left precedence has a much simpler parsingtree than schemes which give precedence to particular operatorsbut the common arithmetic precedences are so widely acceptedand expected that most computer language designers will not riskthe possible lsquoconsumer backlashrsquo that breaking with this traditionwould involve So with every computer language one must searchout and learn the precedence rules that it adopts The usual arith-metic precedences will normally be observed but note that even

B4 Arithmetic expressions 233

Table B3 Precedence of arithmetic expressionsOperator Precedence Order of evaluation

() 1 Left to right innermost first 2 Left to right 3 Left to right 4 Right to left

+ minus 5 Left to right

they are not unambiguous For example which divide has prece-dence in 41632 Working right to left one would get the answerof 8 but Scilab returns (the decimal for) 1128 mdashit works fromleft to right Table B3 lists the operators and their precedencevalue

The rules for evaluation of operators are as follows

bull Operators having high precedence (low numerical value) willbe evaluated before those having a low precedence (high nu-merical value)

bull If an expression contains more than one operator at the samelevel of precedence then the left-to-right rule of evaluationapply

Parentheses () always have the highest precedence Whateveris within the parentheses is evaluated first This means when indoubt about the order of any statement place parentheses aroundthe statement to ensure that the operations are performed in theorder you expect

B42 Matrix arithmetic

One of the strengths of Scilab is its ability to execute matrixarithmetic3 Matrix arithmetic must be implemented in other lan-guages with many lines of code or special functions Scilab isespecially designed to handle matrix arithmetic The representsmatrix multiplication or scalar multiplication of a matrix if one ofthe arguments is a scalar Since scalars are 1times1 matrices ordinaryscalar multiplication can also be performed by the operator Thedot product of two vectors however requires that the first vectorbe a row vector and the second a column vector To multiply thecorresponding elements in two vectors together requires a differentoperator so that

gt a = [2 3 4] b = [6 7 8]

a b

ans =

12 21 32

3 Remember vectors are examples of matrices A column vector of length nis an example of a ntimes 1 matrix

234 Appendix B Programming with Scilab

However because it is a matrix operation

gt a + b

ans =

8 10 40

The standard arithmetic operators described in Table B2 are alsoused with matrices The normal rules of matrix addition subtrac-tion and multiplication apply

The left and right division of matrices are also generalisations ofscalar division Right division BA is roughly the same as Binv(A)Left division AB is roughly the same as inv(A)B The differenceis in how the division is performed Different algorithms are usedwhen A or B are square or not

Scilab also defines a transpose operator for matrices The trans-pose of the matrix A is Arsquo For example if

A =

[25 63

12 09

] then A prime =

[25 12

63 09

]

Accessing matrix elements

Individual elements of a matrix can accessed and used in state-ments by specifying the matrix index of an element The index ofan element is its position in the matrix For example consider thefollowing matrix

A =

6 minus1 4

3 5 7

minus3 6 1

Define this in Scilab with the command

A=[ 6 -1 4 3 5 7 -3 6 7]

to display the contents of matrix A in Scilab just type the variablename A To display or use one element from the matrix specify theelement For example A(13) specifies the element in the first rowand third column that is 4 for the above matrix

To change a specific entry just assign a value to it For example

A(31)=-9

changes the value of the third row first column element from -3

to -9

To display or use a whole row or column use the operator Forexample

gt A(2)

ans =

3 5 7

gt A(2)

B4 Arithmetic expressions 235

ans =

-1

5

6

It is also possible to pick out a sub-matrix by the specifying the rowand column entries required For example To pick out the sub-matrix of A containing the elementsA11 A13 A21 A23 the commandA(12123) could be used as shown below

gt A(12123)

ans =

6 4

3 7

Note 123 means from 1 to 3 in steps of 2 This technique alongwith the assignment operator can be used for values of whole rowscolumns or sub-matrices in one command For example

gt A(12123)=[10111213]

A =

10 -1 11

12 5 13

-3 6 7

Note that the elements A11 A13 A21 A23 now contain the values10 11 12 and 13 respectively instead of their previous values

Index notation is logically an unfortunate phenomenon since itclashes with standard function notation On the face of it A(3)

should be the value of a function called A with input 3 but whenit is interpreted as index notation A is a variable However indexnotation is so familiar and useful to those familiar with classicalmathematical notation that many developers of mathematical soft-ware are not prepared to risk a ldquoconsumer backlashrdquo to providinga functional way of extracting elements from an array such as forexample 3 pick A to pick out the third element of A Similarlywe as teachers feel we would be doing students a disservice if wefailed to introduce them to the index notation that abounds inmathematical texts usually in the form of subscripting as in A3Logic does not always win an argument In the commercial worldof computing an established user base carries more weight thanmathematical logic just as in mathematics tradition may well alsofly in the face of logical consistency

B43 Array arithmetic

Scilab has two forms of arithmetic operations that can be usedwith matrices matrix arithmetic or array arithmetic Matrix arith-metic follows the normal rules of matrix algebra Array arithmeticwhich is also called element-by-element arithmetic is where oper-ations are performed on matrices element by element

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 9: Programming With Scilab

B4 Arithmetic expressions 233

Table B3 Precedence of arithmetic expressionsOperator Precedence Order of evaluation

() 1 Left to right innermost first 2 Left to right 3 Left to right 4 Right to left

+ minus 5 Left to right

they are not unambiguous For example which divide has prece-dence in 41632 Working right to left one would get the answerof 8 but Scilab returns (the decimal for) 1128 mdashit works fromleft to right Table B3 lists the operators and their precedencevalue

The rules for evaluation of operators are as follows

bull Operators having high precedence (low numerical value) willbe evaluated before those having a low precedence (high nu-merical value)

bull If an expression contains more than one operator at the samelevel of precedence then the left-to-right rule of evaluationapply

Parentheses () always have the highest precedence Whateveris within the parentheses is evaluated first This means when indoubt about the order of any statement place parentheses aroundthe statement to ensure that the operations are performed in theorder you expect

B42 Matrix arithmetic

One of the strengths of Scilab is its ability to execute matrixarithmetic3 Matrix arithmetic must be implemented in other lan-guages with many lines of code or special functions Scilab isespecially designed to handle matrix arithmetic The representsmatrix multiplication or scalar multiplication of a matrix if one ofthe arguments is a scalar Since scalars are 1times1 matrices ordinaryscalar multiplication can also be performed by the operator Thedot product of two vectors however requires that the first vectorbe a row vector and the second a column vector To multiply thecorresponding elements in two vectors together requires a differentoperator so that

gt a = [2 3 4] b = [6 7 8]

a b

ans =

12 21 32

3 Remember vectors are examples of matrices A column vector of length nis an example of a ntimes 1 matrix

234 Appendix B Programming with Scilab

However because it is a matrix operation

gt a + b

ans =

8 10 40

The standard arithmetic operators described in Table B2 are alsoused with matrices The normal rules of matrix addition subtrac-tion and multiplication apply

The left and right division of matrices are also generalisations ofscalar division Right division BA is roughly the same as Binv(A)Left division AB is roughly the same as inv(A)B The differenceis in how the division is performed Different algorithms are usedwhen A or B are square or not

Scilab also defines a transpose operator for matrices The trans-pose of the matrix A is Arsquo For example if

A =

[25 63

12 09

] then A prime =

[25 12

63 09

]

Accessing matrix elements

Individual elements of a matrix can accessed and used in state-ments by specifying the matrix index of an element The index ofan element is its position in the matrix For example consider thefollowing matrix

A =

6 minus1 4

3 5 7

minus3 6 1

Define this in Scilab with the command

A=[ 6 -1 4 3 5 7 -3 6 7]

to display the contents of matrix A in Scilab just type the variablename A To display or use one element from the matrix specify theelement For example A(13) specifies the element in the first rowand third column that is 4 for the above matrix

To change a specific entry just assign a value to it For example

A(31)=-9

changes the value of the third row first column element from -3

to -9

To display or use a whole row or column use the operator Forexample

gt A(2)

ans =

3 5 7

gt A(2)

B4 Arithmetic expressions 235

ans =

-1

5

6

It is also possible to pick out a sub-matrix by the specifying the rowand column entries required For example To pick out the sub-matrix of A containing the elementsA11 A13 A21 A23 the commandA(12123) could be used as shown below

gt A(12123)

ans =

6 4

3 7

Note 123 means from 1 to 3 in steps of 2 This technique alongwith the assignment operator can be used for values of whole rowscolumns or sub-matrices in one command For example

gt A(12123)=[10111213]

A =

10 -1 11

12 5 13

-3 6 7

Note that the elements A11 A13 A21 A23 now contain the values10 11 12 and 13 respectively instead of their previous values

Index notation is logically an unfortunate phenomenon since itclashes with standard function notation On the face of it A(3)

should be the value of a function called A with input 3 but whenit is interpreted as index notation A is a variable However indexnotation is so familiar and useful to those familiar with classicalmathematical notation that many developers of mathematical soft-ware are not prepared to risk a ldquoconsumer backlashrdquo to providinga functional way of extracting elements from an array such as forexample 3 pick A to pick out the third element of A Similarlywe as teachers feel we would be doing students a disservice if wefailed to introduce them to the index notation that abounds inmathematical texts usually in the form of subscripting as in A3Logic does not always win an argument In the commercial worldof computing an established user base carries more weight thanmathematical logic just as in mathematics tradition may well alsofly in the face of logical consistency

B43 Array arithmetic

Scilab has two forms of arithmetic operations that can be usedwith matrices matrix arithmetic or array arithmetic Matrix arith-metic follows the normal rules of matrix algebra Array arithmeticwhich is also called element-by-element arithmetic is where oper-ations are performed on matrices element by element

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 10: Programming With Scilab

234 Appendix B Programming with Scilab

However because it is a matrix operation

gt a + b

ans =

8 10 40

The standard arithmetic operators described in Table B2 are alsoused with matrices The normal rules of matrix addition subtrac-tion and multiplication apply

The left and right division of matrices are also generalisations ofscalar division Right division BA is roughly the same as Binv(A)Left division AB is roughly the same as inv(A)B The differenceis in how the division is performed Different algorithms are usedwhen A or B are square or not

Scilab also defines a transpose operator for matrices The trans-pose of the matrix A is Arsquo For example if

A =

[25 63

12 09

] then A prime =

[25 12

63 09

]

Accessing matrix elements

Individual elements of a matrix can accessed and used in state-ments by specifying the matrix index of an element The index ofan element is its position in the matrix For example consider thefollowing matrix

A =

6 minus1 4

3 5 7

minus3 6 1

Define this in Scilab with the command

A=[ 6 -1 4 3 5 7 -3 6 7]

to display the contents of matrix A in Scilab just type the variablename A To display or use one element from the matrix specify theelement For example A(13) specifies the element in the first rowand third column that is 4 for the above matrix

To change a specific entry just assign a value to it For example

A(31)=-9

changes the value of the third row first column element from -3

to -9

To display or use a whole row or column use the operator Forexample

gt A(2)

ans =

3 5 7

gt A(2)

B4 Arithmetic expressions 235

ans =

-1

5

6

It is also possible to pick out a sub-matrix by the specifying the rowand column entries required For example To pick out the sub-matrix of A containing the elementsA11 A13 A21 A23 the commandA(12123) could be used as shown below

gt A(12123)

ans =

6 4

3 7

Note 123 means from 1 to 3 in steps of 2 This technique alongwith the assignment operator can be used for values of whole rowscolumns or sub-matrices in one command For example

gt A(12123)=[10111213]

A =

10 -1 11

12 5 13

-3 6 7

Note that the elements A11 A13 A21 A23 now contain the values10 11 12 and 13 respectively instead of their previous values

Index notation is logically an unfortunate phenomenon since itclashes with standard function notation On the face of it A(3)

should be the value of a function called A with input 3 but whenit is interpreted as index notation A is a variable However indexnotation is so familiar and useful to those familiar with classicalmathematical notation that many developers of mathematical soft-ware are not prepared to risk a ldquoconsumer backlashrdquo to providinga functional way of extracting elements from an array such as forexample 3 pick A to pick out the third element of A Similarlywe as teachers feel we would be doing students a disservice if wefailed to introduce them to the index notation that abounds inmathematical texts usually in the form of subscripting as in A3Logic does not always win an argument In the commercial worldof computing an established user base carries more weight thanmathematical logic just as in mathematics tradition may well alsofly in the face of logical consistency

B43 Array arithmetic

Scilab has two forms of arithmetic operations that can be usedwith matrices matrix arithmetic or array arithmetic Matrix arith-metic follows the normal rules of matrix algebra Array arithmeticwhich is also called element-by-element arithmetic is where oper-ations are performed on matrices element by element

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 11: Programming With Scilab

B4 Arithmetic expressions 235

ans =

-1

5

6

It is also possible to pick out a sub-matrix by the specifying the rowand column entries required For example To pick out the sub-matrix of A containing the elementsA11 A13 A21 A23 the commandA(12123) could be used as shown below

gt A(12123)

ans =

6 4

3 7

Note 123 means from 1 to 3 in steps of 2 This technique alongwith the assignment operator can be used for values of whole rowscolumns or sub-matrices in one command For example

gt A(12123)=[10111213]

A =

10 -1 11

12 5 13

-3 6 7

Note that the elements A11 A13 A21 A23 now contain the values10 11 12 and 13 respectively instead of their previous values

Index notation is logically an unfortunate phenomenon since itclashes with standard function notation On the face of it A(3)

should be the value of a function called A with input 3 but whenit is interpreted as index notation A is a variable However indexnotation is so familiar and useful to those familiar with classicalmathematical notation that many developers of mathematical soft-ware are not prepared to risk a ldquoconsumer backlashrdquo to providinga functional way of extracting elements from an array such as forexample 3 pick A to pick out the third element of A Similarlywe as teachers feel we would be doing students a disservice if wefailed to introduce them to the index notation that abounds inmathematical texts usually in the form of subscripting as in A3Logic does not always win an argument In the commercial worldof computing an established user base carries more weight thanmathematical logic just as in mathematics tradition may well alsofly in the face of logical consistency

B43 Array arithmetic

Scilab has two forms of arithmetic operations that can be usedwith matrices matrix arithmetic or array arithmetic Matrix arith-metic follows the normal rules of matrix algebra Array arithmeticwhich is also called element-by-element arithmetic is where oper-ations are performed on matrices element by element

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 12: Programming With Scilab

236 Appendix B Programming with Scilab

Table B4 Scilab array operatorsOperator Meaning Scilab

^ Exponentiation x^y

Multiply xy

Right Division xy

Left Division yx

+ Addition x+y

- Subtraction x-y

Table B4 lists the Scilab array operators

The array addition and subtraction are identical to matrix additionor subtraction Both array and matrix addition and subtractionoperate element by element Array addition and subtraction re-quire that both arrays have the same size The only exception tothis rule in Scilab occurs when we add or subtract a scalar to orfrom an array In this case the scalar is added or subtracted fromeach element in the array

For example

gt [6 5 6] + 3

ans =

[9 8 9]

gt [6 4 5 8] + [3 1 2 4]

ans =

[9 5 7 12]

gt [4 3] - 7

ans =

[-3 -4]

Array multiplication and division is very different to matrix mul-tiplication and division Array multiplication or division is an ele-ment by element multiplication or division that produces an arraywith the same dimensions as the starting arrays As with addi-tion and subtraction array multiplication and division require thatboth arrays have the same dimensions

Example B2 Consider the two row vectors x=[2 4 7 1] andy=[6 1 3 2] Scilab does not recognise the possibility ofmatrix multiplication of these two vectors They are not com-patible the number of columns of the pre-multiplier must bethe same as the number of rows of the post-multiplier Anattempt to execute x y will bring an error message

Obtain the usual dot product of the two row vectors by trans-posing the post-multiplier as in xyrsquo or yxrsquo The matrixproduct xrsquoy produces a matrix of 4 rows and 4 columns

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 13: Programming With Scilab

B5 Builtndashin functions 237

Array multiplication produces the result

gt xy

ans =

[12 4 21 2]

by multiplying corresponding elements of each vector Theresult is a row vector with the same dimensions as x and ythat is a 1times 4 vector

Example B3 Consider the row vectors x=[2 4 7 1] and col-umn vector y=[6 1 3 2]rsquo Array multiplication of thesetwo matrices is not possible because their dimensions do notagree

Matrix multiplication xy produces the result 39 that is theinner product or dot product of the vectors Note vectorsas such do not exist in Scilab there are only single rowedor single columned arrays

Scilab not only allows arrays to be raised to powers but alsoallows scalars and arrays to be raised by array powers To performexponentiation on an element-by-element basis use the ^ symbolFor example if x=[3 5 8] then x^3 produces the matrix [33 53

83] = [27 125 512]

A scalar can be raised to an array power For example if p=[2 4 5]then typing 3^p produces the array [32 34 35] = [9 81 243]

With element-by-element array operations it is important to re-member that the dot () is a part of a two-character symbol for aparticular array operator such as () () () (^) Sometimesthis can cause some confusion the dot in 3^p is not a decimalpoint associated with the number 3 The following operations withthe value of p=[2 4 5] are equivalent

3^p

30^p

3^p

(3)^p

3^[2 4 5]

B5 Builtndashin functions

B51 Arithmetic functions

Arithmetic expressions often require computations other than ad-dition subtraction multiplication division and exponentiationFor example many expressions require the use of logarithms ex-ponentials and trigonometric functions Scilab has predefined alarge number of functions that perform these types of computations(see Tables B5 and B6)

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 14: Programming With Scilab

238 Appendix B Programming with Scilab

An example of a predefined function is sin which returns the sineof a given angle

m = sin(angle)

where the variable angle contains the angle in radians and theresult is stored in the variable m The variable angle is called theargument or parameter of the function If the angle is stored indegrees it must be converted to radians for example

m = sin(anglepi180)

or

radians =anglepi180

m = sin(radians)

In Scilab the arguments or parameters of the function are con-tained in parentheses following the name of the function This isreferred to as pre-fix notation Many common functions in math-ematics have a syntax using in-fix notation where two argumentsappear to the right and left of the function name as for examplein x+y atimes b nmod r etc Scilab does not support in-fix nota-tion for any but the arithmetic functions Classical mathematicalnotation also has examples of post-fix notationmdash n x squared mdashand other hybrids like |x| while Scilab has ahb to confound thepurist

A function may contain no arguments one argument or many ar-guments depending on its definition If a function contains morethan one argument it is vital to give the arguments in the cor-rect order For example consider the problem of finding θ in thefollowing triangle using the atan command

5

Now by hand calculation the answer is 05586 radians If we useatan as below we get the answers shown

--gt atan(58)

ans =

05586

--gt atan(85)

ans =

10122

The first answer is the correct one The second answer is incorrect

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 15: Programming With Scilab

B5 Builtndashin functions 239

Table B5 Some common mathematical functions defined inScilabFunction Description

abs(x) Computes the absolute value of xsqrt(x) Square root of x The parameter can be nega-

tiveround(x) Round x to the nearest integerfix(x) Round x to the nearest integer toward zerofloor(x) Round x to the nearest integer toward minusinfinceil(x) Round x to the nearest integer toward +infinsign(x) Returns -1 if x is less than zero zero if x equals

zero and 1 otherwisemodulo(xy) Returns the remainder of xy For example

modulo(254) is 1exp(x) Returns ex

log(x) Returns the natural logarithm of x That isthe logarithm to the base e Parameter can benegative but cannot be zero

log10(x) Returns the common logarithm of x That isthe logarithm to the base 10 Parameter can benegative but cannot be zero

since we passed the values to the function in the incorrect order

Some functions also require that the arguments be in specific unitsFor example the trigonometric functions assume that the argu-ments are in radians

In Scilab some functions use the number of arguments to deter-mine the output of the function For example the zeros functioncan have one or two arguments which then determine the output(check this with the command help zeros)

A function reference cannot be made on the left hand side of anassignment since a function call always returns a value(s) whereasan assignment is always to a variable Functions can of courseappear on the right side of an assignment since they return valuesto be assigned to some variable Functions may be applied tothe output of other functions and may be called in the algorithmdefining a function for example

logx = log(abs(x))

When one function is used to compute the argument of anotherfunction be sure to enclose the argument of each function in itsown set of parentheses

Scilab allows recursive functions that is functions that call them-selves in their defining algorithm

Exercise B4 Use examples to show the differences between the

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 16: Programming With Scilab

240 Appendix B Programming with Scilab

Table B6 Some common trigonometric functions defined inScilab

Function Description

sin(x) Sine of x where x is in radianscos(x) Cosine of x where x is in radianstan(x) Tangent of x where x is in radiansasin(x) Arcsine or inverse sine of x where x must be

between -1 and 1 The return angle is in radiansbetween minusπ2 and π2

acos(x) Arccosine or inverse cosine of x where x mustbe between minus1 and 1 The return angle is inradians between 0 and π

atan(x) Arctangent or inverse tangent of x The returnangle is in radians between minusπ2 and π2

atan(xy) Arctangent or inverse tangent of xy The re-turn angle is in radians between minusπ and π de-pending on the sign of x and y

sec(x) Secant (1(cos x)) of x where x is in radianscsc(x) Cosecant (1(sin x)) of x where x is in radianscotg(x) Cotangent (1(tan x)) of x where x is in radians

Table B7 Some of Scilabrsquos utility functionsFunction Description

clear Clear variables from memoryhelp Display the first set of comment lines from

scriptswho List the variables in memorywhos List the variables in memory with their sizeerror Terminates the execution of the Sci-file and out-

puts the supplied error message

functions round(x) fix(x) floor(x) and ceil(x)

Exercise B5 The functions listed in Tables B5 B6 are only asmall sample of all of Scilabrsquos mathematical functions

Using Scilabrsquos help command list all of the hyperbolic func-tions available Also list any restrictions on the values of thefunction arguments

B52 Utility functions

In addition to the arithmetic functions Scilab has several utilityfunctions (see Table B7) These functions allow users to trackvariables (whoswho) feedback an error message if an error occursin the code (error) clear the variables form the memory (clear)etc Essential these functions allow users to debug and performbookkeeping operations inside their code

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 17: Programming With Scilab

B6 Visualising data in Scilab 241

6

5

4- 04- 8

3

- 02

- 6

00

2- 4 Y- 2

02

Z

10

04

X 02

06

4 - 1

08

6- 28

10

Figure B2 Plot of z = sin(radicx2 + y2)

radicx2 + y2 illustrating the

3d capabilities of Scilab

B6 Visualising data in Scilab

One of the big advantages in using Scilab is the ability to visualisedata and results of complex calculations (see Figure B2 as exampleof the 3d capabilities) While Scilab is capability of complex 3dgraphics (see help pages for mesh and surf) in this section we willmesh amp surf

focus on the 2d plotting command (plot) Hence in this sectionplot

we will focus on

1 plotting mathematical functions from within Scilab

2 changing stylistic elements of the plot

3 adding titles labels and legends to the plot

4 including mathematical notation in titles labels and legendsand

5 plotting data stored in an external ASCII file

B61 Plotting mathematical functions from within Scilab

To plot a mathematical function in Scilab three steps are requiredThese are

1 Define the domain of the function (eg x=linspace(02pi))

2 Calculate the values of function at the selected points in thedomain (eg y=sin(x))

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 18: Programming With Scilab

242 Appendix B Programming with Scilab

3 Final step is to plot the function using the plot commandplot

(eg plot(xy))

Using these steps it is possible to produce a basic plot of any math-ematical function (see Figure B3) Note that the plot shown inFigure B3 does not have a title axes labels or a legend all ofwhich are crucial for a good plot The Scilab commands to addthese elements to the plot are given in the following sections

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

0 1 2 3 4 5 6 7

Figure B3 The default plot of y = sin(x) in Scilab Notethat by default axes are not labelled and there is no title orlegend These need to added using the additional commandsxlabelylabeltitle and legend

Changing stylistic elements of the plot

An optional argument can be given to the plot command to cus-tomise each new line aspect This argument is a concatenatedstring containing information about colour line style or markersbased on the specifiers shown in Table B8 To specify the plotbe drawn with a red longdash-dot line with diamond marker thestring that would be passed to plot command would be rsquor-drsquo Thestring which is a concatenation (in any order) of the three typesof properties shown in Table B8 must be unambiguous Further-more the string specification is not case sensitive An exampleof specifying various line styles is shown in Example B6 and Fig-ure B4

Example B6 The following commands illustrate how line stylescan be used to distinguish between the plots of sin(2πt) sin(2πt+π6) and sin(2πt+ π2)

t=linspace(0130)

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 19: Programming With Scilab

B6 Visualising data in Scilab 243

Table B8 Plot specifiers required to change line styles coloursand markers in plotsSpecifier Line style Specifier Colour Specifier Marker stylendash Solid line (default) r Red + Plus signndash ndash Dashed line g Green o Circle Dotted line b Blue Asteriskndash Dash-dotted line c Cyan x Cross

m Magenta s Squarey Yellow rsquononersquo No marker(default)k Blackw White

y2=sin(2pit+pi2)

y1=sin(2pit+pi6)

y=sin(2pit)

mtlb_hold on

plot(tyrsquor-orsquorsquoLineWidthrsquo15)

plot(ty1rsquog-srsquorsquoLineWidthrsquo15)

plot(ty2rsquoc--drsquorsquoLineWidthrsquo15)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6$)rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

legend(rsquo$y=sin(2pit)$rsquorsquo$y=sin(2pit+pi6)$rsquo

rsquo$y=sin(2pit+pi2)$rsquo)

xlabel(rsquotrsquo)

ylabel(rsquoyrsquo)

- 10

- 08

- 06

- 04

- 02

00

02

04

06

08

10

00 01 02 03 04 05 06 07 08 09 10t

y

Figure B4 Resulting plotting after issuing the commands givenin Example B6

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 20: Programming With Scilab

244 Appendix B Programming with Scilab

Example B6 illustrate a number of key commands relating to thecreation of multiple plots in Scilab The mtlb hold4 commandmtlb hold

holds the current plot and axis properties so that all subsequentplots are added to the existing plot

To distinguish each plot a different line specification is passed eachplot command In the example y = sin(2πt) is plotted using a redsolid line with data points indicated using a red circle as indicatedby the string rsquor-orsquo y = sin(2πt + π6) is plotted using greendashed-dotted line with data points marked by a square (rsquog-srsquo)while y = sin(2πt+ π2) is plotted using a cyan dashed line usingdiamonds to mark the data points (rsquoc--drsquo) Finally to completethe plot axes labels and a legend has been added to plot the com-mands for doing this are discussed in sectB62

B62 Adding titleslabels and legends to the plot

All good plots should have the following properties

1 The style of figure is appropriate to the information beingconveyed

2 The contents are well organised so it is easy for readers tointerpret the information

3 Legends labels etc are clear and concise (eg contain unitsif required do not obstruct parts of the plot etc) and

4 A caption or title that summarises the information presented

Like most mathematical applications Scilab has a wide variety ofdifferent plotting styles that can be used (eg look up the help forbar polarplot etc) This allows you to select the most appropri-barpolarplot

ate style to display and organise your data

The Scilab commands xlabel ylabel title and legend al-xlabel ylabel title and

legend lows you to add axes labels titles and legends to plot As shownin Example B6 the commands xlabel ylabel and title takea string input containing the title or label text For the legend

command a string is required for each separate plot Note theorder of the strings in the legend command reflects the order inwhich the each of plots were made

Including mathematical notation in titles labels and legends

It is possible to include mathematical characters such as π inScilab plots This is done by inserting special commands intoeither the title legend or label string These commands are basedon the abbreviations for mathematical notation used in programssuch as LATEX MathType etc A brief summary of the commands

4 mtlb hold on is equivalent to the Scilab commandset(gca()auto clearoff) while mtlb hold off is equivalentto the Scilab command set(gca()auto clearon)

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 21: Programming With Scilab

B6 Visualising data in Scilab 245

Table B9 Basic mathematical symbols available in Scilab forincluding mathematical notation in titles labels and legendscommand symbol command symbol command symbolalpha α upsilon υ sim sim

angle 6 phi φ leq least lowast chi χ infty infinbeta β psi ψ clubsuit clubsgamma γ omega ω diamondsuit diamsdelta δ Gamma Γ heartsuit heartsepsilon ε Delta ∆ spadesuit spadeszeta ζ Theta Θ leftrightarrow harreta η Lambda Λ leftarrow larrtheta θ Xi Ξ Leftarrow lArrvartheta ϑ Pi Π uparrow uarriota ι Sigma Σ rightarrow rarrkappa κ Upsilon Υ Rightarrow rArrlambda λ Phi Φ downarrow darrmu micro Psi Ψ circ nu ν Omega Ω pm plusmnxi ξ forall forall geq gepi π exists exist propto proprho ρ ni 3 partial partsigma σ cong sim= bullet bullvarsigma σ approx asymp div dividetau τ Re lt neq 6=equiv equiv oplus oplus aleph alefsym

Im = cup cup wp weierpotimes otimes subseteq sube oslash cap cap in isin supseteq supesupset sup lceil d subset subint

intcdot middot o oslash

rfloor c neg 6= nabla nablalfloor b times times ldots perp perp surd

radicprime prime

wedge and varpi $ O Oslashrceil e rangle 〉 mid |

vee or copyright ccopy langle 〈

available in Scilab for typesetting mathematical notation is givenin Table B9 To insert these commands into a text string simplystart and end the string with $ signs as shown in Example B7

Example B7 Scilab commands to produce the labelled plot ofy = sin

(2πt+ π

4

)shown in Figure B5

t=linspace(01)

y=sin(2pit+pi4)

plot(ty)

title(rsquo$y=sin(2pi t+fracpi4)$rsquorsquofontsizersquo5)

xlabel(rsquo$x$rsquorsquofontsizersquo4)

ylabel(rsquo$y$rsquorsquofontsizersquo4)

[abc]=xclick()

xset(lsquolsquofontrsquorsquo14)

xstring(bcrsquo$y=sin(2pi t+fracpi4)$rsquo)

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 22: Programming With Scilab

246 Appendix B Programming with Scilab

- 1 0

- 0 8

- 0 6

- 0 4

- 0 2

0 0

0 2

0 4

0 6

0 8

1 0

0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0

Figure B5 Plot of y = sin(2πt+ π

4

)illustrating the use of math-

ematical notation in labels

There are a few key concepts to note about the Example B7 Thefirst can be seen in the string being passed to the title commandtitle

In this string sin is prefixed with a backslash () This is doneso that the letters for sin are not typeset in italic which shouldonly be used for variables and not common mathematical func-tions Table B10 shows the command sequences to use for themore common mathematical functions5 To get the fraction in thetitle the command fracab has been used to produce a

b Ifsuperscripts and subscripts are required in a title or label these aresuperscripts amp subscripts

obtained by adding the subscript character ( ) and the superscriptcharacter (^) to the string These characters modify the characteror substring defined in braces immediately following For examplex 2 gives x2 while e^2x gives e2x

Note in Example B7 the commands xlabel and ylabel has beenxlabelylabel

used to set the axes labels in Figure B5 Instead of using thesethree commands the title and the axes labels could have been setusing the single xtitle command (see help xtitle for details)xtitle

In the example we have also customised the font size to make thetext more readable by a) passing an option to the title xlabelylabel commands and b) by using the command xset to set thexset

default font size before executing the xstring command Finallythe xstring command adds the text string to plot at the locationxstring

specified by variables b and c In the example the coordinates wewant to add the text are obtained by executing the xclick functionxclick

and clicking on the point required in the plot window

5 Additional details can be found in books covering Mathematics in LATEX

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 23: Programming With Scilab

B6 Visualising data in Scilab 247

Table B10 Command sequences for the common mathematicalfunctions in Scilabarccos arcsin arctan cos cot

csc exp lim ln log

max min sec sin tan

B63 Plotting numeric data stored in an ASCII file

As data can be stored in a wide variety of ways in external filesScilab has a wide variety of functions which can be used to importthe data stored in these files (see help for the commands read

fscanf and xlsread) Since data can be stored in such a wideread fscanf and xlsread

range of formats we will confine our discussions here to the situa-tion where numeric data is stored in a ASCII (text) file where eachrow of the file contains the same number of entries

To illustrate the procedure for plotting data stored in ASCII file wewill consider the data obtained measuring the temperature of a cupof coffee every minute for a total of 100 mins The data recorded isstored in the a file called coffeedatatxt6 which simply containsthe two columns of numbers shown in Table B11 As an examplethe first 10 lines of the text file contains the following numbers7

00000 1000000

10000 950000

20000 903125

30000 859180

40000 817981

50000 779357

60000 743147

70000 709201

80000 677376

90000 647540

Note the current version of Scilab has a builtin text editor whichcan be used to view such text files To access this editor simplytype the command edit at the command prompt Once open youedit

can use the graphical interface to open the required file

The first issue is to get the data into Scilab so it is available forplot command In Scilab the command read can used to importread

the data and assign it to a variable In the current example wewould use the following command to import the data and assignit to a variable called cdata assuming the data is in the currentdirectory8

6 The file coffeedatatxt has been attached and should be available for savingprovided you are using Adobe Reader To save the file right click on thepurple Windows version or the red MacOSLinux version in the margin andselect save file from the options Ensure you save the file as coffeedatatxt

7 normally you will have received the data file in this format8 You can check what directory Scilab is in by typing the command pwd

00000000e+00 10000000e+0213 10000000e+00 95000000e+0113 20000000e+00 90312500e+0113 30000000e+00 85917969e+0113 40000000e+00 81798096e+0113 50000000e+00 77935715e+0113 60000000e+00 74314733e+0113 70000000e+00 70920062e+0113 80000000e+00 67737558e+0113 90000000e+00 64753961e+0113 10000000e+01 61956838e+0113 11000000e+01 59334536e+0113 12000000e+01 56876127e+0113 13000000e+01 54571369e+0113 14000000e+01 52410659e+0113 15000000e+01 50384992e+0113 16000000e+01 48485930e+0113 17000000e+01 46705560e+0113 18000000e+01 45036462e+0113 19000000e+01 43471683e+0113 20000000e+01 42004703e+0113 21000000e+01 40629409e+0113 22000000e+01 39340071e+0113 23000000e+01 38131317e+0113 24000000e+01 36998109e+0113 25000000e+01 35935728e+0113 26000000e+01 34939745e+0113 27000000e+01 34006011e+0113 28000000e+01 33130635e+0113 29000000e+01 32309970e+0113 30000000e+01 31540597e+0113 31000000e+01 30819310e+0113 32000000e+01 30143103e+0113 33000000e+01 29509159e+0113 34000000e+01 28914837e+0113 35000000e+01 28357659e+0113 36000000e+01 27835306e+0113 37000000e+01 27345599e+0113 38000000e+01 26886499e+0113 39000000e+01 26456093e+0113 40000000e+01 26052587e+0113 41000000e+01 25674300e+0113 42000000e+01 25319657e+0113 43000000e+01 24987178e+0113 44000000e+01 24675479e+0113 45000000e+01 24383262e+0113 46000000e+01 24109308e+0113 47000000e+01 23852476e+0113 48000000e+01 23611697e+0113 49000000e+01 23385966e+0113 50000000e+01 23174343e+0113 51000000e+01 22975946e+0113 52000000e+01 22789950e+0113 53000000e+01 22615578e+0113 54000000e+01 22452104e+0113 55000000e+01 22298848e+0113 56000000e+01 22155170e+0113 57000000e+01 22020472e+0113 58000000e+01 21894192e+0113 59000000e+01 21775805e+0113 60000000e+01 21664817e+0113 61000000e+01 21560766e+0113 62000000e+01 21463218e+0113 63000000e+01 21371767e+0113 64000000e+01 21286032e+0113 65000000e+01 21205655e+0113 66000000e+01 21130301e+0113 67000000e+01 21059657e+0113 68000000e+01 20993429e+0113 69000000e+01 20931340e+0113 70000000e+01 20873131e+0113 71000000e+01 20818560e+0113 72000000e+01 20767400e+0113 73000000e+01 20719438e+0113 74000000e+01 20674473e+0113 75000000e+01 20632318e+0113 76000000e+01 20592798e+0113 77000000e+01 20555748e+0113 78000000e+01 20521014e+0113 79000000e+01 20488451e+0113 80000000e+01 20457923e+0113 81000000e+01 20429302e+0113 82000000e+01 20402471e+0113 83000000e+01 20377317e+0113 84000000e+01 20353734e+0113 85000000e+01 20331626e+0113 86000000e+01 20310899e+0113 87000000e+01 20291468e+0113 88000000e+01 20273251e+0113 89000000e+01 20256173e+0113 90000000e+01 20240162e+0113 91000000e+01 20225152e+0113 92000000e+01 20211080e+0113 93000000e+01 20197888e+0113 94000000e+01 20185520e+0113 95000000e+01 20173925e+0113 96000000e+01 20163054e+0113 97000000e+01 20152863e+0113 98000000e+01 20143310e+0113 99000000e+01 20134353e+0113 10000000e+02 20125956e+0113

00000000e+00 10000000e+02 10000000e+00 95000000e+01 20000000e+00 90312500e+01 30000000e+00 85917969e+01 40000000e+00 81798096e+01 50000000e+00 77935715e+01 60000000e+00 74314733e+01 70000000e+00 70920062e+01 80000000e+00 67737558e+01 90000000e+00 64753961e+01 10000000e+01 61956838e+01 11000000e+01 59334536e+01 12000000e+01 56876127e+01 13000000e+01 54571369e+01 14000000e+01 52410659e+01 15000000e+01 50384992e+01 16000000e+01 48485930e+01 17000000e+01 46705560e+01 18000000e+01 45036462e+01 19000000e+01 43471683e+01 20000000e+01 42004703e+01 21000000e+01 40629409e+01 22000000e+01 39340071e+01 23000000e+01 38131317e+01 24000000e+01 36998109e+01 25000000e+01 35935728e+01 26000000e+01 34939745e+01 27000000e+01 34006011e+01 28000000e+01 33130635e+01 29000000e+01 32309970e+01 30000000e+01 31540597e+01 31000000e+01 30819310e+01 32000000e+01 30143103e+01 33000000e+01 29509159e+01 34000000e+01 28914837e+01 35000000e+01 28357659e+01 36000000e+01 27835306e+01 37000000e+01 27345599e+01 38000000e+01 26886499e+01 39000000e+01 26456093e+01 40000000e+01 26052587e+01 41000000e+01 25674300e+01 42000000e+01 25319657e+01 43000000e+01 24987178e+01 44000000e+01 24675479e+01 45000000e+01 24383262e+01 46000000e+01 24109308e+01 47000000e+01 23852476e+01 48000000e+01 23611697e+01 49000000e+01 23385966e+01 50000000e+01 23174343e+01 51000000e+01 22975946e+01 52000000e+01 22789950e+01 53000000e+01 22615578e+01 54000000e+01 22452104e+01 55000000e+01 22298848e+01 56000000e+01 22155170e+01 57000000e+01 22020472e+01 58000000e+01 21894192e+01 59000000e+01 21775805e+01 60000000e+01 21664817e+01 61000000e+01 21560766e+01 62000000e+01 21463218e+01 63000000e+01 21371767e+01 64000000e+01 21286032e+01 65000000e+01 21205655e+01 66000000e+01 21130301e+01 67000000e+01 21059657e+01 68000000e+01 20993429e+01 69000000e+01 20931340e+01 70000000e+01 20873131e+01 71000000e+01 20818560e+01 72000000e+01 20767400e+01 73000000e+01 20719438e+01 74000000e+01 20674473e+01 75000000e+01 20632318e+01 76000000e+01 20592798e+01 77000000e+01 20555748e+01 78000000e+01 20521014e+01 79000000e+01 20488451e+01 80000000e+01 20457923e+01 81000000e+01 20429302e+01 82000000e+01 20402471e+01 83000000e+01 20377317e+01 84000000e+01 20353734e+01 85000000e+01 20331626e+01 86000000e+01 20310899e+01 87000000e+01 20291468e+01 88000000e+01 20273251e+01 89000000e+01 20256173e+01 90000000e+01 20240162e+01 91000000e+01 20225152e+01 92000000e+01 20211080e+01 93000000e+01 20197888e+01 94000000e+01 20185520e+01 95000000e+01 20173925e+01 96000000e+01 20163054e+01 97000000e+01 20152863e+01 98000000e+01 20143310e+01 99000000e+01 20134353e+01 10000000e+02 20125956e+01

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 24: Programming With Scilab

248 Appendix B Programming with Scilab

20

30

40

50

60

70

80

90

100

0 10 20 30 40 50 60 70 80 90 100

t ime (mins)

Figure B6 Temperature of coffee based on the data recorded inthe file coffeedatatxt

cdata=read(rsquocoffeedatatxtrsquo-12)

The -12 following the name of the file tells Scilab that you donrsquotknow how many rows you have but you have two columns of dataSince we know that we have 101 rows of data we could have alsoused the following command to load the data

cdata=read(rsquocoffeedatatxtrsquo1012)

We now have a variable called cdata which has two columns ofdata The first column contains the time while the second containsthe Temperature records Hence we can plot it using the followingcommand

plot(cdata(1)cdata(2))

This gives the plot shown in Figure B6 after appropriate labelshave been added as described above

B7 Script files

Executing commands entered at the keyboard or keypad is themost primitive use of a calculating device It is only when se-quences of operations (to perform complex tasks) are stored awayand re-called for repeated application with different inputs that wehave a programmed operation Complex programs must necessarilyhave an interface with the user The basic interface tool in Scilabcapable of executing sequences of commands that are stored in a fileis the script The file names must have an extension of sce forexample program1sce assignment1sce These files are calledScript Sci-files or simply scripts

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 25: Programming With Scilab

B7 Script files 249

Table B11 Coffee temperature recordings at one minute intervalsTime (mins) Temperature (C) Time (mins) Temperature (C)00000 1000000 510000 22975910000 950000 520000 22790020000 903125 530000 22615630000 859180 540000 22452140000 817981 550000 22298850000 779357 560000 22155260000 743147 570000 22020570000 709201 580000 21894280000 677376 590000 21775890000 647540 600000 216648100000 619568 610000 215608110000 593345 620000 214632120000 568761 630000 213718130000 545714 640000 212860140000 524107 650000 212057150000 503850 660000 211303160000 484859 670000 210597170000 467056 680000 209934180000 450365 690000 209313190000 434717 700000 208731200000 420047 710000 208186210000 406294 720000 207674220000 393401 730000 207194230000 381313 740000 206745240000 369981 750000 206323250000 359357 760000 205928260000 349397 770000 205557270000 340060 780000 205210280000 331306 790000 204885290000 323100 800000 204579300000 315406 810000 204293310000 308193 820000 204025320000 301431 830000 203773330000 295092 840000 203537340000 289148 850000 203316350000 283577 860000 203109360000 278353 870000 202915370000 273456 880000 202733380000 268865 890000 202562390000 264561 900000 202402400000 260526 910000 202252410000 256743 920000 202111420000 253197 930000 201979430000 249872 940000 201855440000 246755 950000 201739450000 243833 960000 201631460000 241093 970000 201529470000 238525 980000 201433480000 236117 990000 201344490000 233860 1000000 201260500000 231743

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 26: Programming With Scilab

250 Appendix B Programming with Scilab

A script file is a file of standard keyboard charactersthat define commands to drive a program A script filecan be generated using any text editor or word proces-sor

To invoke a script in Scilab type the commandexec

exec filenamesce

where filename denotes the actual name of the file containing thescript When the script runs it is exactly the same as if you typedthe commands into the command window from the keyboard Thismeans that the Sci-file can use any variables you have defined priorto invoking the script Any variables created in the script are alsoavailable when the script is finished and any variable whose namewas assigned a value in the script will be over-written

If you give a script the same name as any variable that it computesin the running of the script then Scilab will give precedence tothe workspace variable over a script As stated in sectB3 the variablename will hide the script name after the script has run Scilab willtake the name as referring to the variable and not to the definedscript

Scilab also needs to know where to find the script to executedIf Scilab cannot find the script it will report that you have anundefined function or variable

The exact procedure for creating and saving Sci-files depends onthe Scilab version the operating system (MS Windows Macin-tosh or UnixLinux ) and the text editor you use The currentversion of Scilab includes a built-in editor which can be used tocreate and edit Sci-files and text files

To create a new Sci-file under the current version of Scilab simplytype edit newfilenamesce This will open up the Scilab editoredit

with a blank document called newfilename

B71 Script input and output

A script is a named file (with the extension sce) containing asequence of Scilab instructions which when its name is executedin a session performs those instructions in order as though theywere entered at the console

There are two common uses for scripts Pragmatically we maywant to save a particular computational sequence for later use orreference If the tasks involved are to be repeated often thenthe nature of the tasks should be analysed formulated into usefulfunctions (which we will discuss later) and the whole procedurepresented in a single function But if the tasks are only likely toget occasional use then the script may be adequately commentedand stored as a script file It is a quick and dirty way of saving

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 27: Programming With Scilab

B7 Script files 251

the instructions for doing a particular job when we do not wantto go to the trouble of writing the functions for the job It is nota highly recommended modus operandi but useful all the same

The second use is for the script to act like a storyboard presentinginformation to a user in a structured and controlled way permit-ting the user to see the steps of a computational procedure andtheir outputs up on the screen At a more sophisticated level thescript takes on the proportions of an application controlling a largeand complex interaction with advanced interface features We willnot take our study of Scilab programming to this level but workmostly at the storyboard level using the simplest of Scilabrsquos in-terface tools

All the variables created in a script become global variables definedin the workspace and available for perusal As an application itis assumed that a script controls the entire workspace and thevariables it creates are lsquothe datarsquo of the application When scriptsare used as storyboards on a small scale then it cannot be assumedthat the variables they create deserve global recognition and it iscourteous to erase these variables when the script is finished unlessthey have some possible further use An unfortunate side-effect isthat if variables with the same name already exist in the workspacebefore a script is run then these variables will be over-written andlost

Used as storyboards scripts allow the user to cut paste and re-trythe various steps of a procedure and to modify the script to suithis own needs Storyboards may be used for demonstrations oftoolbox utilities or extended documentationexplanation of func-tions However if there is any danger that variables defined bythe script may over-write workspace variables then the demo ordocumentation should be re-fashioned into a function that leavesthe workspace variables untouched (more on this later)

Scripts will often read data from pre-prepared files and we will dis-cuss the functions provided by Scilab to perform this task below

Gathering data entered by the user really falls into the realm ofinterface design but we only briefly consider the simplest interfacefunction provided by Scilab Similarly we briefly consider thefunctions for providing the simplest forms of output presentation

Keyboard input

Scilab has a built-in function input that can be used to promptinput

the user to enter the value of a variable from the keyboard Forexample

Tc = input(rsquoPlease enter the temperature in degrees Celsiusrsquo)

will print the message

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 28: Programming With Scilab

252 Appendix B Programming with Scilab

Please enter the temperature in degrees Celsius

and Scilab will wait for the input The input is terminated bypressing the Enter (or Return) key

The input entered can be any valid Scilab expression which willbe evaluated and the answer assigned to the variable (in this caseTc) in the input statement For example

Please enter the temperature in degrees Celsius [025100]

where the [025100] has been entered by the user in response tothe input prompt The variable Tc will be assigned the row vector[0 25 50 75 100]

Example B8

Script quad_0s

Variables createdoverwritten

A B C D x1 x2 x y a b w thezeros

Purpose To illustrate the use of the

quadratic formula for solving

a quadratic equation of the form

Ax^2 + Bx + C = 0

with the user to enter ABC

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

clc

disp([

rsquo rsquo

rsquo Calculating the solutions rsquo

rsquo of the equation Ax^2 + Bx + C = 0rsquo

rsquo rsquo

])

input(rsquoPress Enter to startrsquo)

A = input(rsquoEnter value of A in Ax^2+Bx+C rsquo)

B = input(rsquoEnter value of B in Ax^2+Bx+C rsquo)

C = input(rsquoEnter value of C in Ax^2+Bx+C rsquo)

disp(rsquoFirst we compute the discriminantrsquo)

D = B^2 - 4AC

input(rsquoPress Enter to continuersquo)

The quadratic formula gives

x1 = (-B + sqrt(D))(2A)

x2 = (-B - sqrt(D))(2A)

thezeros=sort([x1x2])

input(rsquoPress Enter to continuersquo)

Check this from a graph of the function

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 29: Programming With Scilab

B7 Script files 253

if Dlt0

a=-B(2A) b=-B(2A) w=4abs(a)

x1=a x2=a

else

a=min([x1x2]) b=max([x1x2]) w=b-a

end

x=linspace((a-w4)(b+w4)100)

y=Ax^2+Bx+C

plot(xyx10rsquorsquox20rsquorsquo)

clear x y a b w

There are several things to note about this script

(a) Echoing the instructions on the screen is turned off whenthe input function is to be used and comments arethen put onto the screen with the disp function Thismethod of displaying comments could be kept through-out the script

(b) The input function may be used to punctuate the pre-sentation so that it does not all just scroll past theviewer without his having the opportunity to read howthe computation progresses

(c) The graphing of the function involves a few considera-tions that we do not wish to trouble you with since wewant you to concentrate of the quadratic formula Thevariables used in this part of the script are erased withclearmdashbut note that if any variable in the workspaceis called a b x y or w then the result will be that it iserased

(d) If you write a similar script for solving say two equationsin two unknowns then you will see that most of the timewill be spent on perfecting the layout of the presentationrather than on the solution process

Formatted output

The semicolon at the end of a line in Scilab suppresses the displayof output from a computation but allowing the output to be dis-played in Scilabrsquos default mode is sometimes not very convenient

Scilab provides the function printf (a direct implementation ofprintf

the C function of nearly the same name) for formatted output Theform the command takes is

printf(rsquoformatrsquoAB)

The string rsquoformatrsquo describes how to display the variables ABformat

The format string contains text to be displayed plus special com-mands that describe how to display each number The specialcommands takes the general form

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 30: Programming With Scilab

254 Appendix B Programming with Scilab

[-][number1number2]C

where anything in square brackets is optional

The sign tells Scilab to interpret the following characters ascodes for formatting a variable The number1 specifies the mini-mum field width9 If the number to be printed will not fit withinthis width then the field will be expanded The number2 specifiesthe number of digits to print to the right of the decimal pointThat is the precision of the output If the precision of the variableis larger than the precision of the output field then the last digit isrounded before printing Normally the numbers printed are rightjustified the minus sign indicates that they should be left justified

The final character in the format specifier rsquoCrsquo is the format codeThis is not optional it must appear to specify what form the num-ber is to be printed Table B12 lists the most useful format codes

Example B9 Some examples of using the printf command

printf(rsquoThe speed is (kph) 31frsquoSpeed)

if Speed = 6234 this produces the output

The speed is (kph) 623

If A = 3141 and B = 6282 then the command

printf(rsquoPi=53f TwoPi=53frsquoAB)

produces the output

Pi=3141 TwoPi=6282

If M=[12 15 06 03] then the command

printf(rsquo31f rsquoM)

produces the output

12 06 15 03

The printf command prints by column when a matrix is tobe printed

Example B10 An example of the rounding that can occur whenusing printf The output from the command

printf(rsquoPi=75f Pi=64frsquopipi)

is

Pi=314159 Pi=31416

The format string can also contain ordinary text which will be out-put unchanged Escape sequences can be embedded in the format

9 this is the minimum number of characters the number will occupy includingthe decimal point and plusmn signs For example the field width of minus2345 is 6

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 31: Programming With Scilab

B7 Script files 255

Table B12 The printf format string number typesFormat code Description

f Decimal formate Exponential format with lowercase eE Exponential format with uppercase Eg e or f whichever is shorterG E or f whichever is shorter

Table B13 The printf format string escape sequencesEscape Sequence Description

n start a new line in the outputb Backspacet Tab Print a backslash Print a percentrsquorsquo Print an apostrophe

string that have special meaning Table B13 lists the most usefulescape sequences

File input and output

Variables can be defined from information that has been storedin a data file Scilab recognizes two different type of data filesmat-files and ascii-files A mat-file contains data stored in aspace-efficient binary format Only a Scilab program can readmat-files If data is to be shared with other programs then usethe ascii file type An ascii (American Standard Code for In-formation Interchange) file contains only the standard keyboardcharacters and is readable and editable on any platform using anytext editor

To save variables to a mat-file use the command save For exam-ple

save(rsquodata1matrsquoxy)

will save the matrices x and y in the file data1mat To restorethese matrices in a Scilab program use the command10

load(rsquodata1matrsquo)

This command will define the variables x and y and load them withthe values stored in the mat-file The advantage of saving data ina mat-file is that when it is loaded the variables are restored Thedisadvantage is that the file is a binary file and is only readable byScilab

10 Remember this file must be in the Scilab search path

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 32: Programming With Scilab

256 Appendix B Programming with Scilab

An ascii data file that is going to be loaded into a Scilab programmust only contain numeric information and each row of the filemust contain the same number of data values The file can begenerated using a spread sheet program a text editor or by anyother program It can also be generated by a Scilab programusing the fprintfMat command To save the variable y to anascii file called data1dat the command is

fprintfMat(rsquodata1datrsquoy)

Each row of the matrix y will be written to a separate line in thedata file The mat extension is not added to an ascii file How-ever it is good practice as illustrated here to add the extensiondat to all ascii data files so that they can be distinguished fromother Scilab file types and are easily recognisable as data files

Exercise B11 Use the Scilab help command to discover moreoptions for fprintfMat

The fscanfMat command reads an ascii file of numbers For ex-ample

x=fscanfMat(rsquodata1datrsquo)

assigns to variable x the matrix of values in the text files data1datrsquo

Example B12 If the file data3dat contains the following data

000 000

001 001255

002 02507

003 037815

The commanddata3=fscanfMat(rsquodata3datrsquo)

will create a variable data3 with 2 columns and 4 rows thatwill contain the data from the file Then typing data3 at theprompt will give

gt data3=fscanfMat(rsquodata3datrsquo)

data3 =

0 0

00100 00126

00200 02507

00300 03781

Then the columns of data in the file can be stored in the vari-ables x and y by simply doing the following x=data3(1)and y=data3(2)

Exercise B13 Create the ascii data file xyzdat containing thefollowing data

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 33: Programming With Scilab

B7 Script files 257

Table B14 Some of Scilabrsquos data inputoutput functionsFunction Description

input Request input from the keyboard Anyvalid Scilab expression is allowed in re-ply

disp Display variables in free formatfprintf Displayprint variables in a specified for-

matsave Save variables to a fileload Load data from a file

fscanfMat Load data from an ascii filefprinfMat Write ascii data to a file

000 001 002 003012 032 045 087134 121 178 147

Use the Scilab editor or a text editor of your choice

Load the data file into Scilab so that the three variables xy and z each contain a row of data from the file

Note that other more advanced commands exist in Scilab andcan be used to readwrite ascii files (see Table B14) Howeverthese are only used when a specific need arises and are thereforenot covered in detail here (see Scilab Help for more details)

B72 Formatting script files

An important aspect of writing script files is to ensure that thescript is readable and easily understood This ensures that anyonereading the script file (this includes the author of the file) canunderstand the purpose of the script

To help make the script understandable it should be commentedthroughout describing all aspects of the script In Scilab all texton a line following two characters is treated as a comment Thefirst comment line before any executable statement in a script is theline that is searched by the apropos command This line shouldapropos

contain the name of the function and keywords that help locatethe script The help command displays all the comment lines upto the first blank line or executable line that occur at the start ofa script A description of the script should be placed here 11

Lines in a script file should not be too long The lines should be

11 Note help files will only be available online in Scilab once the required xmlhelp files have been generated If you use the above structure these can begenerated from your Sci-file by running the command help from sci Foradditional details see Scilab help for this command

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 34: Programming With Scilab

258 Appendix B Programming with Scilab

visible in the editorrsquos window(printout) without wrapping or hori-zontal scrolling This applies to both comment lines and statementlines

Statements can be broken across multiple lines using the continua-tion symbol rsquorsquo three dots in a row If three dots in a row appearContinuation symbol()

at the end of a line it means that the statement is continued onthe next line

Example B14 is an example of a script file that explains how tomake various temperature conversions

Example B14

Script temperatures

Variables createdoverwritten

Tc Tf Tk Tr T_all

Purpose To illustrate the conversion of

Celsius temperatures (Tc) to

Fahrenheit (Tf) Kelvin (Tk)

and Rankine (Tr) and to produce

a table of equivalents to Tc values

running from 0 to 100 in steps of 10

Source Leigh Brookshaw Mar 15 2000

Last Modified Tony Roberts 2007

-----------------------------------------------

disp(rsquoWe create the list of Celsius valuesrsquo)

Tc = [010100] input(rsquopausersquo)

disp(rsquoCalculate the Fahrenheit equivalentsrsquo)

Tf = 9Tc5 + 32 input(rsquopausersquo)

disp(rsquoCalculate the Kelvin equivalentsrsquo)

Tk = 27316 + Tc input(rsquopausersquo)

disp(rsquoCalculate the Rankine equivalentsrsquo)

Tr = 9Tk5 input(rsquopausersquo)

disp(rsquoCreate a matrix with equivalent temperaturesrsquo)

disp(rsquoin corresponding rowsrsquo)

T_all = [Tc Tf Tk Tr] input(rsquopausersquo)

Turn echoing off as the rest is instructional

printf(rsquoTemperature Conversion Tablenrsquo)

printf(rsquo Tc Tf Tk Trnrsquo)

printf(rsquo62f 62f 62f 62fnrsquoT_allrsquo)

The print instruction works because printf

prints a row at a time

n starts a new line in the output

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 35: Programming With Scilab

B7 Script files 259

As a courtesy clear out the

introducedover-written variables

clear Tc Tf Tk Tr T_all

Exercise B15 Code the Example B14 and name the script filetemperaturessce Test that your script file is giving thecorrect answers Test the answers by calculating a few ofthe values in the output table using the Scilab commandwindow

Run your script with disp as shown then comment out thesedisplays when you are satisfied the script works

Exercise B16 The growth of bacteria in a colony can be mod-eled with the following exponential equation

ynew = yolde1386 t

where yold is the initial number of bacteria in the colonyynew is the new number of bacteria in the colony and t is theelapsed time in hours

Write a script that uses this equation to predict the numberof bacteria in the colony after 6 hours if the initial populationis 1 Print a table that shows the number of bacteria everyhalf hour up to 6 hours Also plot the answer

Exercise B17 Modify the script of Exercise B16 so that theuser enters the elapsed time in hours Use the input com-mand to ask the user for the input

Exercise B18 Modify the script of Exercise B17 so that theuser enters the initial population of the colony

Exercise B19 Carbon dating is a method for estimating the ageof organic substances such as bones wooden artifacts shellsand seeds The technique compares the amount of carbon 14a radioactive isotope of carbon contained in the object withthe amount it would have had when it was alive While livingthe object would have the same amount of carbon 14 as itssurrounding environment For the last tens of thousands ofyears the ratio of carbon 14 to ordinary carbon has remainedrelatively constant in the atmosphere this allows an estimateto be made of age based on the amount of surviving carbon14 in an object The equation is

age(years) =minus loge(carbon 14 proportion remaining)

00001216

If the proportion of carbon 14 remaining is 05 then the ageis 5700 years Which as you would expect is approximatelythe half life of Carbon 14

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 36: Programming With Scilab

260 Appendix B Programming with Scilab

Write a script that allows the user to enter the proportion ofcarbon 14 remaining Print the age in years

What happens if the user enters a proportion le 0 Whathappens if the user enters a proportion ge 1

Exercise B20 Modify the script of Exercise B19 so that theage is rounded to the nearest year

B8 Function files

While a script is intended to be either the controlling unit for anentire application or a storyboard for a minor lsquoapplicationrsquo thecomputational work the various specialised tasks that make up anapplication are done through the use of functions We have seennumerous examples of functions alreadymdashthe built-in or primi-tive functions of Scilab such as input floor and ceil thearithmetic functions + - ^ and elementary functions ofmathematics such as sin cos tan exp log But in most appli-cations there are special tasks that recur and for which it wouldbe useful to have a function Scilab permits the user to define hisown functions and to store them in separate Sci-files called functionfiles

Functions must have a particular syntax Only pre-fix notation isallowed and the first executable line of a function Sci-file must bepreceded by a line of the form

function [uvw] = Fname(xyzt)

where Fname is the unique name of the function which requires oneor more (or no) inputs xyzt and returns one of more (or no)outputs uvw The following lines of the function file list in orderthe steps to be executed on whatever particular inputs are givenin the function call (they need not be called xy ) and theoutputs can be stored under any variable names whatsoever

Unlike a script file all the variables used in a function are local tothat function This means that the values of these variables areonly used within the function and do not over-write variables in theworkspace For example if you assign the variable pi a value of 3in the algorithm for some function (the sequence of steps executedwhen the function is called) then you need not be concerned thatit might over-write the standard value of pi in the workspace Thevariables used to identify the inputs and outputs of a function arealso local to the function

If a function is called without assigning its outputs to variablesthen the first of the outputs only is displayed on the screen

Functions are the building blocks of larger programs They feedtheir results back to other functions and ultimately to the program

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 37: Programming With Scilab

B8 Function files 261

that interfaces with the user that is to a script file The inter-face tools (or functions) used by the script file may be more orless sophisticated but the hard computational work is done in thecomponent functions

The fact that variables defined within a function are local to thatfunction means that functions can be used in any program withoutfear that the variables defined within the function will clash withvariables defined in the main part of the program This also meansthe programmer need not know the contents of a function onlythe information it needs and the information it will return This isexactly the case with built-in (primitive) functionsmdashthe algorithmused is not open to the user and in fact may be proprietory infor-mation (information that might be thought to give this softwarea commercial edge over competitors) Many of the functions in asophisticated package like Mathematica fall into this category

Some important points

bull The first executable line in a function file must be preceededby a syntax line that lists all the input variables and all theoutput variables This line distinguishes a function Sci-filefrom a script Sci-file The form of the syntax line is

function [output_vars] = function_name(input_vars)

bull The output variables are enclosed in square brackets as shown

bull The input variables are enclosed with parenthesis as shown

bull A function does not have to have either input variables oroutput variables but most functions will both have inputsand deliver outputs

bull The function name should be the same as the Sci-file filenameIf the function name is Temp then the Sci-file name should beTempsce

bull Scilab is case sensitive by default but your operating sys-tem may not be For example while Scilab will recognizethat Temp and temp are two different variables your operat-ing system might not recognize that Tempsce and tempsce

are two different files

bull Functions are executed by calling the function with the cor-rect syntax in exactly the same way as built-in functions areused (that is functions such as sin ceil)

bull values needed by the function should be passed as input vari-ables to the function The use of the input command in func-tions should be avoided unless it is a user interface function

bull the last statement of the function is the last statement in theSci-file When the last statement is executed the function

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 38: Programming With Scilab

262 Appendix B Programming with Scilab

returns and execution precedes from where the function wascalled

bull the return statement can be used to force an early returnfrom a function

bull It is a good practice to place an endfunction on the lastline of a function This makes it clear to other users exactlywhere the function ends

Example B21 The following function returns the distance trav-eled and the velocity of an object that is dropped The inputvariable is the elapsed time of falling

Function fall

Syntax [dist vel] = fall(tv0)

Input t = list of elapsed times in seconds since

body began a fall under gravity from

rest with no resistance

v0 = initial speed at the start of the fall

Outputs dist = list of distances fallen in metres

from beginning of fall to times t

vel = speed in metressec at time t

Algorithm Assumes vertical fall under constant gravity

with no air or other resistance forces

Source Leigh Brookshaw 2232000

Last Modified Tony Roberts 2007

function [dist vel] = fall(tv0)

The gravitational acceleration is assumed to be

g = 98 metressecondsecond

Under constant acceleration (g) speed t is given by

vel = gt + v0

and distances travelled by

dist = 05gt^2 + v0t

endfunction

Put this text in a text file say fallsce and load intoScilab with the command exec(rsquofallscersquo) after everytime you edit the text file

The following gives examples of using this function

gt [drop velocity] = fall(50)

drop =

1225000

velocity =

49

The output variables drop and velocity are scalars thathave been assigned the return values from the function

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 39: Programming With Scilab

B8 Function files 263

gt sec = 5

gt [drop velocity] = fall(sec0)

drop =

1225000

velocity =

49

The input can be variables or explicit constants

gt secs=[15]

gt [drop velocity] = fall(secs0)

drop =

49000 196000 441000 784000 1225000

velocity =

98000 196000 294000 392000 490000

Input variable t can be a list The output variables are thenvectors of corresponding values for distance and speed (andconsequently of the same length

gt fall(50)

ans =

1225000

Here the result is not assigned to a variable Note that inthis case the only answer returned is the value of the firstvariable in the function definition namely dist This meansto get all output from a function you must assign all outputvariables

Exercise B22 Use the above function to plot (on the one graph)the distances travelled over a given number of seconds forbodies starting their falls with different speeds by applyingthe command plot(dropsecs) after each execution of thefunction

Example B23 The following code rewrites the script of Exam-ple B8 so that the roots of a quadratic are calculated withina function call

Function quadroot

Syntax [x] = quadroot(ABC)

Input A = coefficient of x^2

B = coefficient of x

C = constant coefficient

in a quadratic polynomial

Outputs x = a list of the solutions

of the equation Ax^2 + Bx + C = 0

Algorithm Uses the quadratic formula

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 40: Programming With Scilab

264 Appendix B Programming with Scilab

function [x] = quadroot(ABC)

Calculate the square root of the discriminant

disc = sqrt(B^2- 4AC)

Calculate and display the two roots

x = (-B + disc[1-1])(2A)

endfunction

Put this text in a text file say quadrootsce and load intoScilab with the command exec(rsquoquadrootscersquo) after ev-ery time you edit the text file The result of running thefunction might be stored in a variable name and passed toother functions for further use

Exercise B24 Use the function of Example B23 to assist you indeciding on the plotting window for various quadratic poly-nomials

Since functions represent often repeated tasks that may be usefulin maintaining an application they are chosen and written withsome care and are well documented In Scilab the first block ofcomments in a function can be accessed via the help commandcommand once the help files are built (see help help from sci)For more sophisticated documentation we would add keywords orphrases that might be used by a person searching for a function todo a particular task Once (s)he has found the appropriate functionname (s)he can then use help to get more detail on its use

1 The first comment line should contain the functionrsquos nameand other keyword descriptors that might help someone lo-cate this function when they have a particular task to do butdonrsquot know the name of the function that does it

2 the next line should be the syntax line showing how thisfunction is to be called

3 then the input variables should be listed with units if appli-cable

4 followed by the output variables with units if applicable

5 input and output listings should be followed (or preceded)by a description of what the function does if this is notmade clear by the description to the input and output vari-ables this statement should also include a description of thealgorithm that is used if this has any special or unusualfeaturesmdashfor example rsquoiterative solution by Jacobirsquos methodrsquoor rsquoiterative solution by GuasssndashSeidel methodrsquo

6 divide the function code into recognisable blocks such asrsquoData Checkingrsquo rsquoSpecial Casesrsquo etc by the use of commentsif appropriate and also add comments to highlight where anyspecial features are implemented Do not add inane com-ments like

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 41: Programming With Scilab

B9 Control structures 265

v= v+2 adds 2 to the value of v

but do not assume that even you will be able to follow yourown brilliant logic when you have long forgotten about howyou wrote the function let alone someone else trying to readthe code for the first time

B81 Local variables

The name of the input variables given in the function definitionline are local to that function This means that when the func-tion is called the input variables used in the call statement canhave different names All variables used in the function are clearedfrom memory after the function finishes executing The functionin Example B21 can be called using the statement

[drop velocity] = fall(sec)

The variable sec is the elapsed time in seconds but inside thefunction this is called t If inside the function the variable t

was changed it would not affect the variable sec in the callingprogram This is what is meant by the functionrsquos variables beinglocal to the function This feature means that functions can bewritten without concern that the calling program uses the samevariable names and therefore function files are portable and neednot be rewritten every time they are used in a different program

B9 Control structures

In the execution of the function control passes from one line tothe next However there are a number of situations in which itis natural to want control to pass to different lines depending onthe value of computed variables For example input data maymaybe be treated differently depending on when it is received (latepayment assignments etc)

Decisions to execute different lines of code in different circum-stances are called branching decisions and most computer lan-guages will provide a branching control structure for implementingsuch decisions Scilab provides the if then and the selectbranching control structures The tests that are made to determinethe blocks of code that should be executed often involve more thanone consideration and Scilab provides both relational and logicaloperators to simplify the expression of these conditions

Statements that alter the linear flow of the script are called controlstructures

A control structure is also required when blocks of code are to berepeated until a certain condion is met for example the computa-tion of interest on a loan balance until such time as the loan balanceis paid off or repeated approximation to the solution of a problem

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 42: Programming With Scilab

266 Appendix B Programming with Scilab

Table B15 Scilabrsquos relational operatorsRelational operator Interpretation

lt less thanlt= less than or equalgt greater thangt= greater than or equal== equal~= not equal

until sufficient accuracy is achieved The repeated execution of ablock of code may be achieved by an iterative control structure orloop Scilab provides a while loop which continues repeatingthe block until a certain condition is met and a for loop whichrepeats the block a given number of times

The flow of control may also be disrupted by a recursive functiondefinitionmdashthat is a function definition which includes a call to thefunction itself (with dfifferent inputs of course) In this case thecurrent function execution is suspended until a result is returnedfrom the within-function function call Suspension will stack uponsuspension until a within-function function call produces a resultEvery recursively defined function must ensure that after somefinite number of recursions there will be a branch to an executableline rather than to a further recursion Such functions will bevery slow in executing and while they are very useful for solvingproblems theoretically they are never as efficient as an equivalentiterative solution and we will not use them much in this course

B91 Relational operations

To be able to create branching code we need to be able to askquestions For example typical sorts of questions a code may askare

bull Is the temperature greater than 100C

bull Is the height of the building less then 700m

bull Is that a car and is itrsquos speed equal to 60 kmh

Questions that can be asked in a program only allow for two possi-ble answers True or False Scilab represents True with the valueT and False with the value F

Relational operators are operators that compare two matrices ofequal size The operator does an element by element comparisonbetween the two matrices and returns a matrix of the same size withthe elements set to T if the comparison is true and to F otherwise

An expression that contains a relational operator is a logical ex-pression because the result is a matrix containing ones and zeros

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 43: Programming With Scilab

B9 Control structures 267

Table B16 Scilabrsquos logical operatorsLogical operator Symbol

and amp

or |

not ~

that can be interpreted as true or false values respectively

Table B15 contains a list of Scilabrsquos relational operators

Example B25 Consider the following Scilab code

a = [3 4 6]

b = [3 5 1]

c = a lt b

d = a ~= b

e = a gt b

The result of this code is that the variables c d and e havethe values

c = [F T F]

d = [F T T]

e = [F F T]

B92 Logical operations

The logical expressions can be combined using the logical opera-tors The logical operators defined in Scilab are and or and notand are represented by the symbols in Table B16

Logical operators are used to combine logical statements createdusing the relational operators into more complex logical expres-sions for example

altb amp bltc

This operation is only valid if the two resultant matrices (repre-sented by altb and bltc) are the same size The entry in the matrixrepresented by this logical expression is T (true) if the values inthe corresponding entries in a b and c are such that altbltc oth-erwise the entry is F (false)

When two logical expressions are joined by or entries in the re-sulting matrix are F (false) if both expressions are false otherwiseit is T (true) If two expressions are joined by and entries in theresulting matrix are T (true) if both expressions are true other-wise it is F (false) Logical expression preceded by not reversesthe value of the relational operation For example if agtb is truethen ~(agtb) is false In this example the relational operation is

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 44: Programming With Scilab

268 Appendix B Programming with Scilab

Table B17 Precedence of operatorsOperator Precedence Order of evaluation

() 1 Left to Right Innermost first~ 2 Right to Left^ 3 Left to Right 4 Left to Right 5 Right to Left+ - 6 Left to Right

lt gt lt= gt= == ~= 7 Left to Rightamp | 8 Left to Right

surrounded by brackets to modify the default precedence See Ta-ble B17 for a list of the order of logical operations

As it does with mathematical expressions Scilab evaluates logicalexpressions are evaluated from left to write Unlike mathematicalexpressions if at any point in the calculation the logical answeris known then the rest of the logical expression is ignored Forexample if x=4 then the statement

(xgt3) |(cos(z)lt0)

must evaluated to true as the first conditional part is true Thismeans that the value of cos(z) need not be evaluated and it isnot Once a logical statement evaluates to a known result extraconditionals are ignored The statement

(xlt3) amp (exp(z)lt10e4)

is false irrespective of the value of exp(z) Scilab will not botherto check whether exp(z)lt10e4 because it is not needed

Scilabrsquos logical operators can also be applied to variables not justused with relational operations exclusively For example if the twomatrices A and B are the same size then the result of A amp B willbe a matrix with elements set to one where both A and B havenonzero elements and zeros otherwise The logical operators orand not behave similarly

Example B26 If A = [6 4 0 1] B = [0 2 6 2] then

AampB = [F T F T]

~A = [F F T F]

A|B = [T T T T]

AltBampA = [F F F T]

Due to operator precedence the last example is equivalent to(AltB)ampA

Exercise B27 Let A = [3 2 7 0] B = [4 0 3 1] C = [8 1 0 5] Without using Scilab solve the following using the prece-dence table and the definitions for the operators

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 45: Programming With Scilab

B9 Control structures 269

Table B18 Some of Scilabrsquos logical functionsFunction Description

find(x) Returns the indices of the nonzero elements ofthe vector x If x is a matrix it returns the rowand column indices of the nonzero elements

isnan(x) Returns a matrix with ones where the elementsof x are Nans zeros otherwise

isempty(x) Returns a one if x is an empty matrix zero oth-erwise

~A A | C A lt= B A+B gt C

~C+B C-4 gt B A ~= 7

Check your answers using Scilab

Exercise B28 Scilab also has many logical functions That isfunctions that return logical matrices Using Table B18 andthe Scilab help command work out the result of the fol-lowing commands Do not use Scilab to solve the problemsonly to check your answers

Let A=[3 2 7 0] B=[4 0 3 1] C=[8 1 0 5] and D=[]What is the result of

find(B) isempty(D) ~isempty(A) find(AgtB)

B93 Branch controls (conditional statements)

The if statement

The if statement is the most widely used conditional statementThe form of a simple if statement is

if logical expressionstatement group

end

If the logical expression is true the statements between the if

statement and the end statement are executed If the logical ex-pression is false then Scilab immediately jumps to the statementfollowing the end statement

It is important to indent the statements within an if structure inorder to see the control flow easily

Example B29 One important use of an if statement is to en-sure that only valid parameters are passed to functions

if x gt 0

y = log(x)

end

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 46: Programming With Scilab

270 Appendix B Programming with Scilab

if (x gt= -1) amp (x lt= 1)

y = acos(x)180pi

end

If statements can be nested when required For example

if logical expression 1

statement group Aif logical expression 2

statement group Bend

statement group Cend

statement group D

Example B30 The following function extends the code of Ex-ample B23 to allow the coefficients of a number of quadraticswith real coefficients to be entered at once and to return notonly the zeros but also the vertices of the parabolas they rep-resent Checks are made for error conditions For exampleThe coefficient of the x2 term cannot be zero All coefficientvectors must be the same length

Function quadroots

Syntax [x v M] = quadroots(ABC)

Input A = coefficients of x^2

B = coefficients of x

C = constant coefficients

in the quadratic polynomials

Outputs x = the solutions of Ax^2 + Bx + C = 0

v = the vertex coordinates

both returned as 2 column matrices

with one row for the results

for each quadratic

M = the original coefficients returned

in the form of a matrix with one row

for each quadratic

Source Leigh Brookshaw 1532000

Last Modified Tony Roberts 2007

function [x v] = quadroots(ABC)

If function fails output is empty

x = [] v = []

Data checking

Check that all the coefficients have the same length

if (length(A) ~= length(B)) | (length(B) ~= length(C))

error(rsquoNot all coefficient arrays are of equal lengthrsquo)

end

Check that all the coefficients are real Tests such as

these are madein case the coefficients have been passed

to this function from some other computation

if ~isreal(A)

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 47: Programming With Scilab

B9 Control structures 271

error(rsquoNot all elements of A are realrsquo)

end

if ~isreal(B)

error(rsquoNot all elements of B are realrsquo)

end

if ~isreal(C)

error(rsquoNot all elements of C are realrsquo)

end

Check that no value of A is zero

if find(A==0)

error(rsquoNo elements of A are allowed to be zerorsquo)

end

Computing the Output

M = [ABC]rsquo the coefficients in a matrix

xs = -B(2A) vertex abscissae

ords = Axs^2 + Bxs + C ordinates of vertices

v = [xsords]rsquo vertex coordinates

disc = BB - 4AC the value of the discriminant

x = ([xsxs]+([1-1]rsquosqrt(disc))[(2A)(2A)])rsquo zeros

endfunction

The if-else statement

The else clause added to an if statement means that two blocksof code can be specified One to be executed if the the logicalexpression is true the other if it is false For example

if logical expression

statement group Aelse

statement group Bend

If the logical expression is true then statement group A is exe-cuted If the logical expression is false then statement group Bis executed The statement groups can also contain if andorif-else statements to provide a nested structure

Example B31 The velocity of a cable car between two towersAssume that the scalar r is the distance from the nearesttower If the cable car is within 30 metres of the tower thevelocity is calculated using the equation velocity = 0425 +000175 times r2 If the cable car is further away from thetower the velocity is calculated using the equation velocity =0625+ 012times rminus 000025times r2

The correct velocity is calculated with the statements

if r lt= 30

velocity = 0425 + 000175r^2

else

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 48: Programming With Scilab

272 Appendix B Programming with Scilab

velocity = 0625 + 012r - 000025r^2

end

Notice that control structures can be executed in the inter-active environment besides being used within functions

The if-elseif-else statement

When several levels of if-else statements are nested it may bedifficult to determine which logical expressions must be true (orfalse) to execute each set of statements In this case the elseif

clause is often used to clarify the program logic

The else and elseif clauses are optional in an if statement Thegeneral form of the if statement is

if logical expression 1

statement group Aelseif logical expression 2

statement group Belseif logical expression 3

statement group C

else

statement group Dend

If logical expression 1 is true then only statement group A is ex-ecuted If logical expression 1 is false and logical expression 2is true then only statement group B is executed If logical ex-pressions 1 and 2 are false and logical expression 3 is true thenstatement group C is executed If none of the logical expressionsare true then statement group D is executed If more than onelogical expression is true the first logical expression that is truedetermines which statement group is executed

The select statement

The select statement provides an alternative to a if-elseif-elseconstruct Though anything programmed using a select state-ment can be programmed using an if structure often the code ismore readable using the former

The structure of the switch statement is

switch input expression

case value 1 then

statement group Acase value 2 then

statement group B

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 49: Programming With Scilab

B9 Control structures 273

else

statement group Dend

The input expression of the select statement must evaluate to ascalar or a string The value of the input expression is compared toeach case value If a match is found then the statements followingthe case statement are executed

At most only one case statement group is executed then executionresumes with the statement after the end statement

If no case statement matches the input expression then the state-ments following the else statement are executed The else state-ment is optional

Below is an example of a case statement where the select variabledirection contains a character string (remember that convstr(arsquolrsquo)is a Scilab primitive function that takes a text as input and re-turns it all in lower case)

select constr(directionrsquolrsquo)

case rsquonorthrsquo then

angle = 0

disp(rsquoDirection Northrsquo)

case rsquosouthrsquo then

angle = pi

disp(rsquoDirection Southrsquo)

case rsquoeastrsquo then

angle = 05pi

disp(rsquoDirection Eastrsquo)

case rsquowestrsquo then

angle = 15pi

disp(rsquoDirection Westrsquo)

else

angle = nan

disp(rsquoDirection Unknownrsquo)

end

B94 Iteration controls (explicit loops)

Scilab contains two constructs for explicitly looping the for state-ment and the while statement The for statement is used whenthe number of times the block of code must be looped over is knownThe while statement is used when the number of times the blockof code must be looped over is unknown The looping is terminatedwhen a specified condition is satisfied

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 50: Programming With Scilab

274 Appendix B Programming with Scilab

The for statement

The general form of the for statement in Scilab is as follows

for index = expression matrix

statement groupend

The statements in the statement group are repeated as many timesas there are columns in the expression matrix (which could also bea scalar or a vector) Each time through the loop the index hasthe value of one of the columns in the expression matrix

Some examples of the for statement

bull calculating the factorial of 20

factorial = 1

for i=220

factorial = factoriali

end

Although this computation is far better done by simply prod(120)

bull Multiply the elements of an array

product = 1

A = [6 8 9 10 2 -5 1 7]

for i=A

product = producti

end

This is also much better done by prod(A)

The rules for a for loop are the following

bull The index of the for loop must be a variable

bull If the expression matrix is the empty matrix the loop willnot be executed Control will pass to the first statementfollowing the end statement

bull If the expression matrix is a scalar then the for loop willbe executed once only The index variable will contain thevalue of the scalar

bull If the expression matrix is a row vector then each timethrough the loop the index will contain the next value inthe the vector

bull If the expression matrix is a matrix then each time throughthe loop the index will contain the next column in the thematrix

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 51: Programming With Scilab

B9 Control structures 275

bull On exiting the for loop the index contains the last valueused

bull The colon operator can be used to define the expression ma-trix The syntax is

for index=initialincrementlimit

The number of times the loop will be executed can be calcu-lated from the equation

floor

[limitminus initial

increment

]+ 1

If this value is negative the loop is not executed If incrementis omitted it is assumed to be one

bull Lastly and the most important rule of all a for loop mustnever never ever be the innermost loop in a computationThe innermost loop must always always always be a naturalvectormatrix command Two examples are the two exam-ples given above the for loop to compute a product mustbe replaced by the prod function See further discussion inSection B95

Example B32 Suppose the cable car distance from the pylon rof Example B31 is a vector Then Example B31 will haveto modified to calculate a vector of velocities

Initialize the velocity array to same size as rsquorrsquo

velocity = zeros(r)

Loop over the distance array and calculate velocities

for k = 1length(r)

if r(k) lt= 30

velocity(k) = 0425 + 000175r(k)^2

else

velocity(k) = 0625 + 012r(k) - 000025r(k)^2

end

end

However the above code has a for loop as the innermost loopand so violates the last criterion above Rewrite it using nat-ural matrixvector modes of computation After initialisingthe velocity to a correct size matrix simply

k=find(rlt=30)

velocity(k) = 0425+000175r(k)^2

k=find(rgt30)

velocity(k) = 0625+012r(k)-000025r(k)^2

Use the for loop only when the inside of the loop is lesstrivial

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 52: Programming With Scilab

276 Appendix B Programming with Scilab

The while statement

The while loop is a structure for repeating a set of statements aslong as a specified condition is true The general form of the whileloop is

while expression

statement group

end

If the expression is true or all elements nonzero then the statementgroup is executed The expression is normally a logical expressionAfter the statements are executed the condition is re-tested If thecondition is still true the group of statements are executed againWhen the condition is false control jumps to the first statementfollowing the end statement If the expression is always true (or isa value that is nonzero) the loop becomes an infinite loop

Example B33

To sum the positive elements of the vector x

use the rsquolengthrsquo command to find the

number of elements in x

sum = 0 k = 1

while (k lt= length(x)) amp (x(k) gt= 0)

sum = sum + x(k)

k = k + 1

end

Of course again this violates our last criteria Instead inpractise code simply

sumx=sum(x(find(xgt=0)))

Use while loops when the computation inside the loop is notso simple

Exercise B34 Write a function containing the code of Exam-ple B33 Test the function and also modify it so that thecondition statement of the while loop is reversed that is

while (x(k) gt= 0) amp (k lt= length(x))

Now test the function again Explain why is there now anerror in the script

A danger of while loops is that they may never terminate Thisobviously occurs if the condition is always true A loop countercan be added to the condition to ensure that the loop terminatesFor example in the code below the termination condition we areinterested in is (agt=0) this is assumed to occur within 100 loops if

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 53: Programming With Scilab

B9 Control structures 277

it does not then an error has occurred The variable count ensuresthe loop will not be infinite

count = 1

while (a lt 0)

count = count + 1

if count gt 100

error(rsquoLoop failed to terminatersquo)

end

end

To break out of an infinite loop and terminate execution of a scriptor function you can press Control C on the keyboard That ishold down the Ctrl key and press C simultaneously

Exercise B35 Timber management needs to determine howmuch of an area to leave uncut so that the harvested areais re-forested in a certain period of time Assume that thereforestation takes place at a known rate per year dependingon climate and soil conditions If the reforestation rate is ηthen the reforestation equation is (Forested area this year) =(Forested area last year) times (1 + η) Assume that there are11000 hectares total with 4500 hectares uncut and the re-forestation rate is 003 hectaresyear Write a function thatreturns a reforestation vector with the followinghelp lines inits definition

Function reforest

Syntax hectares = reforest(years rfrate inhec)

Input

years - the number of years to calculate

the reforestation

rfrate - the reforestation rate in hectaresyear

inhec - the initial forest area in hectares

Output

hectares - a vector that lists the forest area

in hectares for each year The length

of the vector is the same as the

number of years input parameter

function hectares = reforest(years rfrate inhec)

Exercise B36 Write a script to print a table showing the num-ber of hectares re-forested at the end of each year after askingthe user to enter the number of years to be used in the table

Exercise B37 Modify the program of Exercise B35 so that theuser can enter the number of hectares and the program willdetermine how many years are required for the number ofhectares to be re-forested

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 54: Programming With Scilab

278 Appendix B Programming with Scilab

The break statement

Use the break statement to break out of a for loop or a while

loop before it has completed This statement is useful if an errorcondition is detected within the loop This statement is also use-ful for terminating an iteration when the desired result has beencomputed The loop is terminated at the point where the break

command is executed

B95 Implicit loops

If you are familiar with more traditional programming languagessuch as fortran basic or C the discussion on looping above willbe familiar The for and while looping discussed has its coun-terparts in many languages However since Scilab was designedto make matrix manipulations easy one would not expect to haveto use loops to implement operations like matrix multiplication orvector addition but to find them encapsulated in primitive func-tions It turns out that these primitives find surprising uses andthat in many situations where a classical scalar language needsloops to complete a calculation array processing primitives handlethe computation without any apparent looping

See Examples B32 and B33

These codes use the find function to create a vector k that con-tains the indices of all the elements in x that are greater than zeroFor example consider a vector x that is defined as follows

x = 7minus3 2 4minus5minus6

The command k=find(xgt0) returns the following

gt k=find(xgt0)

k =

1 3 4

This means that elements x1 x3 and x4 are the only positive valuesin vector x

In the second line the statement xp=x(k) is a vector that onlycontains the positive elements of x For our example we should geta vector contain the elements x1 x3 and x4 of x Thus xp shouldcontain the values 13 and 4 (see output below to verify this)

gt xp=x(k)

xp =

7 2 4

The Scilab function sum simple sums all of the elements of thisvector (see output below)

gt sumx=sum(xp)

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 55: Programming With Scilab

B9 Control structures 279

sumx =

13

Scilab was designed to process matrix operations rapidly Themore traditional for and while loops have to be interpreted whichtakes an enormous amount of time Implied loops utilize speciallydesigned operators within Scilab This means the processing isextremely rapid An implied loop in Scilab executes up to ahundred times faster than the equivalent explicit for or while

loop

A disadvantage of the implied loop is that Scilab code can becometerse and hard to understand If you develop your skill in thinkingin vector matrix and array terms then this brevity will soon appearas elegance of expression and the scalar version will seem clumsyand pedestrian You should make every effort to think in theseterms as it constitutes rsquoparallel processingrsquo at the software level

B96 Using functions and scripts together

As a mini-application a script can be used as a driver for a par-ticular function As such it can interrogate a user for the requiredinputs and make the function call with the correct syntax This useis particularly attractive when the syntax for a function is rathertedious to find or remember Because of the danger of over-writingworkspace variables when one uses a script if scripts are going tobe used in this way to drive functions then it is a wise practice toeither give the variables long and unlikely names or as the first in-teraction with the user to check that the names used can be safelyover-written For example in a workspace for calculus computa-tions the names d and S might very well be used for functions thatcompute differences between list elements and sequences of partialsums of series Such names will be very convenient in that settingso that one could write for example d(y)d(x) for derivativeapproximations and S(yd(x)) for approximations to the inte-gral (as we shall do in other modules of this course) Of coursethese simple single character names are in grave danger of beingover-written by careless assignments in the interactive session or ascript

Exercise B38 A small rocket is being designed to make windshear measurements in the atmosphere Before testing be-gins the designers have developed a model of the rocketrsquostrajectory The height in metres above the ground at time tin seconds is

height (metres) = 20+ 213 t2 minus 00013 t4 + 0000034 t4751

Write a function that takes the time in seconds and returnsthe height It should return a vector of heights when the timeis given as a vector

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 56: Programming With Scilab

280 Appendix B Programming with Scilab

Write a driver script to run your function

Exercise B39 Using the function from Exercise B38 write ascript to compute the height of the rocket from t = 0 to thetime it hits the ground Use increments of one second Ifthe rocket has not hit the ground after 80 seconds stop theprogram and print out an error message Have the scriptprint out a table of times and heights of a size determine bythe user and on request plot the results

Exercise B40 Using the function from Exercise B38 write aprogram to compute the time at which the rocket reaches thehighest part of its trajectory and the time at which it impactsthe earth Both should be accurate to one second

B10 Numerical programming

B101 Modular Programs

Any problem that can be solved by a computational program canbe solved in one monolithic program contained within one file Infact since a program is just a string of bits we could convert thisbit string into a number to base 10 and present this single numberas an solution to the problem This is not particularly helpful ifyou have the job of maintaining the program (that is modifying itto meet current needs)

There are a number of reasons for avoiding a monolithic program

bull the project as a whole and it could be a large one has to beunderstood in its entirety to write a monolithic program Ifit is not understood in its entirety then many rewrites willbe necessary to incorporate all aspects of the project

bull large cumbersome files are difficult to work with

bull large monolithic programs are difficult to understand for theauthor and anyone else

Sensible programming attempts to identify the key operations re-quired to solve the problem and the tools that will help in puttingthe solution together These tasks are of course solved by runningfunctions The basic rule about functions is that each functionshould perform one task and one task only The project analy-sis should be task oriented each task coded and tested separatelyThe main program pulls together these disparate pieces with ascript that mainly contains calls to functions The advantage ofthis approach is

bull many programmers can work on the problem simultaneously

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 57: Programming With Scilab

B10 Numerical programming 281

bull a monolithic project is broken down into smaller manageablechunks

bull if each function performs one task then the final code is easierto read and understand

bull it is easier to work with smaller files

Functions themselves should also be written in a block like man-ner That is similar tasks should appear together in the functionInitialization of all variables should appear together at the start ofthe function all checks on input variables should appear togetherFor example

1 Help comments name and keywords syntax inputs and out-puts

2 function [output variables] = fname(input variables)

3 Test that the input variables are valid

4 Initialize all variables that need it

5 Load any data that might be needed

6 Computational algorithm for function

The above is an outline for the design of a function Particularcircumstances will dictate the design of any individual functionbut the steps above should be borne in mind whenever a functionis written

B102 Debugging

Debugging a program is the process of finding and removing thebugs or errors Such errors usually fall into one of the followingcategories

bull Syntax errors such as omitting a parenthesis or comma orspelling a command name incorrectly Scilab usually detectsthe more obvious errors and displays a message describing theerror and its location

bull Runtime errors occur while the program is running and fallinto a number of categories

ndash Errors due to incorrect logic They do not necessarilyoccur every time the program is executed the occur-rence may depend on the type of input data A commonexample is division by zero A logic error is caused bythe author not anticipating all possible eventualities

ndash Errors due to incorrect method This can be a very sub-tle error recognising that the numerical method beingused is incorrect for the problem being solved Normallythis can only be fixed by rewriting the program using a

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging
Page 58: Programming With Scilab

282 Appendix B Programming with Scilab

better method for the problem Unfortunately this er-ror might only be recognised after an immense amountof effort has been expended writing the program It isimportant when deciding on which numerical methodto use to solve a problem that the limitations of themethod are well understood

The Scilab error messages usually allow you to find syntax errorsHowever runtime errors are more difficult to locate and are moredifficult to spot It is important to check all answers produced byprograms Never trust the answer from a program Some teststhat should always be employed with computer solutions are

bull always check the order of magnitude of the solution Is itreasonable

bull if the solution has units check that the order of magnitudeof the solution is reasonable for those units

bull plot the answers and see if the plot looks reasonable

If you have tested the solution and think there is an error then tolocate the error try the following

bull Always test your program with a simple version of the prob-lem whose answer can be checked by hand calculations Ifyour program uses functions test the functions individuallyby writing test scripts for each function

bull Display any intermediate calculations by removing semicolonsat the end of statements

bull Use the Sci-file Debugger The Scilab Debugger is a set ofcommands that allow you to stop a script during executionand examine or modify variables

  • Programming with Scilab
    • Introduction
    • Getting started with Scilab
    • Variables
    • Arithmetic expressions
      • Precedence
      • Matrix arithmetic
      • Array arithmetic
        • Builtndashin functions
          • Arithmetic functions
          • Utility functions
            • Visualising data in Scilab
              • Plotting mathematical functions from within Scilab
              • Adding titleslabels and legends to the plot
              • Plotting numeric data stored in an ASCII file
                • Script files
                  • Script input and output
                  • Formatting script files
                    • Function files
                      • Local variables
                        • Control structures
                          • Relational operations
                          • Logical operations
                          • Branch controls (conditional statements)
                          • Iteration controls (explicit loops)
                          • Implicit loops
                          • Using functions and scripts together
                            • Numerical programming
                              • Modular Programs
                              • Debugging