INTRODUCTION TO SCILAB For Scientists and ...

16 downloads 30578 Views 2MB Size Report
Aug 8, 2016 - In this way Scilab is now being developed for developers who would .... 5.5.2 console” presents the command line where cursor is shaped as −− >. ...... ios. Like an object can oscillate and move in curved fashion at the same.
INTRODUCTION TO SCILAB For Scientists and Engineers

By: Sandeep Nagar www.bookmuft.com

www.bookmuft.com

2

Dr. Sandeep Nagar [email protected]

Introduction to Scilab For Scientists and Engineers Dr. Sandeep Nagar Monday 8th August, 2016

www.bookmuft.com

Dr. Sandeep Nagar [email protected]

License information License type: Attribution-NonCommercial-ShareAlike 4.0 International License Present book is presented under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license under which: You are free to: Share — copy and redistribute the material in any medium or format Adapt — remix, transform, and build upon the material More information at http://creativecommons.org/ licenses/by-nc-sa/4.0/

2

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Dedicated to two beautiful ladies in my life, Rashmi and Aliya

3

www.bookmuft.com

4

Dr. Sandeep Nagar [email protected]

Contents

1 Introduction to Scilab 1.1 Introduction to numerical computing . . 1.2 Various alternatives . . . . . . . . . . . 1.3 Installation . . . . . . . . . . . . . . . . 1.4 Workspace . . . . . . . . . . . . . . . . . 1.5 Working with Scilab . . . . . . . . . . . 1.6 First example: Hello World! . . . . . . . 1.6.1 Calculator . . . . . . . . . . . . . 1.7 Variable browser window . . . . . . . . . 1.8 Clearing . . . . . . . . . . . . . . . . . . 1.8.1 Clearing screen . . . . . . . . . . 1.8.2 Clearing Variables . . . . . . . . 1.9 Comments . . . . . . . . . . . . . . . . . 1.10 Seeking help . . . . . . . . . . . . . . . . 1.11 Predefined constants . . . . . . . . . . . 1.11.1 Common mathematical functions 1.12 Variable . . . . . . . . . . . . . . . . . . 1.12.1 Assignment operator = . . . . . 1.12.2 Data types . . . . . . . . . . . . 1.12.3 Naming conventions for variables 1.12.4 List of variables . . . . . . . . . . 1.12.5 Global and Local Variables . . . 1.13 Complex numbers . . . . . . . . . . . . 5

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

9 9 10 11 12 14 14 15 16 16 16 17 18 18 18 20 21 21 23 27 27 27 28

www.bookmuft.com

Dr. Sandeep Nagar [email protected]

1.13.1 Real and imaginary parts . . . . . . . . . . . 1.13.2 Complex conjugate . . . . . . . . . . . . . . . 1.13.3 imult . . . . . . . . . . . . . . . . . . . . . . . 1.13.4 Checking if variable has complex components 1.14 Summary . . . . . . . . . . . . . . . . . . . . . . . . 2 Working with Arrays 2.1 Introduction . . . . . . . . . . . . . . . . . . 2.2 Arrays and vectors . . . . . . . . . . . . . . 2.3 Operations on arrays and vectors . . . . . . 2.3.1 Magnitude of a vector . . . . . . . . 2.3.2 Random matrix . . . . . . . . . . . . 2.3.3 Indexing . . . . . . . . . . . . . . . . 2.3.4 Using indices to make new vector . . 2.3.5 Slicing . . . . . . . . . . . . . . . . . 2.4 Automatic generation of vectors . . . . . . . 2.4.1 Linearly spaced vector . . . . . . . . 2.4.2 logarithmically space vector . . . . . 2.4.3 Meshgrid . . . . . . . . . . . . . . . 2.4.4 Ndgrid . . . . . . . . . . . . . . . . . 2.5 Matrix manipulations . . . . . . . . . . . . 2.5.1 scalar operation with a matrix . . . 2.5.2 Reshaping a matrix . . . . . . . . . 2.6 Special matrices . . . . . . . . . . . . . . . 2.6.1 Upper and Lower triangular matrix 2.6.2 Ones and zeros matrix . . . . . . . . 2.6.3 Diagonal matrices . . . . . . . . . . 2.6.4 special matrices . . . . . . . . . . . . 2.7 Mathematical matrix operation . . . . . . . 2.7.1 dot product . . . . . . . . . . . . . . 2.7.2 cross product . . . . . . . . . . . . . 2.8 Discrete mathematics . . . . . . . . . . . . 2.9 Summary . . . . . . . . . . . . . . . . . . . 3 Plotting 3.1 Introduction . . . . . . . . . . . . . . . 3.2 2D plotting . . . . . . . . . . . . . . . 3.2.1 plot(x,y) . . . . . . . . . . . . . 3.2.2 plot2d,plot2d2,plot2d3,plot2d4 3.2.3 polarplot . . . . . . . . . . . . 6

. . . . .

. . . . .

. . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

29 29 30 31 31

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . .

33 33 34 36 38 39 40 41 41 42 43 43 43 44 44 44 45 45 45 46 46 47 47 48 48 48 51

. . . . .

53 53 54 54 56 59

. . . . .

. . . . .

. . . . .

. . . . .

Dr. Sandeep Nagar [email protected] 3.3

3.4

3.5 3.6

3.7

www.bookmuft.com

Special plots . . . . . . . . . . . . . . . 3.3.1 Histograms . . . . . . . . . . . . 3.3.2 Matplot . . . . . . . . . . . . . . 3.3.3 grayplot . . . . . . . . . . . . . . 3.3.4 champ . . . . . . . . . . . . . . . 3.3.5 Contour maps . . . . . . . . . . . 2D Animation . . . . . . . . . . . . . . . 3.4.1 comet . . . . . . . . . . . . . . . 3.4.2 paramfplot2d . . . . . . . . . . . Plotting multiple plots in same graph . 3.5.1 Plotting multiple plots separately 3D plots . . . . . . . . . . . . . . . . . . 3.6.1 plot3d . . . . . . . . . . . . . . . 3.6.2 plot3d1 . . . . . . . . . . . . . . 3.6.3 plot3d2 . . . . . . . . . . . . . . 3.6.4 plot3d3 . . . . . . . . . . . . . . 3.6.5 surface plots . . . . . . . . . . . 3.6.6 Mesh plots . . . . . . . . . . . . 3.6.7 3D histogram . . . . . . . . . . . Summary . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

60 60 62 62 63 66 69 69 70 71 72 74 74 75 76 77 78 80 80 82 83 83 84 84 85 86 90

4 Data through File reading and writing 4.1 Introduction . . . . . . . . . . . . . . . 4.2 File operations . . . . . . . . . . . . . 4.2.1 Users . . . . . . . . . . . . . . 4.2.2 File Path . . . . . . . . . . . . 4.2.3 Creating files and saving them 4.3 Summary . . . . . . . . . . . . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

5 Functions and loops 5.1 Introduction . . . . . . 5.2 Loops . . . . . . . . . 5.2.1 while . . . . . . 5.2.2 Infinite loops . 5.2.3 for . . . . . . . 5.2.4 if-elseif-else . . 5.3 Functions . . . . . . . 5.3.1 Inline functions 5.4 Summary . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

93 . 93 . 94 . 94 . 95 . 96 . 97 . 98 . 101 . 102

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

7

Dr. Sandeep Nagar [email protected]

www.bookmuft.com 6 Numerical Computing formalism 6.1 Introduction . . . . . . . . . . . . 6.2 Physical problems . . . . . . . . 6.3 Defining a model . . . . . . . . . 6.4 Scilab Packages . . . . . . . . . . 6.4.1 Searching a package . . . 6.4.2 Installing a package . . . 6.4.3 Removing a package . . . 6.4.4 Listing packages . . . . . 6.5 XCOS . . . . . . . . . . . . . . . 6.6 Summary . . . . . . . . . . . . .

8

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

103 . 103 . 104 . 104 . 107 . 107 . 108 . 108 . 108 . 109 . 109

1 Introduction to Scilab

1.1

Introduction to numerical computing

With the advent of computers in post world war II era, desire to simulate all physical problems led to the invention of numerical computing. Whereas analytical computation required only pen, paper and human mind, numerical computation required a calculating device, or a computer. Successful implementation of computing device to solve problems (especially involving repeated tasks) over large array of data points was observed in many fields of science and engineering. For example, breaking enemy’s secret codes, simulating nuclear reactions before nuclear explosions etc. The scope further expanded for civilian purposes. Designing and simulating water ways, dams, electric power stations, town planning etc. are just few areas of engineering where similar techniques were utilized. All these applications need to solve an equation or system of equation for a physical model representing a physical problem. There are two ways in which one can approach to solve these equations namely, analytical and numerical techniques. We shall concentrate only on numerical methods of solving equations in present book. 9

www.bookmuft.com

Dr. Sandeep Nagar [email protected]

As time progressed, various schemes to define analytical functions like differentiation, integration, trigonometric etc. were written for digital computers. This involved their digitization, which certainly introduces some errors. Knowledge of error introduced and its proper nullification could yielded valuable information quicker than analytical results. Thus it became one of the most actively researched field of science and continues to be the one till date. Search for faster and accurate algorithms continues to drive innovation in the field of numerical computing and enables humanity to simulate otherwise impossible tasks.

1.2

Various alternatives

A number of alternatives exist to perform numerical computation. Programming languages written to handle mathematical functions like FORTRAN, C, python, Java to name a few, can be used to write algorithms for numerical computation. There exists a set of specialized softwares like R M AT LAB , Scilab, Mathematica etc. Their rich libraries now run in many R GBs of data. Amongst them, M AT LAB became tremendously popular among scientific community since 1984. Cheap availability of digital computing resources propelled its usage in industry and academia to such an R extent that virtually every lab needed M AT LAB . Whereas it wasn’t very expensive for relatively rich western world, it proved to a costly piece of software for rest of the world, particularly third world countries. This part of world, which has otherwise a rich pool of scientific community, needed an R open sourced alternative to M AT LAB . The solutions came in the form of Octave and Scilab. Whereas Scilab is extremely powerful, it was not deR signed exactly on the lines of M AT LAB syntax-wise. On the other hand R

Octave was developed so that M AT LAB ’s .m files could directly run on octave. In this way Scilab is now being developed for developers who would like to shift thier work to an open source platform like Scilab completely R and do not mind editing thier M AT LAB if required. R When compared to M AT LAB package including specialized packages for various engineering domains and simulink for graphical programming paradigm, octave presents a limited variety of solutions. It included almost R all functions included in M AT LAB ’s basic package and some specialized packages.But it does not provided simulink’s equivalent. Scilab proves to a complete alternative in this sense. Scilab’s XCOS provides simulink’s equivalent and specialized packages of Scilab can rival the packages provided

10

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

R ’s functionalities. Present book will introduce their basic by M AT LAB usage.

Other alternatives include programming languages like python, C, C++, Java etc. They have their own merits and demerits and hence reader is advised to judge their choice based on their needs. Scilab is a good choice to prototyping the problem quickly and checking the results. Other alternatives prove better while working with web-based data collection, analysis and visualization. Scilab is a high-level language, primarily intended for numerical computations and has a rich library of tools for solving numerical linear algebra problems, finding the roots of non-linear equations, integrating ordinary functions, manipulating polynomials, and solving ordinary as well as partial differential and differential-algebraic equations. This makes it suitable for most of the basic numerical computational work.

1.3

Installation

Scilab is open source software distributed under CeCILL license (http: //www.cecill.info/index.en.html) which is a version of GNU-GPL compatible licenses for free software. Please note that following instructions are valid for Scilab, version 5.5.2 only. It can be downloaded from the url http://www.scilab.org/ as per the choice of operating system. Installation is quite straight forward and user forums or simple Google search yields useful answers to common problems encountered by users. Scilab includes a GUI based console for easy user interface. The on-line implementation of software is available at http://scilab. in/. Here, user does not need to install the software on their own system. They need to connect to a remote server using a web-browser and can run Scilab program is similar fashion as in a local installation. Users are encouraged to test this facility too. For the purpose of present book, we shall recommend a local installation and work in the same. After proper installation at a windows OS, a Scilab icon can be observed amongst list of installed programs. Double clicking the same will open a Scilab Session. Same is true for Mac OSX. For Linux based OS distributions, one can choose either to click a desktop icon or simply write scilab at command line. 11

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

1.4

Workspace

Figure 1.1 presents a screen-shot of installed Scilab version 5.5.2. One can observe three partitions in the main windows namely: • File browser • Scilab 5.5.2 console • Variable Browser All three partitions have options of un-docking (separating from main window and opening it was a separate window) and closing as per requirements. It is recommended that users should keep all three partitions open for now as first time users can observe the computation and their results in an interactive way.

Figure 1.1: Scilab-Screenshot

To check if installation is done for a proper version as selected for download, one can write a simple command ver at scilab command prompt (at Scilab 5.5.2 console window). The following output is displayed at the time of writing this book: 1 2

−−>v e r ans =

3

12

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

4 5

column 1

6 7 8 9 10 11 12 13 14 15 16 17

! Scilab Version : ! ! O p e r a t i n g System : ! ! Java v e r s i o n : ! ! Java runtime i n f o r m a t i o n : ! ! Java V i r t u a l Machine i n f o r m a t i o n : ! ! Vendor s p e c i f i c a t i o n :

! ! ! ! ! ! ! ! ! ! !

18 19

column 2

20 21

22

23

24

25

26

27

28

29

30

31

!5.5.2.1427793548 ! ! ! ! Windows 8 6 . 2 ! ! ! ! 1 . 6 . 0 41 ! ! ! ! Java (TM) SE Runtime Environment ( b u i l d 1 . 6 . 0 41−b02 ) ! ! ! ! Java HotSpot (TM) 64− B i t S e r v e r VM ( b u i l d 20.14 − b01 , mixed mode ) ! ! ! ! Sun M i c r o s y s t e m s I n c . !

The above information shows that Scilab version is 5.5.2.1427793548 on OS Windows version 8.6.2 etc. 13

www.bookmuft.com

1.5

Dr. Sandeep Nagar [email protected]

Working with Scilab

There are two ways to work within Scilab. First one is to work at command line by writing one command at a time. The partition titled ”Scilab 5.5.2 console” presents the command line where cursor is shaped as −− >. One can write commands here for immediate execution. Second method is to write a script i.e. a set of multiple commands as a file. Scilab provides two kinds of script files. Two formats .sci and .sce differentiates them explicitly. .sci files contains Scilab and/or user defined functions. The execution of such a file simply loads them in Scilab environment but does not executes them. On the other hand .sce files contains both Scilab functions and executable commands and when this file is called, it is executed. The usually conventions of naming the files are followed i.e. the first letter should not be a special character or a numeric value and file names are case sensitive. Keywords should be avoided while naming files. Its is also recommended that user should work in a single folder for a particular project. The advantage of this approach is that to run programs, instead of full path of the file, one only needs to write the name of program. Also it is easier to share the codes for executions because paths will differ if different computers.

1.6

First example: Hello World!

One can write the first program printing the string ”Hello world!” by simply typing the following at command prompt: 1 2

−−>d i s p ( ’ h e l l o world ! ’ ) h e l l o world !

The in-built Scilab function disp() displays a string (”Hello World!”) on the command prompt, which is printed immediately below the command. Alternatively, one can store this command in an file namely hello.sce and run this file by writing exec(hello.sce). One needs to open the editor for this purpose. Editor in Scilab 5.5 is called SciNotes. One can either open it using the icon provided at top left corner of menu card, or one can simply write edit hello.sce at the command prompt. A new window pops up where user can write the code and save it as hello.sce. If one does not 14

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

define the format of file as .sce, Scilab gives the format .sci since it treats the file as a Scilab function. User can simply write a one line code in the file hello.sce as given below. 1

d i s p ( ” h e l l o world ! ” )

hello.sce In this case, the command(s) written in program are fed to command prompt one by one and executed. One can also run a command using play button provided at the window for editor. When a program is played only the outputs are displayed. Scilab command prompt is represented by the symbol ”-->” by default. Scilab is an interpreted language with dynamically typed objects. This implies that after entering a command at the command prompt, if enter key is pressed on keyboard, the command is executed. One can write the code one line at a time and execute the same. The code executes well untill an error is presented. One way to learn Scilab is to run demonstration programs. Click on ? symbol in the list of menu present at top of main wondow. Choose ”Demonstrations” and click ”Introduction: Getting started with scilab”. Choose appropriate topic to learn the same. This approach would require the user to structure his/her learning experience themselves. This is not recommended for first time user. Present book will help in this aspect as the learning structure has been devised for first-time user.

1.6.1

Calculator

In simplest view, Scilab works as a calculator with mathematical operators like multiplication (symbol is *), division (symbol is /), addition (symbol is +), substraction (symbol is -) and exponentiation(symbol is ^): 1 2 3 4 5 6 7 8

−−>2+4.2 ans = 6.2 −−>2+4 ans = 6. −−>2−4.2 ans =

15

www.bookmuft.com 9 10 11 12 13 14 15 16 17 18

Dr. Sandeep Nagar [email protected]

− 2.2 −−>2∗4.2 ans = 8.4 −−>2/4.2 ans = 0.4761905 −−>2ˆ4 ans = 16.

As seen in example above, when command is fed at the command prompt --> it is executed and answer is given by displaying the results in next line as ans =.

1.7

Variable browser window

As soon as answer is displayed, the ”Variable Browser” windows shows that a new variable named ”ans” has been created and the value of calculations is stored by this variable name. ans is the default variable name for Scilab. During the course of programming, all variables and thier values as well as thier type is displayed at the variable browser window. Double clicking a variable name or any of its properties, open the same in a graphic interface which looks similar to an excel sheet. This is because, Scilab performs matrix calculations and hence stores values as matrices. A single value is a 1 × 1 matrix (i.e. a matrix having one row and one column). When we shall learn to define arrays, user can correlate the fact that variables will store values an n × m dimensional matrix where data is stored in n rows and m columns. Apart from these 2-dimensional arrays, one can define multi-dimensional arrays too.

1.8 1.8.1

Clearing Clearing screen

When a programmer start working at a command line interface, after some time the screen fills up with a lot of information. This can be very distracting at times. For the purpose of helping the user, Scilab provides the 16

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

in-built function clc which stands for clear command window. clc clears all input and output from the console. Scilab function tohome() also provides the same functionality where it moves the cursor to the upper-left corner of the Command Window and clears the screen. clc(4) clears the 4 lines above the cursor and positions it there. Interestingly, it takes a floating point number argument too and perform same as integer argument.

1.8.2

Clearing Variables

Variable values are stored at specific memory locations. The command clear kills these variables, unless they are protected. protected variables are standard libraries and variables with the percent prefix. As soon as the user types clear at command prompt, one can see that the Variable Browser is cleared of all values and information. If three variables a,b,c have been defined that they can be selectively killed by issuing command clear a where only variable named a is killed and other true remains safe. The function isdef() checks whether a variable is live. Check out the following excercise. 1 2 3 4 5 6 7 8 9 10 11 12 13

d i s p ( ” D e f i n e t h r e e v a i a b l e s named a , b , c ” ) a = 10; b = 12.2; c = a ∗ b; d i s p ( ” Checking i f v a r i a b l e s have been d e f i n e d a s a , b , c ” ) disp ( i s d e f ( ”a” ) ) d i s p ( i s d e f ( ”b” ) ) d i s p ( i s d e f ( ”b” ) ) disp ( ” After c l e a r i n g the v a r i a b l e a” ) clear a disp ( i s d e f ( ”a” ) ) d i s p ( i s d e f ( ”b” ) ) d i s p ( i s d e f ( ”b” ) )

clear.sce When executed (by writing exec(clear.sce)), it produces the following output: 1 2 3 4

−−>e x e c ( ’ c l e a r . s c e ’ ) −−>d i s p ( ” D e f i n e t h r e e v a i a b l e s named a , b , c ” ) D e f i n e t h r e e v a i a b l e s named a , b , c −−>a = 1 0 ;

17

www.bookmuft.com 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

Dr. Sandeep Nagar [email protected]

−−>b = 1 2 . 2 ; −−>c = a ∗ b ; −−>d i s p ( ” Checking i f v a r i a b l e s have been d e f i n e d a s a , b , c ” ) Checking i f v a r i a b l e s have been d e f i n e d a s a , b , c −−>d i s p ( i s d e f ( ” a ” ) ) T −−>d i s p ( i s d e f ( ”b” ) ) T −−>d i s p ( i s d e f ( ”b” ) ) T −−>d i s p ( ” A f t e r c l e a r i n g t h e v a r i a b l e a ” ) After c l e a r i n g the v a r i a b l e a −−>c l e a r a −−>d i s p ( i s d e f ( ” a ” ) ) F −−>d i s p ( i s d e f ( ”b” ) ) T −−>d i s p ( i s d e f ( ”b” ) ) T

1.9

Comments

All programming languages are designed to encourage programmers to put comments at desired places in program so that programmers can make them in human-understandable form. Scilab uses the double forward slash (//). Anything written in front of a comment, is not executed by the interpreter. Comments are used as texts explaining the flow of information and tagging information at specific locations in program.

1.10

Seeking help

Scilab provides a very useful function namely help where one can simply mention the Scilab command and read the documentation. Say for examle help exec gives detailed documentation of exec command. the documentation also gives some useful examples for better understanding of usage.

1.11

Predefined constants

Scientific computing requires some predefined constants which are frequently used. They are preceded by the % sign as shown below. 18

Dr. Sandeep Nagar [email protected] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

disp ( ” value d i s p ( %pi ) disp ( ” value d i s p ( %eps ) d i s p ( ” Value d i s p ( %inf ) d i s p ( ” Value d i s p (%e) d i s p ( ” Value d i s p ( %i ) disp ( ” value d i s p ( %t ) d i s p ( ” Value d i s p ( %f ) disp ( ” value d i s p (%nan)

www.bookmuft.com

of pi : ”) of eps : ” ) of i n f i n i t y : ”) of e : ”) o f i m a g i n a r y number i : ” ) o f b o o l e a n True : ” ) of boolean False : ” ) o f Not−a−number v a r i a b l e i . e . nan : ” )

constants.sce When executed (by writing exec(constants.sce)), it produces the following output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

value of pi : 3.1415927 value of eps : 2 . 2 2 0D−16 Value o f i n f i n i t y : Inf Value o f e : 2.7182818 Value o f i m a g i n a r y number i : i v a l u e o f b o o l e a n True : T Value o f b o o l e a n F a l s e : F v a l u e o f Not−a−number v a r i a b l e i . e . nan : Nan

A number of physical constants are per-defined: pi, e (Euler’s number), √ i is the imaginary number −1), inf (Infinity = ∞), NaN (Not a Number - resulting from undefined operations, such as Inf/Inf) and eps which is defined as 2−52 . 19

www.bookmuft.com

1.11.1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

Dr. Sandeep Nagar [email protected]

Common mathematical functions

−−>abs ( %i ) ans = 1. −−>abs ( %pi ) ans = 3.1415927 −−>abs(−%pi ) ans = 3.1415927 −−>l o g ( 1 0 ) ans = 2.3025851 −−>l o g (%e) ans = 1. −−>l o g 1 0 ( 1 0 ) ans = 1. −−>s i n ( 4 5 ) ans = 0.8509035 −−>s i n ( ( 4 5 ∗ %pi ) / 1 8 0 ) ans = 0.7071068 −−>s q r t ( 2 ) ans = 1.4142136 −−>a c o s ( 1 ) ans = 0.

A number of predefined mathematical functions exists in Scilab like:

• absolute value: abs() • Logarithm: Natural logarithm log(), Base 10 logarithm log10() • trigonometric functions” sin(), cos(), tan() Arguments are taken in radians • inverse-trigonometric functions” asin(), acos(), atan() 20

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Complex calculations using these functions and operations can be performed with ease like p sin(10)2 + cos(10)2 . 1 2 3 4 5 6

7

t h e t a = 1 0 ; // Theta i s taken a s 10 h e r e s = sin ( theta ) ; s sq = s ˆ2; c = cos ( theta ) ; c sq = c ˆ2; r e s u l t = s q r t ( s s q + c s q ) ; // V a r i a b l e named ” r e s u l t ” s t o r e s v a l u e o f answer disp ( r e s u l t )

complexCal.sce The result is displayed as 1 in compliance with trigonometric identity: p sin(θ)2 + cos(θ)2

1.12

Variable

Variables are used to store values temporarily at computer memory locations. They are addressed using a alphanumeric symbol or set of symbols (called strings). The example of this approach is given in Scilab code complexCalc.sce where numeric value 10 is stored in variable name theta, then sin(θ) is calculated and stored in variable named s. SImilarly cos(θ) is stored as c. Thier respective squares are stored in variable named s_sq and c_sq. Finally a variable named result stores the calculation p sin(θ)2 + cos(θ)2 and this variable name is used to print the final answer of calculation. The main advantage of using this approach is that value allocation to a variable is a dynamic process. If user changes the value of variable theta to 5 instead of 10, the value changes at all places where this variable is called.

1.12.1

Assignment operator =

The symbol = works as an assignment operator, which assigns the value present on right hand to the variable name at left hand side. In mathematics, the symbol is used to equate two sides of equation but in Scilab, the symbol is used for assigning values. The equivalent of mathematical symbol for equality is the symbol == which checks the equality of data value for qualtities on both sides. 21

www.bookmuft.com 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Dr. Sandeep Nagar [email protected]

−−>1==2 ans = F −−>1==1.0 ans = T −−>a=1 a = 1. −−>b=2 b = 2. −−>a==b ans = F

Multiple assignments can be performed by using comma (,) operator. Also if we do not wish to produce results on screen, we can suppress this by using ; operator. 1 2 3 4 5 6 7

−−>a1 =10 , a2 =20 , a3=30 a1 = 10. a2 = 20. a3 = 30.

Output can be suppressed using ; operator in front of command. In the following case, assignment for a3 is not produced on terminal since it is supressed with an ; operator. 1 2 3 4 5 6 7 8

−−>a1 =10 , a2 =20 , a3 =30; a1 = 10. a2 = 20. −−>a3 a3 = 30.

22

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Note that the only the output at terminal is suppressed but the assignment operation is unaffected by ; operator. It can still be accessed as shown by second command at the terminal.

1.12.2

Data types

Numerical data While assigning data to a variable it is important to understand that data can be defined as a variety of object defined by its data-type. The command help(type) gives detailed documentation about various data-types. Signed and unsigned integers are stored as 1, 2 or 4 bytes as int8, int16, int32, unit8, uint16, unit32 data type. Thier ranges are given in table: Data Type int8 uint8 int16 uint16 int32 uint32

Range [−128, 127] [0, 255] [−32768, 32767] [0, 65535] [−2147483648, 2147483647] [0, 4294967295]

Its easier to understand and remember the limits by knowing that facts that for binary representation of 8 bits, we can make a maximum number given by 28 = 256. When number starts from 0, this makes the range of limits to be [0, 255]. When this range needs to accommodate integers of both signs, it splits to [−128, 127] because the positive numbers accommodate 0 too. Following codes will make user understand the consequences of defining the data-type beyond its range. 1 2 3 4 5 6 7 8 9

−−>a=i n t 8 ( 2 ˆ 1 0 ) a = 0 −−>a=i n t 1 6 ( 2 ˆ 1 0 ) a = 1024 −−>a=i n t 3 2 ( 2 ˆ 1 0 ) a = 1024

23

www.bookmuft.com

Dr. Sandeep Nagar [email protected]

Since 210 = 1024, which is beyond the range of int8 data-type, it results in storage of 0 as its value whereas it can be stored in int16, int32 datatypes. Another data type for numerical values is double and float which store real numbers. Real variables are stored as 64 bits floating point numbers. This format includes: • One bit to store the sign of the number • 52 significant bits • 11 for exponent This complies with IEEE 754 standard. Its is important to note that ≈ 1019 which means that we can define numbers as large as 1019 in real number system. 264

Specialized packages exists for Scilab where arbitrary precision can be used for more accurate mathematical calculations. Even though detailed discussion of this topic is beyond the scope of present book, users are advised to check out he packages xnum (maximum precision of 200 digits) at http: //www.awitness.org/unifiedm/xnum.html and Mupat at http://www. awitness.org/unifiedm/qupat.html. Precision plays an important role in producing meaningfully reliable numerical values for critical applications so data-type is such cases must be used judiciously. Controlling the format of displaying the number of digits of a numerical value, is one of the most significant ability of advanced programming environment. Scilab provides the command format. Its description can be obtained using the command help format. The command format() takes integer values as argument for displaying the number of digits in numerical value. The range for this input argument is [2, 25]. 1 2 3 4 5 6 7 8 9

−−>exp ( 1 ) ans = 2.7182818 −−>format ( 2 0 ) −−>exp ( 1 ) ans = 2.71828182845904509 −−>format ( 3 0 ) !−− e r r o r 999

24

Dr. Sandeep Nagar [email protected] 10

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

www.bookmuft.com

f o r m at : Wrong v a l u e f o r i n p u t argument #1: Must be i n t h e interval [2 , 25]. −−>f o rmat ( 2 5 ) −−>exp ( 1 ) ans = 2.7182818284590450907956 −−>f o rmat ( 2 ) −−>exp ( 1 ) ans = 3. −−>f o rmat ( 2 ) −−>exp ( 1 0 0 ) ans = ∗∗ −−>f o rmat ( 2 0 ) −−>exp ( 1 0 0 ) ans = 2 . 6 8 8 1 1 7 1 4 1 8 1 6 1D+43

exp(1) represents e1 = 2.7182818 which is also called the Euler number. When the format command restricts too few digits for representation of a large number (ex: format(2) for e100 ) then instead of digits, * is displayed. Boolean data help(boolean) provides detailed description about boolean variables namely \%T for true and \%F for flase. Boolean variable must be operated using boolean operators like (NOT) ~, (AND) \& and (OR) | operator. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

−−>a = [%T, %F] a = T F −−>b = a b = T F −−>˜a ans = F T −−>a&b ans = T F −−>a | b ans = T F

25

www.bookmuft.com

Dr. Sandeep Nagar [email protected]

Strings Alphabets along with special characters are treated as string data-type. The in-built function string() converts a given value to string data type. As shown in example below, the numberical value 2 is converted to a string data type when string() function is applied to it and remains an integet type otherwise. 1 2 3 4 5 6 7

−−>type ( s t r i n g ( 2 ) ) ans = 10. −−>type ( 2 ) ans = 1. −−>h e l p ( type )

It is worth noting that binary data for 2 as a string and as a number will be quite different and hence the numerical computations will treat them differently even if it is always displayed as 2. When it is represented as a string, operators will first understand the data-type and then operate. An addition operator is simply a concatenation operator for strings. 1 2 3 4 5 6

−−>s t r i n g ( 2 )+s t r i n g ( 3 ) ans = 23 −−>2+3 ans = 5.

In general, strings are defined by enclosing them in single quotes (’’) or double quotes (""). Strings are case sensitive too. 1 2 3 4 5 6 7 8 9

−−>a = ” h e l l o world ” a = h e l l o world −−>b = ’ H e l l o World ’ b = H e l l o World −−>a ==b ans = F

26

Dr. Sandeep Nagar [email protected]

1.12.3

www.bookmuft.com

Naming conventions for variables

There are some naming conventions for variables names, which must be respected to avoid errors. • Names should not start with a number however numbers can be used anywhere afterwards. • Variable names are case sensitive • Keywords cannot be used as names. • Names can include underscore (_)

1.12.4

List of variables

List of all variables can be obtained by the commands who and whos where who simply presents the list of variables in the workspace whereas whos presents the same with more details like size of variable, number of bytes used to store the variable and variable type. By using who and whos one can keep track of memory requirements judicious This is critical in memory and speed starved systems like Raspberry Pi.

1.12.5

Global and Local Variables

A variable declared globally i.e. within the main program is known as global variable whereas a variable declared locally within a function is known as local variable. Global variables are available to all functions whereas local variables are available only for particular functions. It is defined using global declaration statement. Once defined, it remains same irrespective of any new definition unless clear command is issued for clearing variable names and values from the memory. Another command i.e. clearglobal performs the task of killing global variable selectively. To check if a variable is global, user can use isglobal() function. Global variables are used to define constants during numerical calculations. Suppose we wish that all variable except some should change values, then we name those unchanging values to be global variables by giving the name of our choice. The predefined variables like %pi, %e etc. have been defined in a similar manner. 27

www.bookmuft.com

1.13

Dr. Sandeep Nagar [email protected]

Complex numbers

One of the most important part of doing mathematical calculations on computers is the ability to work with complex numbers and their algebra. The in-built function complex() provides this facility. Detailed documentation can be obtained by simply typing help complex on Scilab command line. 1 2 3 4 5 6

−−>complex ( 5 , 4 ) ans = 5. + 4. i −−>complex ([ −3 1 ] , [ 3 −1]) ans = − 3. + 3. i 1. − i

When only first argument is specified, then the imaginary part is set to zero. 1 2 3 4 5 6

−−>complex ([ −3 1 ] ) ans = − 3. 1. −−>complex ( 5 ) ans = 5.

If the two arguments are dis-similar sized matrices, the output is adjusted for its size accordingly in some cases when one of the argument is just a single number. 1 2 3 4 5 6

−−>complex ([ −3 1 ] , 9 ) ans = − 3. + 9. i 1. + 9. i −−>complex ( 9 ,[ − 3 1 ] ) ans = 9. − 3. i 9. + i

On the other hand, of the size of two argument matrices differ as below, an error message is generated. 28

Dr. Sandeep Nagar [email protected] 1 2 3 4 5 6 7 8 9 10 11 12 13

www.bookmuft.com

−−>a=rand ( 2 , 2 ) ; −−>b=rand ( 2 , 3 ) ; −−>complex ( a , b ) !−− e r r o r 8 Inconsistent addition . at l i n e 45 o f f u n c t i o n complex c a l l e d by : complex ( a , b ) −−>a=rand ( 2 , 2 ) ; −−>b=rand ( 2 , 2 ) ; −−>complex ( a , b ) ans = 0.3076091 + 0.3616361 i 0.2146008 + 0.5664249 i 0.9329616 + 0.2922267 i 0.312642 + 0.4826472 i

1.13.1

Real and imaginary parts

Real and imaginary parts of a real number are given by the in-built functions real(),imag() as follows: 1 2 3 4 5 6 7 8 9 10 11 12

−−>r r = 2. −−>i i = 3. −−>r r = 2. −−>i i = − 3.

= r e a l ( complex ( 2 , 3 ) )

= imag ( complex ( 2 , 3 ) )

= r e a l ( complex ( [ 2 , 3 ] , [ − 3 , − 4 ] ) ) 3. = imag ( complex ( [ 2 , 3 ] , [ − 3 , − 4 ] ) ) − 4.

1.13.2

Complex conjugate

The in-built function conj() produces the complex conjugate of a given complex number. 1 2 3 4 5

−−>a = complex ( 2 , 3 ) a = 2. + 3. i −−>b = c o n j ( a ) b =

29

Dr. Sandeep Nagar [email protected]

www.bookmuft.com 6 7 8 9

2. − 3. i −−>a ∗b ans = 13.

The product of a complex number with its conjugate can be understood as Y ((a + ib), (a − ib)) = a2 + b2 Where a and b are real and imaginary parts. For multiple entries i.e. complex numbers as array elements: 1 2 3 4 5 6 7 8 9

−−>a = complex ( [ 1 2 3 ] , [ 4 5 6 ] ) a = 1. + 4. i 2. + 5. i 3. + 6. i −−>b = c o n j ( a ) b = 1. − 4. i 2. − 5. i 3. − 6. i −−>a . ∗ b ans = 17. 29. 45.

1.13.3

imult

The in-built function imult() is an efficient way of multiplying a real number with i (the imaginary unitart) especially when %inf and %nan are present in the calculation. 1 2 3 4 5 6 7 8 9 10 11 12

−−>i m u l t (%nan) ans = Nani −−>i m u l t ( %inf ) ans = Infi −−>%i∗%nan ans = Nan + Nani −−>%i∗ %inf ans = Nan + I n f i

30

Dr. Sandeep Nagar [email protected] 13 14 15 16 17 18

www.bookmuft.com

−−>i m u l t ( 4 ) ans = 4. i −−>i m u l t ( complex ( 4 , 4 ) ) ans = − 4. + 4. i

As seen above when 4 × i = 4i and (4 + 4i) × i = 4i − 4 = −4 + 4i

1.13.4

Checking if variable has complex components

The in-built function isreal() checks if a variable has complex componets. It produces an boolean output T if input variable does not have complex numbers and outputs F otherwise. 1 2 3 4 5 6 7 8 9 10 11 12

−−>a = [ 1 2 3 ] a = 1. 2. 3. −−>a1 = complex ( a , a ) a1 = 1. + i 2. + 2. i −−> i s r e a l ( a ) ans = T −−> i s r e a l ( a1 ) ans = F

1.14

3. + 3. i

Summary

Using Scilab as a simple calculator (using numbers and basic operations) as well as a complex calculator (using variables with complex functions), one can perform numerical calculation at ease. Learning curve for Scilab is quite flat owing to is simple and intuitive syntax. In case of confusion, documentation for particular commands can be easily available using help 31

www.bookmuft.com

Dr. Sandeep Nagar [email protected]

command. Octave also provides an integrated environment for working with a lot of different kinds of computational tasks.

32

2 Working with Arrays

2.1

Introduction

Matrix formulation of mathematical problem enables faster numerical computations. For a 2 dimensional matrix, elements have unique row and column index through which one can access them. Rows and Columns can be attributed to different properties under study. In this way, one can fit data for two properties as a matrix and then use these matrices for numerical calculations. For example, suppose element of a row is defined as 1 if a compound is conductor and 2 if it is a semiconductor and 3 if it is an insulator. Then a row vector (a matrix composed of only one row) [1 0 0 3 2 1 3 0 1 0 3 2 1] has information about 13 compounds. In a numerical calculation involving conductive nature of a compound, this row vector (a 13 × 1 matrix) can be utilized where 13 compounds can be simultanelusly scanned mathematically. Scilab has a class of objects for dealing with matrices. They are called arrays. Using different properties of this class, one can define various kinds of matrices. Built-in functions for matrix operations make it easier for a programmer to deal with large number of data by arranging them as a 33

www.bookmuft.com

Dr. Sandeep Nagar [email protected]

matrix in the desired format and performing array operations.

2.2

Arrays and vectors

Instead of just pointing to a single number, a variable name can point to a sequential set of numbers called an array. Arrays must be defined within square brackets [] as shown below. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

−−>a = [ 1 2 3 4 5 ] a = 1. 2. 3. 4. 5. −−>b = [ 1 , 2 , 3 , 4 , 5 ] b = 1. 2. 3. 4. 5. −−>c = [ 1 . 0 2 . 0 3 . 0 4 . 0 5 . 0 ] c = 1. 2. 3. 4. 5. −−>m at ri x 22 = [ 1 2 ; 3 4 ] m at ri x 22 = 1. 2. 3. 4. −−>m at ri x 33 = [ 1 2 3 ; 4 5 6 ; 7 8 9 ] m at ri x 33 = 1. 2. 3. 4. 5. 6. 7. 8. 9. −−>s i z e ( m at ri x 22 ) ans = 2. 2. −−>s i z e ( m at ri x 33 ) ans = 3. 3. −−>m at ri x 32 = [ 1 2 ; 3 4 ; 5 6 ] m at ri x 32 = 1. 2. 3. 4. 5. 6. −−>s i z e ( m at ri x 32 ) ans = 3. 2. −−>s i z e ( s i z e ( ma t ri x 33 ) ) ans = 1. 2.

34

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

As seen in the example code, an array can be understood as a matrix consisting of rows and columns. Thus one can make a desired sized matrix for example, matrix22 is a 2 × 2 and matrix33 is a 3 × 3 matrix where as a is a 1 × 5 matrix. The first number while defining the size gives the number of rows while the second number gives the number of columns. The comma (,) operator operates by defining the next element in the same row whereas the (;) operator defines the numbers in the next line/row. Usage of comma operator is optional. If skipped, it must be replaced by a white space. The inbuilt function size() outputs a 2 × 1 array where first number signifies number of rows and second number represents the number of coloumns. If the number of elements in each row/column do not match then one obtains an error message: 1 2 3 4 5 6 7 8 9 10 11

>> r i g h t 3 3 = [ 1 , 2 , 3 ; 4 , 5 , 6 ; 7 , 8 , 9 ] right33 = 1 2 3 4 5 6 7 8 9 −−>wrong33 = [ 2 , 3 ; 4 , 5 , 6 ; 7 , 8 , 9 ] !−− e r r o r 6 I n c o n s i s t e n t row/ column d i m e n s i o n s . wrong33 = [ 1 , 2 , 3 ; 4 , 5 , 6 ; 8 , 9 ] !−− e r r o r 6 I n c o n s i s t e n t row/ column d i m e n s i o n s .

Elements of an array can be any data-type as defined in section 1.12.2. The in-built function type() can be used to determine the data-type of stored values. All elements of an array can be set to a particular data-type by the commands as shown below: 1 2 3 4 5 6 7 8 9 10 11 12

−−>a = u i n t 8 ( [ 1 2 3 ] ) a = 1 2 3 −−>b = u i n t 1 6 ( [ 1 2 3 ] ) b = 1 2 3 −−>c = u i n t 3 2 ( [ 1 2 3 ] ) c = 1 2 3 −−>type ( a ) ans = 8.

35

www.bookmuft.com 13 14 15 16 17 18

Dr. Sandeep Nagar [email protected]

−−>type ( b ) ans = 8. −−>type ( c ) ans = 8.

2.3

Operations on arrays and vectors

Operating on arrays has two aspects: • Operating on two or more arrays • Element wise operations All arithmetic operators like +,-,*,/,^ etc. can be used in both cases. When we need to do element wise operation, then a . is placed before operator so that element-wise operators become .+,.-,.*,./,.^. This will become more clear in following example. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

1−−>a = [ 1 2 3 ; 4 5 6 ; 7 8 9 ] a = 1. 2. 3. 4. 5. 6. 7. 8. 9. −−>b = a b = 1. 2. 3. 4. 5. 6. 7. 8. 9. −−>a . / b ans = 1. 1. 1. 1. 1. 1. 1. 1. 1. −−>a ˆb !−− e r r o r 43 Not implemented i n s c i l a b . . . at l i n e 61 o f f u n c t i o n %s pow c a l l e d by : a ˆb −−>a . ˆ bc // Element w i s e o p e r a t i o n

36

Dr. Sandeep Nagar [email protected] 22 23 24 25

ans = 1. 256. 823543.

4. 3125. 16777216.

www.bookmuft.com 27. 46656. 387420489.

Those who are familiar with matrix algebra, know that matrix multiplication and division is not a straightforward task. A aXb matrix can only be multiplied by a bXc matrix which results in aXc matrix and it is performed by multiplying elements of rows with elements of columns to get new elements. Following code will illustrate this matrix multiplication method. 1 2 3 4 5 6 7 8 9 10 11 12 13 14

−−> a = [ 1 , 2 ; 3 , 4 ; 5 , 6 ] a = 1. 2. 3. 4. 5. 6. −−>a ’ ans = 1. 3. 5. 2. 4. 6. −−>a ∗a ’ ans = 5. 11. 17. 11. 25. 39. 17. 39. 61.

a’ gives the transpose of a matrix (rows are made columns and vice versa). Performing division of a matrix involves the matrix inversion. 1 2 3 4

−−>pi nv ( a ) ans = − 1.33333 − 0.33333 0.66667 1.08333 0.33333 − 0.41667

pinv() function give s a psuedo-inverse of a matrix such that if X=pinv(a) then a*X*a = a, X*a*X = X and both a*X and X*a are Hermitian matrix. I is known as identity matrix because all its diagonal elements are 1 and all non-diagonal elements are zero, which makes its determinant 1. Determinant of a matrix a is calculated by the command det(a). 37

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Automatic generation of an identity matrix is done by using the command eye(a,b) where a and b are values of number of rows and columns. 1 2 3 4 5 6 7 8 9 10 11 12 13

−−>eye ( 2 , 3 ) ans = 1. 0. 0. 0. 1. 0. −−>a = eye ( 4 , 4 ) a = 1. 0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0. −−>d e t ( a ) ans = 1.

2.3.1

0. 0. 0. 1.

Magnitude of a vector

A mathematical vector can be defined by vector defined as a 1 × 3 array. The in-built function norm() gives the magnitude of vector. So if a vector is defined as: ~a = A~x + B~y + C~z then its magnitude can be defined as: p N = A2 + B 2 + C 2 A unit vector for a vector is obtained by dividing the vector by its own norm/magnitude. So this can be performed with ease in Scilab. 1 2 3 4 5 6 7 8 9

−−>a = [ 1 2 3 ] a = 1. 2. 3. −−>norm ( a ) ans = 3.74166 −−>a = [ 1 2 3 ] / norm ( a ) a = 0.26726 0.53452 0.80178

38

Dr. Sandeep Nagar [email protected]

2.3.2

www.bookmuft.com

Random matrix

Using random number generators, a random matrix can be created by the command rand(a,b) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

−−>rand ( 4 , 5 ) ans = 0.21132 0.66538 0.75604 0.62839 0.00022 0.84975 0.33033 0.68573 −−>rand ( 4 , 5 ) ans = 0.30761 0.36164 0.93296 0.29223 0.21460 0.56642 0.31264 0.48265 −−>rand ( 1 ) ans = 0.28065 −−>rand ( 4 , 1 ) ans = 0.12801 0.77831 0.21190 0.11214 −−>rand ( 1 , 4 ) ans = 0.68569 0.15312

0.87822 0.06837 0.56085 0.66236

0.72635 0.19851 0.54426 0.23207

0.23122 0.21646 0.88339 0.65251

0.33217 0.59351 0.50153 0.43686

0.26931 0.63257 0.40520 0.91847

0.04373 0.48185 0.26396 0.41481

0.69709

0.84155

Please note that the numbers generated above will be different each time even on same machine since they are supposed to be random in nature. By default, they are uniformly distributed over the interval (0, 1). A vector is simply a row vector so it can be generated randomly by command rand(a). help rand gives detailed description about various other features and arguments of random number generator. 1 2 3

−−>rand ( 4 , 5 , ’ u nif orm ’ ) ans = 0.11384 0.68540 0.38738

0.37601

0.26386

39

Dr. Sandeep Nagar [email protected]

www.bookmuft.com 4 5 6 7 8 9 10 11 12

0.19983 0.89062 0.56187 0.50422 0.58962 0.34936 −−>rand ( 4 , 5 , ’ normal ’ ) ans = − 1.28586 − 0.37782 0.59712 1.14562 0.61078 2.57491 − − 1.05679 − 0.50056

0.92229 0.94882 0.34353

0.73409 0.26158 0.49935

− 0.45753 0.01164 0.56232 0.22327 0.64533 − 1.43445 − 0.36478 1.73638

0.52536 0.53762 0.11999

1.74874 1.86518 0.16459 − 1.03589

The ’normal’ and ’uniform’ provides normal and uniform distribution of random numbers. A more refined in-built function named grand() gives a variety of options to choose distributions and set limits for the set of numbers. Simply typing help(grand) provides detailed documentation for its usage.

2.3.3

Indexing

Each element of the matrix is characterized by two numbers, the row number and the column number. This is used to pinpoint an element and operate on that. They are called index of elements. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

−−>a = rand ( 3 , 4 ) a = 0.38850 0.04070 0.67899 0.64673 0.37286 0.81418 −−>a ( 2 , 1 ) ans = 0.67899 −−>a ( 4 , 2 ) !−− e r r o r 21 I n v a l i d index . −−>a ( 2 , 2 ) =0 a = 0.38850 0.04070 0.67899 0. 0.37286 0.81418

40

0.44219 0.48739 0.76592

0.01109 0.84484 0.89999

0.44219 0.48739 0.76592

0.01109 0.84484 0.89999

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Assignment operator can be used to set the value at a particular index to produce a new matrix with updated value(s). It is important to note that unlike some programming languages, where indices start from 0, in Scilab indices start from 1 and it does not take negative numbers as indices.

2.3.4 1 2 3 4 5 6

Using indices to make new vector

−−>a = [ 1 4 a = 1. 4. −−>b = a ( [ 2 b = 4. 3.

1 3 1 4 1 4 2 4 5] 1. 3. 4 2 4]) 4.

1.

4.

1.

4.

2.

4.

5.

3.

In the above example, b is a new vector formed from vector a where successive elements are made up of elements taken from a index vector [2 4 2 4]. Same method can be employed for 2-dimesnional and higher dimensional matrices. 1 2 3 4 5 6 7 8 9

−−>a a = 0.61618 0.38019 0.63517 0.35260 0.15988 0.91202 −−>a ( [ 1 , 2 ] , [ 2 , 3 ] ) ans = 0.38019 0.76251 0.35260 0.7284

0.76251 0.7284 0.27883

0.40089 0.55388 0.27174

Please note that since use of comma operator is optional, so henceforth vectors and matrices will be defined by simply putting a whitespace.

2.3.5

Slicing

Matrices can be sliced to desired portions by using indices and colon : operator. If n:m is provided for slicing then a new matrix is fabricated where element with index n to index m are placed. 41

Dr. Sandeep Nagar [email protected]

www.bookmuft.com 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

−−>a = [ 1 2 4 5 7 a = 1. 2. 4. −−>a ( 2 : 5 ) ans = 2. 4. 5. −−>a ( 0 : 5 ) !−− e r r o r 21 I n v a l i d index . −−>a ( : 5 ) !−− e r r o r 276 Missing operator , −−>a ( : ) ans = 1. 2. 4. 5. 7. 5. 7. 5. 7. −−>a ( 1 : ) !−− e r r o r 2

2.4

5 7 5 7] 5.

7.

5.

7.

5.

7.

7.

comma , o r s e m i c o l o n .

Automatic generation of vectors

Most often a user would like to generate a long list of sequential numbers as elements of an array. This is called the automatic generation of vectors. One can generate a series of numbers and store them as arrays by using the command start:step:stop 1 2 3 4 5 6 7 8 9

−−>a = 1 : 1 : 1 0 a = 1. 2. 3. −−>a = [ 1 : 1 : 1 0 ] a = 1. 2. 3. −−>a = 1 : 2 : 1 0 a = 1. 3. 5.

42

4.

5.

6.

7.

8.

9.

10.

4.

5.

6.

7.

8.

9.

10.

7.

9.

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Please note that [] are optional here. Also, if the step is not defined then its default value (1) is taken. 1 2 3

−−>a =1:10 a = 1. 2.

2.4.1

3.

4.

5.

6.

7.

8.

9.

10.

Linearly spaced vector

The command linspace(start,stop,n) produces an array starting from first number and stopping at second one with a total of n numbers. Hence they are linearly spaced. 1 2 3 4 5 6

−−>a = l i n s p a c e ( 1 , 2 , 5 ) a = 1. 1.25 1.5 1.75 −−>a = l i n s p a c e ( 1 , 1 0 , 1 0 ) a = 1. 2. 3. 4. 5.

2.4.2

2.

6.

7.

8.

9.

10.

logarithmically space vector

Similar to linspace logspace(start, stop,n) produces n number from start to stop which are linearly space in logarithmic nature. 1 2 3

−−>a = l o g s p a c e ( 1 , 1 0 , 5 ) a = 10. 1778.28 316228.

2.4.3

5 . 6D+07

1 . 0D+10

Meshgrid

The in-built functions linspace and logpspace are used to derive points on a line segement graphically. If we wish to derive a surface, as equally spaced mesh points, then we use the in-built function meshgrid as follows: 43

www.bookmuft.com 1 2 3

Dr. Sandeep Nagar [email protected]

−−>a = 1 : 0 . 1 : 1 0 0 ; −−>b = 1 : 0 . 1 : 1 0 0 ; −−>[X,Y]= meshgrid ( a , b ) ;

Here [X,Y] is an 2D-array containing two numbers for each element. One of the element is taken from the array a and other element is taken from the array b.

2.4.4

Ndgrid

The in-built function meshgrid provides a 2D grid of points on which a 3D function can be dfiend to fabricate a 3D surface. The in-built function ndgrid provides an n-dimesnional grid in similar fashio as shown below: 1 2 3 4

−−>a = 1 : 0 . 1 : 1 0 ; −−>b = 1 : 0 . 1 : 1 0 ; −−>c = 1 : 0 . 1 : 1 0 ; −−>[X Y Z ] = n d g r i d ( a , b , c ) ;

2.5

Matrix manipulations

Some common matrix manipulations have already been written in function form which makes it easier for developer to use them right away, rather than invest time to write an optimum code.

2.5.1

scalar operation with a matrix

Scalar multiplication of a matrix can be performed by simply multiplying a scalar with a matrix. One can argue that a scalar is a 1 × 1 dimensional matrix so how can it operate on say a m × n matrix. In this case, a scalar is projected onto a m × n dimensions and then element wise operation is performed. 1 2 3 4 5 6 7

−−>a = [ 1 2 a = 1. 2. 4. 5. 7. 8. −−>a2 = 2∗ a a2 =

44

3; 4 5 6; 7 8 9] 3. 6. 9.

Dr. Sandeep Nagar [email protected] 8 9 10 11 12 13 14 15

2. 4. 8. 10. 14. 16. −−>a3 = a /2 a3 = 0.5 1. 2. 2.5 3.5 4.

2.5.2

www.bookmuft.com

6. 12. 18.

1.5 3. 4.5

Reshaping a matrix

Number of rows and columns can be changed provided total number of elements remains same. For this purpose matrix() function can be used. Its usage is illustrated well in help()matrix). 1 2 3 4 5 6 7 8 9 10 11

−−>a = [ 1 2 3 ; 4 5 6 ; 7 8 9 ] a = 1. 2. 3. 4. 5. 6. 7. 8. 9. −−>a1 = matrix ( a , 1 , 9 ) a1 = 1. 4. 7. 2. 5. 8. 3. 6. 9. −−>a1 = matrix ( a , 2 , 5 ) !−− e r r o r 60 Wrong s i z e f o r argument : I n c o m p a t i b l e d i m e n s i o n s .

2.6

Special matrices

Matrix algebra defines some kinds of matrices which are special in nature and find their use in some problems. Octave has some functions defined to create these matrices.

2.6.1

Upper and Lower triangular matrix

Upper triangular matrix is such that only diagonal and elements above diagonal are non-zero. Similarly, lower triangular matrix is such that diagonal and elements below diagonal are non-zero. tril and triu fabricate a lower and upper triangular matrix. 45

Dr. Sandeep Nagar [email protected]

www.bookmuft.com 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

−−>a = rand ( 3 , 3 ) a = 0.40409 0.31513 0.41941 0.78735 0.24369 0.63817 −−> t r i l ( a ) ans = 0.40409 0. 0.41941 0.78735 0.24369 0.63817 −−>t r i u ( a ) ans = 0.40409 0.31513 0. 0.78735 0. 0.

2.6.2

0.02929 0.18410 0.26223

0. 0. 0.26223

0.02929 0.18410 0.26223

Ones and zeros matrix

A matrix having all its numbers as 1 or 0 make up ones and zeros matrix respectively: 1 2 3 4 5 6 7 8 9 10

−−>o n e s ( 3 , 3 ) ans = 1. 1. 1. 1. 1. 1. 1. 1. 1. −−>z e r o s ( 3 , 3 ) ans = 0. 0. 0. 0. 0. 0. 0. 0. 0.

2.6.3

Diagonal matrices

Diagonal matrices with predefined diagonal elements can be fabricated using diag() command. 1 2 3 4 5

−−>d i a g ( [ 1 3 ] ) ans = 1. 0. 0. 3. −−>d i a g ( [ 1 3 4 6 7 ] )

46

Dr. Sandeep Nagar [email protected] 6 7 8 9 10 11

ans 1. 0. 0. 0. 0.

www.bookmuft.com

=

2.6.4

0. 3. 0. 0. 0.

0. 0. 4. 0. 0.

0. 0. 0. 6. 0.

0. 0. 0. 0. 7.

special matrices

The in-built function testmatrix() generates special matrices like a magic square, Franck and inverse of a n × n Hilbert matrix when used with input arguments magi,frk,hilb as strings. 1 2

−−>t e s t m a t r i x ( ’ magi ’ , 3 ) ans =

3 4 5 6

8. 3. 4.

1. 5. 9.

6. 7. 2.

7 8 9

−−>t e s t m a t r i x ( ’ f r k ’ , 4 ) ans =

10 11 12 13 14

4. 3. 0. 0.

3. 3. 2. 0.

2. 2. 2. 1.

1. 1. 1. 1.

15 16 17

−−>t e s t m a t r i x ( ’ h i l b ’ , 4 ) ans =

18 19 20 21 22

16. −120. −120. 1 2 0 0 . 240. −2700. −140. 1 6 8 0 .

2.7

240. −2700. 6480. −4200.

−140. 1680. −4200. 2800.

Mathematical matrix operation

A variety of matrix operations like dot product, cross product etc. exist in matrix algebra. They can be performed in Scilab using appropriate code for the same. 47

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

2.7.1

dot product

Dot product of two vectors produces a scalar as: A~1 = x1~i + y1~j + z1~k A~2 = x2~i + y2~j + z2~k A~1 .A~2 = x1 × x2 + y1 × y2 + z1 × z2 This operation can be performed using the following code where vector dot product is defined as multiplication of a with transpose of b. 1 2 3 4 5

−−>a1 =[1 2 3 ] ; −−>a2 =[2 3 4 ] ; −−>a1 ∗ a2 ’ ans = 20.

2.7.2

cross product

The in-built function cross() returns the cross product of two input vectors as shown below: 1 2 3 4 5 6 7 8 9 10 11 12

13 14

−−>a =[1 2 3 ] ; −−>b=[2 3 4 ] ; −−>c r o s s ( a , b ) ans = − 1. 2. − 1. −−>a1 =[%t , %t , %f ] ; // One can d e f i n e v e c t o r u s i n g b o o l e a n s t o o −−>a2 =[%f , %f , %f ] ; −−>c r o s s ( a1 , a2 ) ans = 0. 0. 0. −−>c r o s s ( a1 , a ) // c r o s s p r o d u c t o f b o o l e a n v e c t o r with v e c t o r o f r e a l numbers ans = 3. − 3. 1.

2.8

Discrete mathematics

Scilab has a limited but useful set of in-built functions to work with discrete mathematics as follows: 48

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

1. primes outputs the primes numbers untill the given number. 1 2 3 4

−−>x = 3 0 ; −−>y = p r i m e s ( x ) y = 2. 3. 5. 29.

7.

11.

13.

17.

19.

23.

5

2. factor derives the factors of a given number i.e if n is the given number then factor produces an array of prime numbers a,b,c ...z such that Y n= (a, b, c...z) 1 2 3 4

5 6 7 8 9

−−>x=3∗10 e4 ; −−>y=f a c t o r ( x ) y = 2. 2. 2. 2. 5. −−>x =79867858; −−>y=f a c t o r ( x ) y = 2. 7. 5704847. −−>x =9999;

2.

3.

5.

5.

5.

5.

10 11 12 13

−−>y=f a c t o r ( x ) y = 3. 3. 11.

101.

14

3. rat() derives a floating point rational representation of a given number. help rat gives its detailed usage for input arguments. 1 2 3 4 5 6 7 8 9 10

−−>[n , d]= r a t ( %pi ) d = 113. n = 355. −−>[n , d]= r a t (%e) d = 465. n = 1264.

49

www.bookmuft.com 11 12 13 14 15 16 17 18 19 20

Dr. Sandeep Nagar [email protected]

−−>[n , d]= r a t ( 5 0 0 ) d = 1. n = 500. −−>[n , d]= r a t ( 5 0 0 . 5 ) d = 2. n = 1001.

21

4. factorial outputs the factorial of a given number 1 2 3 4 5 6 7 8 9 10 11 12

−−>x = 8 7 ; −−>y=f a c t o r i a l ( x ) y = 2 . 1 0D+132 −−>x = 7 ; −−>y=f a c t o r i a l ( x ) y = 5040. −−>x=0; −−>y=f a c t o r i a l ( x ) y = 1.

13

5. perm outputs permutations of a given set of numbers. 1 2 3 4 5 6 7 8 9 10 11 12

50

−−>x = [ 1 2 3 ] x = 1. 2. 3. −−>y=perms ( x ) y = 3. 2. 1. 3. 1. 2. 2. 3. 1. 2. 1. 3. 1. 3. 2. 1. 2. 3.

Dr. Sandeep Nagar [email protected]

2.9

www.bookmuft.com

Summary

Array based computing lies at the very heart of modern computational techniques. Scilab presents a very suitable platform to perform this technique with ease. A variety of predefined functions enable user to save time while prototyping a problem. Flexible methods to define multidimensional arrays and performing fast computation is the main necessity of our times. Most of the time spent during a simulation is either in loops or in array operations. Predefined array operations have been optimized with algorithms for reliability, time saving and efficient memory management.

51

www.bookmuft.com

52

Dr. Sandeep Nagar [email protected]

3 Plotting

3.1

Introduction

Without visualization, numerical computations are difficult to understand and eventually judge. Producing publication quality images of complex plots which give a meaningful analysis of numerical results, has been a challenge for scientists all over the world. Many commercial softwares made good business satisfying this need. Scilab also provides this facility quite efficiently. Plotting features includes choosing from various types of plots in 2D and 3D regime, decorating plots with additional information like titles, labeled axes, grids, label for data, writing equations and other important information about data etc. Following sections will describe these actions in detail. It is worth mentioning that plotting capabilities are essential to certain numerical analysis experiments since visual directions from the progressive steps give intuitive understanding of the problem under consideration. 53

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

3.2 3.2.1

2D plotting plot(x,y)

Since one need data on two axes to be plotted, we first need to create them. Lets assume that x axis has 100 linearly space data points and points on y-axis are defined by equation y = x2 . 1 2 3

>>x = l i n s p a c e ( 0 , 1 0 0 , 1 0 0 ) ; >> y = x . ˆ 2 >> p l o t ( x , y )

Figure 3.1: y = x2

54

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

First we defined a variable x and placed 100 equally spaced data points from 0 to 100. This made a 1x100 matrix. Using scalar operation of exponentiation, we defined a variable y as x2 . It is important to note that this operation is defined using an element-wise operator so that each element of matrix x is operated by the operator. Without this approach, the array would have to be squared i.e. multipled with itself. This would have produced error since a n × m can only be multipled by a m × n matrix. Finally, one can use the function plot() which takes two arguments as x-axis and y-axis data points. Writing help plot or help’plot’ on the command prompt gives useful insight into this wonderful function written to plot two dimensional data. By default, successive plots are superposed. To clear the previous plot, use clf(). Also the plot function can evaluate the input arguments as shown below. 1

−−>p l o t ( x=l i n s p a c e ( 0 , 1 0 0 , 1 0 0 ) , x . ˆ 2 . 5 , ’ r ∗ ’ )

The result of above line code is given in figure 3.2. Please note that the third argument, a string: "r*" plots the data with * at each point of input array. Multiple plots can be plotted using plot() command. As an example lets plot sin(x) and cos(x) fucntions between −π and π. First version of the code is given as: 1 2

−−>x=l i n s p a c e (−%pi , %pi , 1 0 0 ) ; −−>p l o t ( x , s i n ( x ) , ’ r ∗ ’ , x , c o s ( x ) , ’ b− ’ )

and the second version of code given as: 1 2 3

−−>x=l i n s p a c e (−%pi , %pi , 1 0 0 ) ; −−>p l o t ( x , s i n ( x ) , ’ r ∗ ’ ) −−>p l o t ( x , c o s ( x ) , ’ b− ’ )

55

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.2: y = x2 Both codes produce similar figures because in second version, second plot is overwritten on first plot to produce multiple plots on same figure window. Figure 3.3 shows the result where sin(x) and cos(x) are plotted with * and - markers.

3.2.2

plot2d,plot2d2,plot2d3,plot2d4

plot2d command works similar to plot command. In addition some other variations of these functions exist w.r.t specialized way in which plots are plotted. 1. plot2d2 same as plot2d but the curve is supposed to be piecewise constant. 2.

plot2d3 same as plot2d but the curve is plotted with vertical bars.

3. plot2d4 same as plot2d but the curve is plotted with arrows The following set of codes illustrate their usage 1 2 3

// Program t o p l o t u s i n g p l o t 2 d f u n c t i o n x = l i n s p a c e (−%pi , %pi , 2 0 ) plot2d (x , sin (x) )

56

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.3: sin(x) and cos(x)

4 5 6

x t i t l e ( ’ Graph f o r p l o t t i n g s i n ( x ) u s i n g p l o t 2 d ’ ) xlabel ( ’ angle ’ ) ylabel ( ’ sin (x) ’ )

plot2d.sce 1 2 3 4 5 6

// Program t o p l o t u s i n g p l o t 2 d 2 f u n c t i o n x = l i n s p a c e (−%pi , %pi , 2 0 ) plot2d2 (x , sin (x) ) x t i t l e ( ’ Graph f o r p l o t t i n g s i n ( x ) u s i n g p l o t 2 d 2 ’ ) xlabel ( ’ angle ’ ) ylabel ( ’ sin (x) ’ )

plot2d2.sce 1 2 3 4 5 6

// Program t o p l o t u s i n g p l o t 2 d 3 f u n c t i o n x = l i n s p a c e (−%pi , %pi , 2 0 ) plot2d3 (x , sin (x) ) x t i t l e ( ’ Graph f o r p l o t t i n g s i n ( x ) u s i n g p l o t 2 d 3 ’ ) xlabel ( ’ angle ’ ) ylabel ( ’ sin (x) ’ )

plot2d3.sce

57

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.4: sin(x) and cos(x)

Figure 3.5: sin(x) and cos(x)

1

// Program t o p l o t u s i n g p l o t 2 d 4 f u n c t i o n

58

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.6: sin(x) and cos(x) 2 3 4 5 6

x = l i n s p a c e (−%pi , %pi , 2 0 ) plot2d4 (x , sin (x) ) x t i t l e ( ’ Graph f o r p l o t t i n g s i n ( x ) u s i n g p l o t 2 d 4 ’ ) xlabel ( ’ angle ’ ) ylabel ( ’ sin (x) ’ )

plot2d4.sce

3.2.3

polarplot

During mathematical analysis, Polar coordinates becomes important for the cases which do not exhibit symmetry in cartesian systems but do show symmetry in polar coordinates. In these cases, one prefers to plot in polar coordinates, rather than Cartesian coordinates. Then instead of x, y our coordinates are r, θ which are related by the equations x = r × cos(θ) y = r × sin(θ) The code given by polarplot.sce plots one such case. The result is given in figure 3.8. 59

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.7: sin(x) and cos(x)

1 2 3 4

// Program t o p l o t u s i n g p o l a r p l o t f u n c t i o n t h e t a= 0 : . 0 1 : 3 ∗ %pi ; p o l a r p l o t ( s i n (2∗ theta ) , cos ((2∗ theta ) ) ) x t i t l e ( ’ Using p o l a r p l o t ’ )

polarplot.sce

3.3 3.3.1

Special plots Histograms

Histograms are traditionally used to visualize the number of events occurring in within different ranges. Scilab provides a useful function histplot() for this purpose which takes input for number of bins and data provided as an array. For example in code titled hist.sce, normalized distribution of random numbers is plotted in figure 3.9. 1

// Program t o p l o t h i s t o g r a m

2 3 4 5

n=rand ( 1 , 1 0 e4 , ’ normal ’ ) ; b i n s =20 h i s t p l o t ( bins , n)

60

// n o r m a l i z e d g a u s s i a n random sample

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.8: Polar Graph

6 7 8

t i t l e ( ’ Histogram p l o t t i n g random numbers ’ ) xlabel ( ’x ’ ) ylabel ( ’y ’ )

hist.sce

Histograms find their usage in showing the sampled data. From a dataset, one can segregate the data point according to their values into number of bins and visualize which range of values dominate the profile. This contains useful information about the system. For example, values following normalized distribution represent systems which follow certain kind of statistics always. In present case given by Figure 3.9, most of the data events occur in the middle. If this graph represents the probability of finding an electron between two atoms then we can conclude that electron is found mostly in the middle of the atoms. If this graph represents marks obtained by students in the class then one can deduce that very few students obtain very good and very bad marks (extremes of graph) and most of the students got close to 50% marks. 61

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.9: Histogram plot

3.3.2

Matplot

To plot colors representing certain values, matplot command is used as follows: 1 2 3 4 5 6 7

// Program t o p l o t u s i n g Matplot f u n c t i o n x=[1 2 3 4 ; 5 4 3 6 ] Matplot ( x ) g r a y p l o t ( x , y ,m) x t i t l e ( ’ Using Matplot ’ ) xlabel ( ’x ’ ) ylabel ( ’y ’ )

matplot.sce

3.3.3

grayplot

Sometime, we need to see the value of a two dimensional function on a 2D plot. This is done by visualizing the components of the functional value z on x and y coordinates. grayplot plots a graph window for a 2D plot of the surface given by z on a grid defined by x and y. Each rectangle on the grid is filled with a gray or color level depending on the average value of z on the corners of the rectangle. 62

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.10: Matplot figure for [1 2 3 4;5 4 3 6]

1 2 3 4 5 6 7 8

// Program t o p l o t u s i n g g r a y p l o t f u n c t i o n x = −10:10; y = −10:10; m=rand ( 2 1 , 2 1 ) ; g r a y p l o t ( x , y ,m) x t i t l e ( ’ Using g r a y p l o t f o r random numbers ’ ) xlabel ( ’x ’ ) ylabel ( ’y ’ )

grayplot.sce

Figure 3.11 shows the color value as per the value of z (which is given by a random number in this case). The graph will result in different plots each time it is run because the value is z is given by a random number. In fact the effectiveness of random number generating algorithm can be visually inspected using grayplot by checking if two colors are situated close-by.

3.3.4

champ

Science and Engineering studies employs the theoretical study of vector fields. Both in theoretical and practical studies, it is sometimes important 63

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.11: grayplot figure for random numbers to plot vector field as per given equation. Vectors are best described by arrows. To provide this facility, champ draws a 2D vector field. The length of the arrows is proportional to the intensity of the field. 1

2 3 4 5 6 7 8 9 10

// Program t o p l o t u s i n g champ f u n c t i o n f o r p l o t t i n g a v e c t o r field x = l i n s p a c e ( −1 ,1 ,10) ; y = l i n s p a c e ( −1 ,1 ,10) ; [ X,Y] = meshgrid ( x , y ) ; f y = 3 . ∗Y; f x = 0 . 5 . ∗X; champ ( x , y , fx ’ , fy ’ ) x t i t l e ( ’ Using champ f u n c t i o n t o p l o t v e c t o r f i e l d ’ ) xlabel ( ’x ’ ) ylabel ( ’y ’ )

champ.sce

Complex polynomials can be used to represent the horizontal and vertical components of the vector field, which are usually measured. champ provides an easy way to visualize the vector field and then deduce about forces arising out of it.

64

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.12: Plotting vector field using champ

1

2 3 4 5 6 7 8 9 10

// Program t o p l o t u s i n g champ f u n c t i o n f o r p l o t t i n g a v e c t o r field x = l i n s p a c e ( −2 ,2 ,10) ; y = l i n s p a c e ( −2 ,2 ,10) ; [ X,Y] = meshgrid ( x , y ) ; f y = X.ˆ3 −2.∗X. ˆ 2 + 4 . ∗X−10; f x = X. ˆ 3 + 2 . ∗X.ˆ2 −4.∗X+10; champ ( x , y , fx ’ , fy ’ ) x t i t l e ( ’ Using champ f u n c t i o n t o p l o t v e c t o r f i e l d ’ ) xlabel ( ’x ’ ) ylabel ( ’y ’ )

champ1.sce

Adding color (indicating field intensity) to the arrows gives more meaningful visual presentation as shown in champcolor.sce 1

2 3 4 5 6

// Program t o p l o t u s i n g champ f u n c t i o n f o r p l o t t i n g a v e c t o r field x = l i n s p a c e ( −1 ,1 ,20) ; y = l i n s p a c e ( −1 ,1 ,20) ; [ X,Y] = meshgrid ( x , y ) ; f y = 3 . ∗Y; f x = 0 . 5 . ∗X;

65

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.13: Plotting vector field using champ

7 8 9 10

champ1 ( x , y , fx ’ , fy ’ ) x t i t l e ( ’ Using champ f u n c t i o n t o p l o t v e c t o r f i e l d ’ ) xlabel ( ’x ’ ) ylabel ( ’y ’ )

champcolor.sce

3.3.5

Contour maps

Contour maps are frequency used to visualize the projection of a function on 2D surface. They are used in various branches of science and engineering, especially geophysics where information of a measurement parameters like temperature, pressure, humidity etc is projected onto a map. Apart from these, contour maps are also used to visualize the 2D mathematical projection on a plane. Scilab provides an in-built function contour2d() for this purpose. Its usage is explaned in example code contour.sce. Detailed usage of the function can be learnt from using the command help contour2d. Essentially the function takes x, y, z values and the value for number of levels. The code produces random number and plots them as per thier value on a 66

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.14: Plotting vector field using champ 2D matrix. 1 2 3 4 5 6 7 8 9

// Program t o p l o t 2D c o n t o u r s x =1:10; y =1:10; z=rand ( 1 0 , 1 0 ) ; l e v e l n u m b e r =8; contour2d (x , y , z , level number ) t i t l e ( ’ P l o t t i n g c o n t o u r map ’ ) xlabel ( ’x ’ ) ylabel ( ’y ’ )

contour.sce The figure 3.15 shows the result of the code. Instead of contour outlines, filled contours can be obtained using the in-built function contourf(). It follows a similar syntax as contour2d() function. 1 2 3 4 5

// Program t o p l o t 2D c o n t o u r s x =1:10; y =1:10; z=rand ( 1 0 , 1 0 ) ; l e v e l n u m b e r =8;

67

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.15: Plotting vector field using champ

6 7 8 9

contourf (x , y , z , level number ) t i t l e ( ’ P l o t t i n g c o n t o u r map ’ ) xlabel ( ’x ’ ) ylabel ( ’y ’ )

contourf.sce

The figure 3.16 shows the result of the code. Similarly color coded area are on same level. Since z values are taken from a random number generator function rand() hence the figure will be different each time the code contourf.sce is run. Contour maps are easier way to visualize the smoothness of 2D data. Smooth data will have little variation and hence will fall under same level. The choice of level range will define the degree of smoothness. For example, suppose an Infra-Red camera measures the temperature of a room and the data is color coded for visual display. Contours will be defined by the different levels of temperature ranges. If the temperature is uniform in a region, it will be coded with similar color. The difference in temperature of that region will be within the range defined and hence definition of range 68

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.16: Plotting vector field using champ will become critical in that case. If minimum and maximum values of temperature are T1 and T2 and number of levels are n then temperature range of a zone is given by |T2 − T1 | n

3.4

2D Animation

During simulation, its is sometimes useful to animate an equation to understand its evolution. Scilab contains very useful function for this purpose. Please note that figure provided below are snapshots-at-the-end for the animations. Users should write the code as discussed below and test on their own to see the animation on a computer monitor. Animations are found to be particularly useful for teaching concepts to students.

3.4.1

comet

comet() function comes handy in such a case. Lets try to animate an equation x5 − x3 + x + 5 using comet function. 1

// Program t o d e m o n s t a r t e u s a g e o f comet

2

69

Dr. Sandeep Nagar [email protected]

www.bookmuft.com 3 4 5 6 7

x=l i n s p a c e (−%pi , %pi , 5 0 0 ) ; comet ( x , %sˆ5−%sˆ3+%s+5) x t i t l e ( ’ Using comet f u n c t i o n t o animate an e q u a t i o n ’ ) xlabel ( ’x ’ ) ylabel ( ’y ’ )

comet.sce

Figure 3.17: Plotting using comet function

3.4.2

paramfplot2d

Time evolution of function at multiple points can be represented by paramfplot2d() function. Lets consider evolution to the fucntion y = sin(x) + sin(2x) + sin(4x) i.e mixing of a signal with double and four times its own frequency. The resulting signal is the complex waves combining these three primary waves (sin(x), sin(2x), sin(4x)): 1

2 3 4 5 6

d e f f ( ’ y=f ( x , t ) ’ , ’ y=t ∗ s i n ( x )+s i n ( 2 ∗ x )+s i n ( 4 ∗ x ) ’ ) // D e f i n i n g equation x=l i n s p a c e (−4∗%pi , 4 ∗ %pi , 1 0 e3 ) ; // d e f i n i n g s p a t i a l s t e p s t =100; t i m e s p e e d = 0 : 0 . 0 5 : 1 ; // s t e p s i z e d e t e r m i n e s s p e e d o f a n i m a t i o n paramfplot2d ( f , x , time speed ) ; x t i t l e ( ’ Using p a r a m f p l o t 2 d f u n c t i o n t o animate an e q u a t i o n ’ )

70

Dr. Sandeep Nagar [email protected] 7 8

www.bookmuft.com

xlabel ( ’x ’ ) ylabel ( ’y ’ )

paramfplot2d.sce

Figure 3.18: Plotting using paramfplot2d function

Please note that, deff is used to define a fucntion. Its usage can be checked from help deff. Its detaield usage will be discussed in chapter concerning definition of scilab function.

3.5

Plotting multiple plots in same graph

Multiple plots can be plotted within the same figure by simply supplying x and y axes vectors. 1

// Program f o r m u l t i p l e p l o t s with l e g e n d s

2 3 4 5 6 7 8

x = linspace (1 ,10 ,30) ; p l o t ( x , x . ˆ 2 , ’ k∗ ’ ) p l o t ( x , x . ˆ 2 . 5 , ’ r− ’ ) p l o t ( x , x . ˆ 3 , ’ b−− ’ ) l e g e n d ( [ ’ x ˆ2 ’ ; ’ x ˆ3 ’ ; ’ x ˆ4 ’ ] ) ; t i t l e ( ’ P l o t t i n g m u l t i p l e p l o t s i n same window ’ )

71

Dr. Sandeep Nagar [email protected]

www.bookmuft.com 9 10

xlabel ( ’x ’ ) ylabel ( ’y ’ )

multi.sce

Figure 3.19: Multiple plots within same figure

Figure 3.19 is obtained by running the code. These types of plots are generally used to check the variation of result by varying a particular parameter.

3.5.1

Plotting multiple plots separately

subplot(row,coloumn, index) command is used to plot multiple plots within the same figure separately. subplot(2,2,4) means that plot will be on 2nd row, 2nd column and 4th index. 1 2

// Program t o show u s a g e o f s u b p l o t f u n c t i o n // s u b p l o t f u n c t i o n p r o d u c e s a f i g u r e a s a matrix

72

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

3 4 5 6 7 8 9 10

x=l i n s p a c e (−2∗%pi , 2 ∗ %pi , 1 0 0 0 ) ; // 1 s t f i g u r e o f a 2X2 f i g u r e matrix subplot (221) plot (x , sin (x) , ’ r∗ ’ ) t i t l e ( ’ Plot f o r s i n (x) ’ ) xlabel ( ’x ’ ) ylabel ( ’ sin (x) ’ )

11 12 13 14 15 16 17

// 2nd f i g u r e o f a 2X2 f i g u r e matrix subplot (222) p l o t ( x , s i n ( x )+s i n ( 2 . ∗ x ) , ’ b∗ ’ ) t i t l e ( ’ P l o t f o r s i n ( x )+ s i n ( 2 x ) ’ ) xlabel ( ’x ’ ) y l a b e l ( ’ s i n ( x )+ s i n ( 2 x ) ’ )

18 19 20 21 22 23 24

// 3 rd f i g u r e o f a 2X2 f i g u r e matrix subplot (2 ,2 ,3) p l o t ( x , s i n ( x )+ s i n ( 3 . ∗ x ) , ’ g ∗ ’ ) t i t l e ( ’ P l o t f o r s i n ( x )+ s i n ( 3 x ) ’ ) xlabel ( ’x ’ ) y l a b e l ( ’ s i n ( x )+ s i n ( 3 x ) ’ )

25 26 27 28 29 30 31

// 4 th f i g u r e o f a 2X2 f i g u r e matrix subplot (2 ,2 ,4) p l o t ( x , s i n ( x )+ s i n ( 4 . ∗ x ) , ’ k∗ ’ ) t i t l e ( ’ P l o t f o r s i n ( x )+ s i n ( 4 x ) ’ ) xlabel ( ’x ’ ) y l a b e l ( ’ s i n ( x )+ s i n ( 4 x ) ’ )

subplot.sce

As seen in figure 3.20, plots are organized as matrix where row number as well as column number dictates its position. Index of the plot can then be used to treat it as an object for further processing on graphical object. Theoretically, the limit to the number of rows and columns is limited to the memory of computer but while printing, user must understand that according to the size of plots, some of them will go outside the print area. Hence judicious usage of this command is recommended. Automatic generation of figure matrix can be achieved by generating the index of plots using a loop (will be discussed in further chapters). 73

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.20: Separate Multiple plots within same figure using subplot

3.6

3D plots

There are various functions available for 3D plotting in octave. Choosing one of them depends on particular problem.

3.6.1

plot3d

The in-built function plot3d() plots a 3D plot for given values of x, y, z defined as arrays. One of its usage is shown in the code plot3d.sce where the equation 3.1 is plotted z= 1

p x2 + y 2

// Program t o p l o t 3D graph u s i n g p l o t 3 d

2 3 4 5 6 7

a = l i n s p a c e ( −8 ,8 ,41) ’ ; b = l i n s p a c e ( −8 ,8 ,41) ’ [ xx , yy ] = meshgrid ( a , b ) ; c = s q r t ( xx . ˆ 2 + yy . ˆ 2 )+%eps ; plot3d (a , b , c )

plot3d.sce

74

(3.1)

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.21: 3D plot of equation

3.6.2

plot3d1

The in-built function plot3d1() plots a colored 3D plot for given values of x, y, z defined as arrays. The colr of cells indicates the z value range. Its usage is shown in the code plot3d1.sce where the equation 3.1 is plotted 1

// Program t o p l o t 3D graph u s i n g p l o t 3 d 1

2 3 4 5 6 7

a = l i n s p a c e ( −8 ,8 ,41) ’ ; b = l i n s p a c e ( −8 ,8 ,41) ’ [ xx , yy ] = meshgrid ( a , b ) ; c = s q r t ( xx . ˆ 2 + yy . ˆ 2 )+%eps ; plot3d1 (a , b , c )

plot3d1.sce

The color coding provided by plot3d1() becomes an additional feature in some critical analysis. The contours in a 3D plot gives the idea about shape of projection areas where the value of measured system is same. For example, suppose the figure 3.22 represents the electric field near a chanrged particle placed at its center. The color represents the zone in 3D where the force on that charged particle will be within a certain range. 75

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.22: 3D plot of equation

3.6.3

plot3d2

Another in-built function plot3d2() builds the 3D graph using rectangular facets. One the example is shown in the code plot3d2.sce. 1

// Program t o p l o t 3D graph u s i n g p l o t 3 d 2

2 3 4 5 6 7 8

u = l i n s p a c e (−%pi / 2 , %pi / 2 , 4 0 ) ; v = l i n s p a c e ( 0 , 2 ∗ %pi , 2 0 ) ; X = cos (u) ’∗ cos ( v ) ; Y = cos (u) ’∗ s i n ( v ) ; Z = s i n (u) ’∗ ones ( v ) ; p l o t 3 d 2 (X, Y, Z ) ;

plot3d2.sce

The result is shown as figure 3.23. It is important to note that making a finer mesh will make the figure with better resolution of its 3D feature. For a finer mesh, the linspace() arguments should be defined with a smaller step size. But at the same time, this increases the computational time. Thus 3D rendering is an computationally inensive task but sometimes desired. The choice of parameters depends upon the requirements of data analysis. When finer resolution of 3D surface features is sought, one has to go for 76

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.23: 3D plot of equation higher rendering power (which directly results in high computational power requirements).

3.6.4

plot3d3

Another in-built function plot3d3() builds the 3D mesh graph using rectangular facets. The only difference between plot3d2 and plot3d3 is that the formet produces a surface plot and latter produces a mesh plot on rectangular facets. One the example is shown in the code plot3d3.sce. 1

// Program t o p l o t 3D graph u s i n g p l o t 3 d 3

2 3 4 5 6 7 8

u = l i n s p a c e (−%pi / 2 , %pi / 2 , 4 0 ) ; v = l i n s p a c e ( 0 , 2 ∗ %pi , 2 0 ) ; X = cos (u) ’∗ cos ( v ) ; Y = cos (u) ’∗ s i n ( v ) ; Z = s i n (u) ’∗ ones ( v ) ; p l o t 3 d 3 (X, Y, Z ) ;

plot3d3.sce

Same arguments apply for the resolution of mesh as that for surface. It is however important to note that rendering a mesh is bit less computationally 77

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.24: 3D plot of equation intensive than rendering a surface.

3.6.5

surface plots

Surface plots are obtained using in-built functions surf() which takes a single argument of height of mesh point. By connecting these mesh point, a surface is created. By default, surface facets are color coded differently to identify them distinguishably. This can be checked in the code surf.sce. 1 2 3 4 5

// Program t o p l o t 3D graph u s i n g s u r f subplot (2 ,2 ,1) z = rand ( 1 0 , 1 0 ) ; surf (z) t i t l e ( ’ surf ’ )

6 7 8 9

subplot (2 ,2 ,2) s u r f ( z , ’ f a c e c o l ’ , ’ red ’ , ’ edgecol ’ , ’ blu ’ ) t i t l e ( ’ s u r f f u n c t i o n with f a c e and edge c o l o r ’ )

10 11 12 13

subplot (2 ,2 ,3) surf (z , ’ facecol ’ , ’ interp ’ ) t i t l e ( ’ surf function interpolated ’ )

14 15

subplot (2 ,2 ,4)

78

Dr. Sandeep Nagar [email protected] 16 17 18 19 20

www.bookmuft.com

x=rand ( 1 0 , 1 0 ) ; y=rand ( 1 0 , 1 0 ) ; z=rand ( 1 0 , 1 0 ) ; s u r f ( z , ’ f a c e c o l ’ , ’ red ’ , ’ edgecol ’ , ’ blu ’ ) t i t l e ( ’ s u r f f u n c t i o n with each c o o r d i n a t e d d e f i n e d s e p e r a t e l y ’ )

surf.sce

Note that when additional arguments about facecolor being red and edge colors being blue are fed, then the plot is plotted with red colored surface having blue colored edges. The input to surf() command is an array. Its is created by the in-built function rand() in this case, but it can be created externally and fed to surf() function.

Figure 3.25: 3D plot of equation

In third subplot, random mesh values are defined by rand() function but intermediate values between two mesh points is interpolated. This results in 79

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

color coding of contours. In fourth subplot, individual cartesian coordinates for (x, y, z), each taken from a rand() function, are fed to surf function seperately.

3.6.6

Mesh plots

Mesh plots are generated by joining mesh points defined by coordinates. As an example, consider the code mesh.sce. 1

// Program t o e x p l a i n t h e u s a g e o f mesh f u n c t i o n

2 3 4 5

[ X,Y]= meshgrid ( − 5 : 0 . 5 : 5 , − 5 : . 5 : 5 ) ; Z=s i n (X)+c o s (Y) ; mesh (X, Y, Z ) ;

mesh.sce

Here a 2D coordinate system is generated and stored in two arrays named X and Y. For these points defining x and y, an equation is defined as follows: z = sin(x) + cos(x)

(3.2)

These three values i.e. one each from arrays x, y, z are fed to mesh function. Result is shown in figure 3.26. The three coordinates i.e (x, y, z) are defined by the corresponding elements of vectors X,Y,Z. These points are used to create the mesh plot.

3.6.7

3D histogram

Just like 2D histograms, 3D histograms give visual clue about segregation of data having 2D dependency. 3D visualization is presented as vertical solid bars. 1

// Program t o make a 3D h i s t o g r a m

2 3 4 5

h i s t 3 d ( 5 ∗ rand ( 1 0 , 1 0 ) ) ; h i s t 3 d (−5∗ rand ( 1 0 , 1 0 ) ) ; t i t l e ( ’ 3D h i s t o g r a m ’ )

hist3d.sce 80

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Figure 3.26: 3D plot of equation An example code is presented in hist3d.sce. Here random numbers are amplifiled and plotted on a 2D matrix. The random numbers generate the height of bar. Two histograms, one each in positive and negavtive quadrant is generated. The result is shown in figure 3.27.

Figure 3.27: 3D histogram

81

www.bookmuft.com

3.7

Dr. Sandeep Nagar [email protected]

Summary

A variety of in-built functions were presented for 2D and 3D plotting as well as animations. With these rich features, Scilab provides a nice developing environment for scientists and engineers. Visualization tools presented in the chapter are comparable to many commercial alternatives. Explaining each and every option for the plots is beyond the scope of this chapter hence only relevant functions have been discussed here. User is advised to study the documentation using the command help plot and see the variety of options for 2D and 3D plotting along with options to modify plot properties.

82

4 Data through File reading and writing

4.1

Introduction

Using the information in the chapter on arrays and on plotting, one can now formulate physical problems in terms of numerical computations and solve them on digital computer. This process includes some requirements such as: • Data should be in digital form (a digital file) • Computer program should be able to read the file and make array without errors. If errors have been made, then a mechanism to check those errors and giving a warning to the user should be in place. Error correction will be an added feature in this case.. • Data should be stored as an array as per the data type and should be displayed on demand in proper format. • Array operations on data will result in memory usage in terms of reading and writing data on disk. This should be facilitated by the system. User should be able to check the status of memory as and when required. • Post-processing tasks includes displaying data in various formats: As a printout from printer, on a terminal, as a graph on terminal or printer/plotter etc. 83

www.bookmuft.com

Dr. Sandeep Nagar [email protected]

• If a report for particular experiment having input parameters, processing data and output as file or graph, can be generated, then it makes the task of user easier. Scilab has some features for each of these steps. Present chapter will discuss them in brief.

4.2

File operations

File operations constitutes an important part of computation. It is important to note that file system is OS (Operating System) dependent. Since LINUX has been the primary operating system for scientific and engineering work, Scilab supports Linux commands for file management. When Scilab is installed on windows too, one uses same commands as that of Linux for dealing with file since one always works in a Scilab micro-environment. Codes written below has been tested on Windows 8, Mac OSX 10.10 and Ubuntu 14.04 systems.

4.2.1

Users

A computing system is accessed by different users. Each user defines a workspace to avoid damaging each other’s work. After login, a user’s workspace becomes active for a user. Scilab does not provide the facility of login for the software but when user logs in his/her OS, his/her workspace for Scilab is activated too. Workspace is made up of various files and folders. Some files are essential for the OS to define the behaviour of system, hence they should not be altered. This is ensured by giving permissions for various users. ”Reading” and ”Writing” a file is restricted by permissions. ”Administrator” (fondly called admin) is also called ”super user” who has all the privileges and permissions to edit any file/folder. One must understand the defined user-type on a particular computer system and then issue commands accordingly. If one is not permitted to access certain folders and input data is placed inside those files/folders, then unless one seeks to change the permission from the admin, one would always get an error. 84

Dr. Sandeep Nagar [email protected]

4.2.2

www.bookmuft.com

File Path

Directory/Folder can contain sub-directories/sub-folders and files again. This can go to any level if this process if not restricted by the administrator. pwd command stands for print working directory. On Scilab terminal, typing pwd displays the path of present working directory as shown in example below. 1 2 3

−−>pwd ans = / Users / sandeepnagar

Under the user, /Users directory, contains another directory named /sandeepnagar. This is the present working space. When pwd is typed on the terminal, a variable name named ans stores this data (file path). A variable name of choice, can be assigned to store the filename as a string. Users may please note that depending on the installation of linux in different systems, the name of directory can be different in different systems, but they will all follows the same architecture. A file/folder is accessed by writing file-path on the terminal. Lets do a small exercise to understand this process. To make a new directory, use mkdir ’name’ as follows: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

−>mkdir s c i l a b ans = 1. −−>cd s c i l a b / ans = / Users / sandeepnagar / s c i l a b −−>mkdir t e s t ans = 1. −−>cd t e s t ans = / Users / sandeepnagar / s c i l a b / t e s t −−> l s ans = [] −−>mkdir new ans = 1. −−> l s

85

Dr. Sandeep Nagar [email protected]

www.bookmuft.com 20 21 22 23 24 25 26 27 28 29 30

ans = new −−>rmdir new ans = 1. −−> l s ans = [] −−> i s d i r ( ’ / U s e r s / s a n d e e p n a g a r / s c i l a b / t e s t ’ ) ans = T

At line number 1, mkdir scilab makes a directory named ”scilab”. To see the contents of the present directory, one can use the command ls, which stands for list. To change directory, one can use the command cd "file path". It is suggested that one works in this directory for rest of the excercises in the present book. One can further make a directory named test in the directory named scilab. One can see the list of its contents by using the command ls. Whent he directory is empty, ans=[] is displayed. If one now creates a new directory named new within the subdirectory test by issuing the command mkdir new, and then checkes for list of contents, the result is shown as ans=new. To remove a directory, one can use the command rmdir. So by executing rmdir new, one can see that user removes the directory named new. The command isdir checks whether the input argument (path) directs to a directory. When directory is found at the input path, output is boolean variable T (True), otherwise the output is F (False).

4.2.3

Creating files and saving them

save and load commands enables one to write and read data to the memory. 1 2 3 4 5

−−>a = rand ( 3 , 3 ) a = 0.2113249 0.3303271 0.7560439 0.6653811 0.0002211 0.6283918

86

0.8497452 0.6857310 0.8782165

Dr. Sandeep Nagar [email protected] 6 7 8 9 10 11 12 13 14

www.bookmuft.com

−−>s a v e ( ’ r a n d m a t r i x . dat ’ , ’ a ’ ) −−> l s ans = ! r a n d m a t r i x . dat ! −−>l o a d ( ’ r a n d m a t r i x . dat ’ , ’ a ’ ) −−>a = 0.2113249 0.3303271 0.8497452 0.7560439 0.6653811 0.6857310 0.0002211 0.6283918 0.8782165

At line number 1, A variable named a is created first, which stored a random values 3 × 3 matrix. At line number 2, this data is stored as a .dat file (data file) named rand_matrix.dat, which is passed the variable name as the argument. When required, this file can be loaded in workspace using load command. Please note that the data need not be numbers always. It can anything which a digital computer can handle, like pictures, videos, strings, character just to name a few. Multiple variables can be stored in the same file by passing the name of variables at the time of saving. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

−−>a = rand ( 2 , 2 ) a = 0.0683740 0.6623569 0.5608486 0.7263507 −−>b = rand ( 3 , 3 ) b = 0.1985144 0.2312237 0.5442573 0.2164633 0.2320748 0.8833888 −−>c = rand ( 3 , 2 ) c = 0.2146008 0.2922267 0.312642 0.5664249 0.3616361 0.4826472 −−>s a v e ( ’ r a n d m a t r i x 1 . dat −−> l s ans = ! r a n d m a t r i x 1 . dat ! ! ! ! r a n d m a t r i x . dat ! −−>l o a d ( ’ r a n d m a t r i x 1 . dat −−>a a =

0.6525135 0.3076091 0.9329616

’ , ’a ’ , ’b ’ , ’ c ’ )

’ , ’a ’ , ’b ’ , ’ c ’ )

87

Dr. Sandeep Nagar [email protected]

www.bookmuft.com 24 25 26 27 28 29 30 31 32 33 34 35

0.0683740 0.5608486 −−>b b = 0.1985144 0.5442573 0.2320748 −−>c c = 0.2146008 0.312642 0.3616361

0.6623569 0.7263507

0.2312237 0.2164633 0.8833888

0.6525135 0.3076091 0.9329616

0.2922267 0.5664249 0.4826472

help save and help load gives very useful instructions about using them. load function follows the same logic as save function. Data can be unzipped and loaded from a particular formatted file as an array. Array thus populated, can be used for computation and resultant files can be made using save function again (if required). Elaborate computations require this procedure to be repeated successively many times, thus the functions have been optimized to locate and load required data in a short time. Opening and closing files To read and write data files, they must be opened and defined as readable and/or writeable. The command mopen() is used to create a non-existent file or to open an existing file. For example, the followsing code shows how to make a file named test.sce in write mode. A variable named file_handle is used to store the event. Listing the contents of the folder, one can see that a file by this name is indeed created. Similar to mopen() command, mclose() is used to clse the file. 1 2 3 4 5 6 7 8

−−>f i l e h a n d l e = mopen ( ’ t e s t . s c e ’ , ’w ’ ) file handle = 1. −−> l s ans = test . sce −−>m c l o s e ( f i l e h a n d l e ) ans =

88

Dr. Sandeep Nagar [email protected] 9

www.bookmuft.com

0.

The mode parameter controls the access type for the file which can have one of the following values: r w a r+ w+ a+

opens opens opens opens opens opens

for for for for for for

reading (default). The file must exist, otherwise it fails. writing. If the file exists, its contents are destroyed. appending. It creates the file if it does not exist. both reading and writing. The file must exist, otherwise it fails. both reading and writing. If the file exists, its contents are destroyed. both reading and appending. It creates the file if it does not exist. Table 4.1: Different file modes

In addition, the following characters can be used to specify the type of file: t b

text file. binary file (default)

Table 4.2: Different file types The default access mode is ’rb’ (binary file reading). ———csvread and csvwrite Functions csvRead and csvWrite are used to read data from .csv filed which stand for comma seperated values. 1 2 3 4 5

−−>a = rand ( 4 , 4 ) ; −−>c s v W r i t e ( a , ’ c s v f i l e d a t a ’ ) ; −−>b = csvRead ( ’ c s v f i l e d a t a ’ ) ; −−>a a =

6 7

column 1 t o 2

8 9 10 11 12

0.3321719 0.5935095 0.5015342 0.4368588

0.2693125 0.6325745 0.4051954 0.9184708

89

www.bookmuft.com

Dr. Sandeep Nagar [email protected]

13 14

column 3 t o 4

15 16 17 18 19

0.0437334 0.4818509 0.2639556 0.4148104

0.2806498 0.1280058 0.7783129 0.2119030

20 21 22

−−>b b =

23 24

column 1 t o 2

25 26 27 28 29

0.3321719 0.5935095 0.5015342 0.4368588

0.2693125 0.6325745 0.4051954 0.9184708

30 31

column 3 t o 4

32 33 34 35 36

0.0437334 0.4818509 0.2639556 0.4148104

0.2806498 0.1280058 0.7783129 0.2119030

The functions to write an read a .csv file has a number of options which can be understood by using the command help csvRead and csvWrite. User is encourages to explore the options as .csv files are abundantly used in the domain of data analytics. Using and manipulating them is an important skill of a data scientist. Note: A number of other functions to read and write files exist, but the present section focuses on some of the most commonly used ones. Documentation can be accessed to know about using these specialized functions, if required.

4.3

Summary

In present chapter, various functions enabling reading and writing permission as well as taking data to and from a file, has been illustrated. This becomes an essential part of a numerical computation exercise. The data 90

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

can be generated in the form of files using a software or hardware (an instrument). Scilab does not care for its origin. It treats data by its type and by file-type. Judging an appropriate function to operate using files, has to be done by the user as per the situation. File operation does provide faculties to trim the data so that only useful part of data is fed as an array. Further trimming can be performed by slicing operations. With the art of handling files, one can confidently proceed towards handling sophisticated numerical computations.

91

www.bookmuft.com

92

Dr. Sandeep Nagar [email protected]

5 Functions and loops

5.1

Introduction

When a particular numerical tasks needs to be ”repeated” over different data points, digital computers becomes a useful tool since they can perform the same, with greater speeds than humans. Loops perform exactly this tasks. Using a condition to check the start and termination rules, one can perform repetitive parts of a process as desired. Different programming languages and environments have different rules of defining loops. Scilab provides a much simpler way to define and run loops. Apart from loops, functions also defines an important part of modern programming architecture. A big program may require a set of instructions to be called at different times. Hence these set of instructions can be defined as a sub-program, which can be requested to perform the computation at a desired time. In this way, a complicated task can be divided into many small parts. This architecture of programming is called modular programming. This is the most popular way of programming since its quite logical, better at visualizing the problem and easy to debug. The most popular way of defining the these small set of instructions is to define them as functions. Together, functions and loops, breaks the numerical computation problem into series of simpler 93

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

problems which can be accessed as per requirement. Present chapter will discuss both these concepts in details.

5.2

Loops

Loops form an essential part of an algorithm since they perform the tasks which computers perform best: doing repetitive actions in a very fast manner. Loops can come in many flavors like for loop which repeats certain tasks over a list of variable values, while loop which checks a logical condition before executing certain task and if-then-else loop which checks a condition and directs the flow of algorithm. Choice of a particular loop depends on the problem at hand. A variety of functions and their usage is listed below. Judging their usage critically becomes supremely important because the looping part of algorithm consumes most of execution time.

5.2.1

while

while loop defines a logical condition and until it is satisfied, it run a block of code. The syntax for while loop is: 1 2 3

while condition BODY endwhile

Here the keyword while initiates the execution of a while loop. The condition is a logical condition whose answer can be ’true’ (1) or ’false’ (0). The BODY encompasses the st of commands which is executed until the condition holds true. 1 2 3 4 5

i = 1 w h i l e i e x e c ( ’ / U s e r s / s a n d e e p n a g a r / . . . / w h i l e . s c e ’ , −1) 1. 2. 4. 8. 16

The code while.sce first initialize the variable i to the numerical value 1. It then checks the condition i < 20. This is true at first step when i = 1. hence it enters the loop and executes the command disp(i) i.e. displays the value of i on the Scilab terminal i.e. the numerical value 1 is printed on the terminal. Then the next line is executed i.e. i = i ∗ 2 which makes the new value of i=2. At the end of loop, the control is further taken by the condition statement i.e. i < 20. Untill this holds true, the loop runs and hence 1, 2, 4, 8, 16 are printed. When i = 16 and then the statement i = i ∗ 2 is executed, the new value of i becomes 32. Now the condition is not satisfied and hence the loop is terminated.

5.2.2

Infinite loops

Some loops can run infinitely, and hence they are called infinite loops. Try the code while.sce by initiatilizing i = 0 instead of i = 1. In this case, the value of i will always be 0 inside the loop and the condition i < 20 will always be true. Hence the code will run forever, unless interrupted. Infinite loops can be interrupted by Ctrl+C key combination on an ASCII keyboard. The onus of avoiding infinite loop lies on the user. Scilab will simply execute the statements mindlessly without showing a warning or error message. Technically, infinite loops are not programming errors as they are syntactically correct. In-fact, infinite loops can be used in case one needs to generate an infinite stream of data or the case where one needs to execute a Scilab program infinitely. For example, suppose a scilab program reports the status of a remote wind turbine. This code needs to run infinitely unless interrupted. In another scenario, suppose an application required a stream of random numbers. In this case, scilab code can be written to generate an infinite sequence of random numbers. 95

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

5.2.3

for

for loop is used to perform computation on a list of known values. The syntax of for loop is: 1 2 3

for variable = vector BODY end

The keyword for declared the starting of loop where a variable takes the values stored in a vector. Then a body of code (here represented by BODY) is executed. The keyword end declares end of for loop. This is explained in the example below: 1 2 3 4

f o r i =1:10 square root = sqrt ( i ) ; disp ( square root ) end

5 6

d i s p ( ” Program f i n i s h e d ” )

for.sce

Executing for1.m yields: 1 2 3 4 5 6 7 8 9 10 11 12

−−−>e x e c ( ’ / U s e r s / sandeepnag . . . / f o r . s c e ’ , −1) 1. 1.4142136 1.7320508 2. 2.236068 2.4494897 2.6457513 2.8284271 3. 3.1622777 Program f i n i s h e d

Here the for statement creates a vector of numberals from 1 to 10 and stores it ina variable named i. Each member of this vector is fed to the body of loop. Here a variable named square_root stores the square root of the 96

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

value stored in the array. Its is then printed on Scilab terminal using the command disp(square_root). When these two commands are finished, next member of the vector is picked and same is repeated. This is continued till the last member of the vector stored in variable named i i.e. i = 10.

5.2.4

if-elseif-else

Situation where a number of conditions needs to be checked at different points of times, if-elseif-else loop works well. The syntax for the loop is given by: 1 2 3 4 5 6 7

i f condition1 BODY1 e l s e i f condition2 BODY2 else BODY3 endif

At line 1, a condition is defined. If this condition is satisfied then the line 2 is executed or else line 3 is executed. Hence BODY1, BODY2 are the blocks of codes which are executed by checking for different set of conditions and BODY3 set of codes is executed in the case when none of the condition is executed. 1 2 3 4 5 6 7 8

i=rand ( 1 , 1 ) ; i f i > 0 . 5 then disp ( i ) ; d i s p ( ” True ” ) ; else disp ( i ) ; disp (” False ”) ; end

ifelse.sce

Running the code yields: 1 2 3 4 5

−−−>e x e c ( ’ / U s e r s / s a n d e e p n a g a r / . . . / i f e l s e . s c e ’ , −1) 0.5376230 True −−−>e x e c ( ’ / U s e r s / s a n d e e p n a g a r / . . . / i f e l s e . s c e ’ , −1) 0.1199926

97

Dr. Sandeep Nagar [email protected]

www.bookmuft.com 6 7 8 9

False −−−>e x e c ( ’ / U s e r s / s a n d e e p n a g a r / . . . / i f e l s e . s c e ’ , −1) 0.2256303 False

Whenever the value of random number is more than 0.5 then True is printed and False is printed otherwise. 1 2 3 4 5 6 7 8 9 10 11

i=rand ( 1 , 1 ) ; i f i > 0 . 5 then disp ( i ) ; d i s p ( ” Value i s l a r g e r then 0 . 5 ” ) ; e l s e i f i > 0 . 3 then disp ( i ) ; d i s p ( ” v a l u e i s l a r g e r than 0 . 5 and 0 . 3 ” ) ; else disp ( i ) d i s p ( ” v a l u e i s s m a l l e r than 0 . 5 ” ) end

ifelseif.sce Executing the code ifelseif.sce one obtains the following results on Scilab terminal. 1 2 3 4 5 6 7 8 9 10 11 12 13

−3−>e x e c ( ’ / U s e r s / s a n d e e p n a g a r 0.0485566 v a l u e i s s m a l l e r than 0 . 5 −3−>e x e c ( ’ / U s e r s / s a n d e e p n a g a r 0.6723950 Value i s l a r g e r then 0 . 5 −3−>e x e c ( ’ / U s e r s / s a n d e e p n a g a r 0.2017173 v a l u e i s s m a l l e r than 0 . 5 −3−>e x e c ( ’ / U s e r s / s a n d e e p n a g a r 0.3911574 v a l u e i s l a r g e r than 0 . 5 and 0.3

5.3

/ . . . / i f e l s e i f . s c e ’ , −1)

/ . . . / i f e l s e i f . s c e ’ , −1)

/ . . . / i f e l s e i f . s c e ’ , −1)

/ . . . / i f e l s e i f . s c e ’ , −1)

Functions

Function is a set of code which can be called as and when required. Hence it can be defined separately either in a separate file or within the body of 98

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

program. A script file is similar in nature. A script file stores a sequence of commands to be executed. It seems that function and script have similar R and Octave, Scilab provides separate kinds nature but, unlike MATLAB of files from each one of them. This is based on the nature of their behaviour with core Scilab program. Whereas a script file (with extension .sce) is an executable, a fucntion file (with extension .sci) stores a set of instructions. The function file behaves like a black box where input is fed and output is obtained whereas a script file changes its behaviour as per input values. Whatever input data a script file accesses is taken from Scilab workspace. Output data from a script file is put into Scilab workspace. The semantics of input data, local variables are visible only within the function. ————– The definition of a function follows the syntax: 1 2 3 4 5 6

f u n c t i o n [ o1 , o2 , . . . ] = f u n c t i o n n a m e ( i 1 , i 2 , . . . ) statement 1 statement 2 ... statement n endfunction

Here function keyword defines the object types as function. Then a set of variables are defined which this function is expected to return (o1,o2,... signifying output1, output2,...). Next comes an = operator. Then the name of function. In above case its function_name. Name objects takes a set of arguments which are objects using which the function is defined (i1,i2,... signifying input1,input2,...). Then comes the main body of function where commands for executing the purpose of function are mentioned. The last statement endfunction signifies the end of function. For example, one can write a function to find x2 − y 2 and assign it to variable name z. 1 2 3

function y = fn1 (a , b) y = a ˆ2 − b ˆ 2 ; endfunction

fn1.sci 99

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

Notice that the extension of above code is .sci. This file must first be loaded in Scilab workspace. One needs to provide the full path of file to the in-built function exec() as below first and then use the fucntion by providing its name with input arguments. 1 2 3 4

−−−>e x e c ( ’ / U s e r s / s a n d e e p n a g a r / . . . / f n 1 . s c i ’ , −1) −−−>f n 1 ( 2 , 3 ) ans = − 5.

It is a good practice to define the program as a group of function files and call them in the master program stored as a script file. This modular approach makes it easy to experiment with the idea and also makes it easier to debug and test the code. A function can return more than two values too. For example: 1 2 3 4 5

f u n c t i o n [ y1 , y2 , y3 ] = f n 2 ( x , y ) y1 = x − y ; y2 = x + y ; y3 = y − x ; endfunction

fn2.sci

This gives the following result: 1 2 3 4 5 6 7 8

−−−>e x e c ( ’ / U s e r s / s a n d e e p n a g a r / . . . / f n 2 . s c i ’ , −1) −−−>[a , b , c ]= f n 2 ( 2 , 3 ) c = 1. b = 5. a = − 1.

Functions can incorporate loops to regulate the repetitive tasks inside the program. For example, factorial of a number can be calculated using a function given below: 100

Dr. Sandeep Nagar [email protected] 1 2 3 4 5 6 7 8

www.bookmuft.com

function result = f a c t o r i a l 1 (n) i f ( n == 0 ) result = 1; return ; else r e s u l t = prod ( 1 : n ) ; end endfunction

factorial1.sci A function named factorial1, which takes a number n as an argument calculates the product of number with all its successive numbers. When called from octave command line, the function yields the following result. 1 2 3 4 5 6 7

−−−>e x e c ( ’ / U s e r s / s a n d e e p n a g a r / . . . / f a c t o r i a l 1 . s c i ’ , −1) −−−>f a c t o r i a l 1 ( 1 0 ) ans = 3628800. −−−>f a c t o r i a l 1 ( 1 0 e5 ) ans = Inf

5.3.1

Inline functions

An inline function is a short function that can be defined without having to use the function skeleton discussed in Session 10. This is useful only when the body of the function is short. 1 2 3 4

−−−>d e f f ( ’ [ x]= mult ( y , z ) ’ , ’ x=y∗ z ’ ) −−−>mult ( 2 , 3 ) ans = 6

The in-built function deff() is used to define an inbuilt fucntion. The first argument of deff defines the output variable (x here), function name (mult) and input variables (y,z here). The second argument defines the body of fucntion (x=y*z). This kind of fucntion are defined in a .sce just like a command and hence do not need a separate loading action. Once defined, they can be called by thier function name along with input parameters. 101

www.bookmuft.com

5.4

Dr. Sandeep Nagar [email protected]

Summary

Defining functions is the key to modular programming. Scilab presents an elegant way to define and use functions both inline and in separate files. When combined with the ability to write functions inside a loop, complex problems can be implemented in few lines of codes. It requires an artistic attitude while designing an algorithm where functions and loops are the paintbrush to devise an elegant solutions to a given numerical problem.

102

6 Numerical Computing formalism

6.1

Introduction

Numerical computation enables us to compute solutions for physical problems, provided we can frame them into a proper format. This requires certain considerations. First and foremost is the understanding of approximate solutions. For example, if we digitize continuous functions, then we are going to introduce certain errors due to the sampling at a finite frequency. Hence a very accurate result would require very fast sampling rate. In cases when a large data set needs to be computed, it becomes computationally intensive and time consuming task. One must understand that the numerical solutions are an approximation at best, compared to analytical solutions. The onus of finding their physical meaning and significance lies on user. The art of discarding solutions which do not have a meaning for real world scenario, is something which a scientist/engineer develops over the years. Also, a computational device is just as intelligent as its operator. The law of GIGO (Garbage-In-Garbage-Out) is followed very strictly in this domain. In the present chapter, we shall try to understand some of the important steps one must consider to solve a physical problem using numerical com103

www.bookmuft.com

Dr. Sandeep Nagar [email protected]

putation. Defining a problem in proper term is just the first step. Making the right model and then using the right method to solve (solver) enables to distinguish between a naive and experienced scientist/engineer.

6.2

Physical problems

Everything in our physical world is governed by physical laws. Owing to men and women of science who toiled under difficult circumstances and came up with fine solutions to phenomenon happening around us, we obtained mathematical theories for physical laws. To test these mathematical formalisms of physical laws, we use computational techniques. Analytical computation involves solving using symbols. Numerical computation instead involves solving using computers which follow binary logic. Both approaches have their limitations. Whereas analytical solutions are very accurate, they are difficult to derive especially if pre-defined framework is absent. On the other hand, numerical solutions are always an approximations to real values. In any case, if the computation yields the same results as that of a real experiment, they validate each other. Numerical simulations can remove the need of doing an experiment altogether provided we have a well tested mathematical formalism. For example, nuclear powers of our times need not test nuclear bombs for real any more. The data about nuclear explosion, which was obtained during real nuclear explosions, enabled scientists to model these physical systems quite accurately, thus eliminating the need to a real testing. Apart from applications like simulating a real experiment, modelling physical problems are good educational exercises. While modelling, hands-on exercises enables students explore the subject in depth and give a proper meaning of topic under study. Solving numerical problem and visualization of results makes the learning permanent and also ignites the research about flaws in mathematical theory which ultimately leads to new discoveries.

6.3

Defining a model

Modelling means writing equations for a physical system. As the name suggests, an equation is about equating two sides. An equation is written using an = sign where terms on left hand side is equal to term on right hand side. The terms on either sides of equations can be numbers or expressions. For example: 104

Dr. Sandeep Nagar [email protected]

www.bookmuft.com 3x + 4y + 9z = 10

This is an equation having a term 3x + 4y + 9z on left hand side (LHS) and a term 10 on right hand side (RHS). Please note that whereas LHS is an algebraic term, RHS is a number. Expressions are written using functions which is simply a relation between two domains. Like f (x) = y is a relation from y to x using rules of algebra. Mathematics has a rich library of functions using which one can make expressions. Choice of proper functions depend on problem. Some functions describe some situations best. For example, oscillatory behaviour can be described in a reasonable manner using trigonometric functions like sin(x), cos(x) etc. Objects moving in straight lines can be described well using linear equations like y = mx + c where x is their present position, m is constant rate of change of x w.r.t y and c is the offset position. Objects moving in a curved fashion can be described by various non-linear functions (where power of dependent variable like x above, is not 1). In real life we can have situations which can be mixture of these scenarios. Like an object can oscillate and move in curved fashion at the same time. In that case we write an expression using mixture of functions or find new functions which could explain the behaviour of object. Verification of these choices of functions is done by finding solutions to equations describing the behaviour and matching it with observations taken on object. If they match perfectly, we obtain perfect solutions. In most cases, an exact solutions might be difficult to obtain. In these cases, we get an ”approximate” solution. If the errors involved while obtaining an approximate solution are within tolerance limits, the models can be acceptable. As discussed above, physical situations can be analytically solved by writing mathematical expressions in terms of functions involving dependent variables. Simplest problems have simple functions between dependent variables with a single equation. There can be situation where multiple equations are needed to explain a physical behaviour. In case of multiple equations being solved, the theory of matrix comes handy. Suppose equations below define the physical behavior of a system: 105

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

−x + 3y = 4

(6.1)

2x − 4y = −3

(6.2)

Then this system of two equations can be represented by a matrix equation as follows:       −1 3 x 4 + = 2 −4 y 3 Now using matrix algebra, values of variables x and y can be found such that they satisfy the equations. Those values are called roots of these equations. These roots are the point in 2-D space (because we had 2 dependent variables) where the system will find stability for that physical problem. In this way, we can predict the behaviour of system without actually doing an experiment. Mathematical concept of differentiation and integration becomes very important where we need to work with dynamic system. When the system is constantly changing the values of dependent variables to produce a scenario, then its important to know the rate of change of these variables. When these variables are independent of each other, we use simple derivatives to define their rate of change. When they are not independent of each other, we use partial derivatives for the same. For example, Newtons second law of motion indicates that rate of change of velocity of an object is directly proportional to the force applied on it. Mathematically: dv (6.3) dx The proportionality is turned into equality by substituting for a constant of multiplication m such that: F ∝

F =m×

dy dx

(6.4)

If we know values or expressions for F , this equation can be solved analytically and solutions can be found to this equation. But in some cases, the analytical solution may be too difficult to obtain. In those cases, we digitize the system and find a numerical solution. 106

Dr. Sandeep Nagar [email protected]

www.bookmuft.com

There are many methods to digitize and numerically solve a given function. Programs to implement a particular method to solve a function numerically, is called a solver. A lot of solvers exist to solve a function. Choice of solver is critical to successfully obtain a solution. For example, equation 6.4 is a differential equation. It is a first order ordinary differential equation. A number of solvers exist to solve it like Euler, Runge-Kutta etc. Choice of particular solver depends on accuracy of its solution, time taken for obtaining a solution and amount of memory used during the process. The latter is important where memory is not an freely expendable commodity like micro-computers with limited memory storage (ex: RaspberryPi). The advantage of using Scilab to perform a numerical computation lies in the fact that it has a very rich library of functions to perform various tasks required. The predefined functions has been optimized for speed and accuracy (in some cases, accuracy can be predefined). This enables the user to rapidly prototype the problem instead of concentrating on writing functions to do basic tasks and optimizing them for speed, accuracy and memory usage.

6.4

Scilab Packages

A number of packages exist to perform numerical computation in a particular scientific domain. Scilab uses ATOMS package manager for managing (installing, deleting and updating) a Scilab package. The website https://wiki.scilab.org/ATOMS describes its usage. Clicking on the Menu item Applications -> Module Manager ATOMS opens up the ATOMS (AuTomatic mOdules Management for Scilab) package manager. It lists a variety of specialized modules for Scilab. It is frequenctly updated with new developments. One can select a package by clicking on its name and install using the install button. In similar way, one can uninstall the same. One can also perform these actions using Scilab command line too.

6.4.1

Searching a package

If one knows the name of package, one can search for the same using the command: 1

−−>atomsSearch ( ” c o s e l i c a ” )

107

www.bookmuft.com 2 3 4 5 6 7 8 9

Dr. Sandeep Nagar [email protected]

ans = ! c o s e l i c a Standard Open M o d e l ic a B l o c k s ! −−>atomsSearch ( ” a r d u i n o ” ) ans = ! a r d u i n o Arduino Communication through S e r i a l −−>atomsSearch ( ” r a s p b e r r y p i ” ) ans = []

!

Whereas the module names coselica and arduino could be found, module name raspberrypi returned an empty string i.e. it could not be found.

6.4.2

Installing a package

The commands to install a module uses an in-built function atomInstall() as follows: 1 2 3

−−>atomsSearch ( ” a r d u i n o ” ) ans = ! a r d u i n o 1.1 −1 u s e r SCIHOME\ atoms \ x64 \ a r d u i n o \1.1 −1

I

!

The returned argument shows the version number of module as well as the path at which it is stored. Module is loaded during the next-startup run of Scilab automatically. To load a module manually, one can use the command atomsLoad("arduino")

6.4.3

Removing a package

The in-built function atomsRemove("arduino") can be used to remove the package arduino.

6.4.4

Listing packages

The in-built function atomsList can be issued at the command line to obtain a detailed list of packages sorted in alphabetical order. 108

Dr. Sandeep Nagar [email protected]

6.5

www.bookmuft.com

XCOS

One of the most attractive feature of Scilab (which is absent in other MATR LAB’s alternative namely Octave) is XCOS graphical programming enviR ronment. It is similar to MATLAB’s graphical programming environment called Simulink. Detailed discussion about simulink is left for next series of book on the same but users are encouraged to explore the same by clicking on Menu items Applications -> Xcos. Being graphical in nature, the speed of development for modelling a physical system improves many order’s of magnitude.

6.6

Summary

Almost all branch of science and engineering requires one to perform numerical computation. Scilab is one of the alternative to do so. Scilab has a rich library of optimized functions for general computation which is growing day-by-day as developers all around the world are contributing to the effort. Also it has a variety of packages are present to perform a specialized job. This makes it an ideal choice for prototyping a numerical computation problem efficiently.

109