Scilab Quick Reference (Early Access)
Engr. Allan Jay L. Baco
1
Scilab Quick Reference (Early Access) i
Last Modified Date: March 20, 2009
Contents
1 Scilab Basics 31.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 Definition of terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.4 Mode of Scilab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.5 Some useful windows in Scilab . . . . . . . . . . . . . . . . . . . . . . . 41.6 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Basic data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Editing variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Scalar computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Continuing long command . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.7 Boolean expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131.8 Built-in math functions and variables . . . . . . . . . . . . . . . . . . . 131.9 Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Matrix construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Matrix operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Elementwise operation . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Expanding a matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Submatrix extraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Replacing a submatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Deleting matrix or submatrix . . . . . . . . . . . . . . . . . . . . . . . 27Deleting submatrix with matrix as index . . . . . . . . . . . . . . . . . 28Matrix manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Element lookup in a matrix . . . . . . . . . . . . . . . . . . . . . . . . 29Auto-generation of matrices . . . . . . . . . . . . . . . . . . . . . . . . 32Kinds of matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.10 Special types of matrices . . . . . . . . . . . . . . . . . . . . . . . . . . 36List, Struct and Typed List . . . . . . . . . . . . . . . . . . . . . . . . 36Other special types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Scilab Quick Reference (Early Access) ii
1.11 Miscellaneous functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 401.12 Formatting numeric precision display . . . . . . . . . . . . . . . . . . . 401.13 Basic of polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Constructing polynomial symbolically . . . . . . . . . . . . . . . . . . . 44Constructing polynomial via roots . . . . . . . . . . . . . . . . . . . . . 45Constructing polynomial via coefficients . . . . . . . . . . . . . . . . . 45Polynomial operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Polynomial manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . 45
1.14 Evaluating a function in string form . . . . . . . . . . . . . . . . . . . . 471.15 Complex numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Complex construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48Complex operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Complex manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Complex matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
1.16 Basic of plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51Customizing plot properties graphically . . . . . . . . . . . . . . . . . . 51
1.17 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
2 Programming Basics 582.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582.2 Definition of terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592.4 Scipad editor window . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592.5 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622.7 Nested function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642.8 Multiple functions in one file . . . . . . . . . . . . . . . . . . . . . . . . 652.9 Mixed scripts and functions . . . . . . . . . . . . . . . . . . . . . . . . 662.10 Inline function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672.11 Sequential statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
if-elseif-else-end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68select-case-else-end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
2.12 Looping statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71for-loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71while-loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
2.13 Nested loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Scilab Quick Reference (Early Access) iii
2.14 Using break and continue in a loop . . . . . . . . . . . . . . . . . . . . 742.15 Variable input and output arguments . . . . . . . . . . . . . . . . . . . 752.16 Reading input and displaying output . . . . . . . . . . . . . . . . . . . 782.17 Formatting output display . . . . . . . . . . . . . . . . . . . . . . . . . 792.18 Reading and writing data to a file . . . . . . . . . . . . . . . . . . . . . 802.19 Error handling and exceptions . . . . . . . . . . . . . . . . . . . . . . . 832.20 Character and string manipulations . . . . . . . . . . . . . . . . . . . . 84
Executing a command enclosed in a string . . . . . . . . . . . . . . . . 84Regular Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
2.21 Date and time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 862.22 Miscellaneous functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 862.23 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3 Plotting Basics 913.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913.2 Definition of terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913.4 Basic plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 923.5 plot2d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
plot2dx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 953.6 Plotting a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 963.7 Customizing plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Grids and ticks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96Label and title . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Legend and caption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Multiple plot in a graphics window . . . . . . . . . . . . . . . . . . . . 101Adding text in a plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102Capturing points from the plot . . . . . . . . . . . . . . . . . . . . . . 104Drawing plot later . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106Customizing plot graphically . . . . . . . . . . . . . . . . . . . . . . . . 106
3.8 Animating 2D plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1063.9 Other types of plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Data plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109Surface plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Scilab Quick Reference (Early Access) iv
Polygon plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1103.10 Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1103.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
4 Dialogs 1154.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1154.2 Definition of terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1154.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1154.4 messagebox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1154.5 progressionbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1164.6 waitbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1164.7 x dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1164.8 x mdialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1184.9 x choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1194.10 x choose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1204.11 x matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1214.12 Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
5 Graphical User Interface 1265.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1265.2 Definition of terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1265.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1265.4 UI controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1265.5 Figure properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1265.6 UI properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1265.7 Layouting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Layouting Figure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129Layouting UI controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129Layouting Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
5.8 Callback functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1295.9 Other useful dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1295.10 Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Scilab Quick Reference (Early Access) v
List of Tables
1 Basic data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Variable types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Boolean variable, comparison operator, and boolean functions . . . . . 144 Math built-in variables and functions . . . . . . . . . . . . . . . . . . . 155 Operators used in matrix operation . . . . . . . . . . . . . . . . . . . . 176 Operators used in elementwise matrix operation . . . . . . . . . . . . . 197 Operators and syntax used for extracting element or submatrix . . . . 228 Functions used to manipulate a matrix . . . . . . . . . . . . . . . . . . 309 Functions and syntax for searching elements in a matrix that satisfies a
criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3110 Functions used to generate a matrix . . . . . . . . . . . . . . . . . . . . 3311 Kinds of matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3612 List, struct and tlist . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3713 Functions used for creating and manipulating a special matrix . . . . . 3914 Other functions used to manipulate a number in scilab . . . . . . . . . 4115 Formatting functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4216 Operators used in polynomial operation . . . . . . . . . . . . . . . . . . 4617 Functions used to manipulate a polynomial . . . . . . . . . . . . . . . . 4618 Functions used to manipulate complex numbers . . . . . . . . . . . . . 4919 Transposing a complex matrix . . . . . . . . . . . . . . . . . . . . . . . 5020 Functions used for plotting and customizing plot . . . . . . . . . . . . . 5121 Break and continue statement for loop . . . . . . . . . . . . . . . . . . 7422 Variable input and output . . . . . . . . . . . . . . . . . . . . . . . . . 7523 Input data from user and display . . . . . . . . . . . . . . . . . . . . . 7824 Formatting printing of output . . . . . . . . . . . . . . . . . . . . . . . 7925 Placeholder for printf . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8026 External file processing . . . . . . . . . . . . . . . . . . . . . . . . . . . 8127 Error handling commands . . . . . . . . . . . . . . . . . . . . . . . . . 8328 String processing syntax . . . . . . . . . . . . . . . . . . . . . . . . . . 8529 Executing scilab command in string form . . . . . . . . . . . . . . . . . 8530 Regular expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8531 Date and time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8732 Miscellaneous functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 8833 Line specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Scilab Quick Reference (Early Access) vi
34 Plot2d properties and property values . . . . . . . . . . . . . . . . . . . 9435 Plot2dx series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9636 Grids and ticks property . . . . . . . . . . . . . . . . . . . . . . . . . . 9737 Adding label to the plot . . . . . . . . . . . . . . . . . . . . . . . . . . 10138 Legends and captions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10139 Multiple plot in a single graphics window . . . . . . . . . . . . . . . . . 10240 Adding text to the plot . . . . . . . . . . . . . . . . . . . . . . . . . . . 10341 Capture points in a plot using mouse click . . . . . . . . . . . . . . . . 10542 Drawlater commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10543 Miscellaneous functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 10644 Animate plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10645 Other types of plotting data . . . . . . . . . . . . . . . . . . . . . . . . 10946 Surface plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10947 Polygon plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11048 Dialog boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11749 Progress bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11750 Waitbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11751 UI control styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12752 Figure properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12753 Basic properties of UI control styles . . . . . . . . . . . . . . . . . . . . 12754 Other UI properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12855 Callback functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Scilab Quick Reference (Early Access) vii
List of Figures
1 Scilab Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Scilab console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Scilab editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 Help window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Graphics Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 Scicos Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Variable editor window . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Axes properties editor menu . . . . . . . . . . . . . . . . . . . . . . . . 529 Axes properties editor window . . . . . . . . . . . . . . . . . . . . . . . 5310 Sample plot output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5411 Scipad editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6012 Plot output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9313 Plot2d sample plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9514 Multiple plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10315 Text to a plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10416 Axes properties editor menu . . . . . . . . . . . . . . . . . . . . . . . . 10717 Axes properties editor window . . . . . . . . . . . . . . . . . . . . . . . 10818 Digital signal plot output . . . . . . . . . . . . . . . . . . . . . . . . . . 11219 messagebox sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11620 progressionbar sample . . . . . . . . . . . . . . . . . . . . . . . . . . . 11621 waitbar sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11822 xdialog sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11823 x mdialog sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11924 x choices sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12025 x choose sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12126 x matrix sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Scilab Quick Reference (Early Access) Acknowledgment viii
Acknowledgment
First and foremost, I would like to say thank you to our Lord God for giving mesuch patience to pursue this handbook.
To start, I want to extend my gratitude to God’s disciple who help me out with theevaluation of this handbook. Starting with my one and only younger brother, Allen,for his loving support and continuing loyalty to me. When I finished the first draft ofchapter 1 and chapter 2, he is my first student to evaluate my work. Thanks to him, Idid a lot of corrections and additional subsections to include in each chapter which isvery relevant.
To my parents who did love me unconditionally and support any work I made, mayit be beneficial or not to them or to me as long as I am enjoying of what I am doing.Their support, both of them, are incomparable that gives me the fighting spirit to finishthis handbook.
To the people who evaluates this handbook thanks to all of you guys. From ECE172 and ES 84 batch 2008-2009 2nd semester. To Rogelio who learn Scilab using thisas a reference important additional subsection such as function in string is added.
Thanks to my experience in MATLAB it really help me a lot. Influences me tooutline the topics as it is.
Scilab Quick Reference (Early Access) Preface ix
Preface
Scilab can be used to simulate engineering applications such as Control systems,power system application, numerical methods and other advance engineering math ap-plications. But for the sake of a minified handbook the discussion will be limited tominimal capabilites of Scilab. Every end of the chapter provides exercise problems toassess your skill.
This is a minified1 handbook for Scilab programming serve as a quick reference forlearning Scilab programming. Inside are not just the proper syntax but also the tricksof code used to simplify commands.
This handbook is divided into two volumes outlined below.
Volume 1 covers:
Chapter 1, Scilab Basics, serve as a quick start for using Scilab in the areas ofmathematical operations, matrix manipulation, complex numbers, polynomials andplotting. Some topics are tackled in detail in a separate chapter such as plotting forfurther discussion.
Chapter 2, Programming Basics, discusses the basic syntax of creating a function orscript. Sample code are also provided for live testing. Some features of character andstring manipulation are also included.
Chapter 3, Plotting Basics, shows the different and easiest way of plotting a dataand dynamic setting of its properties.
Chapter 4, Dialogs, shows how to use popup dialogs to display visually the results.Chapter 5, Graphical User Interface, extends the dialog boxes into a pack of user
interfaces that interacts with user actions such as entering text, clicking a button, up-dating a slider, etc. GUI programming concerns about the visual user interface and itscorresponding layout and arrangement in a graphics window.
Volume 2 covers extra toolboxes such as:
Chapter 6, Symbolic Operation using Maxima.Chapter 7, Java Interface.
1Minified is a term borrowed from jquery.com referring to a compact form of the script
Scilab Quick Reference (Early Access) Preface x
Chapter 8, MS Excel Interface.Chapter 9, Optimization Toolbox.Chapter 10, Creating a Toolbox.
What Scilab Can Do
One of the advantage of Scilab is its batch calculation through matrix operation.That is, you can apply an operation to each element of set of data in a single call. Scilabcan be interfaced with other languages such as C++, Java and Fortran but only Javainterface is discussed in Volume 2. Matlab has its own way of increasing computationperformance but in terms of memory consumption, Scilab is more lightweight thanMatlab. For optimized performance, scilab console can be used. Programming alsois very handy in Scilab with its enhanced editor features such as code completion,colorizer and proper indentation. Unlike Java or C/C++, Scilab codes are no longercompiled but rather interpreted right away. Programming concepts such as conditionalstructures, looping, types, arrays are somewhat similar to Java/C/C++ languages butwith some differences on handling iterations like in for-loop that iterates only once.Scilab is designed to be used as a software in numerical methods course. Some otherfeatures of Scilab is 3D plotting, block diagram using Scicos, and more toolboxes relatedto the fields of engineering, control systems, accounting, business, math and statistics.
What Scilab Can’t Do
Scilab has limited functionalities dealing with symbolic operations such as differen-tiation, integration, etc. But this limitation can be overcome by installing additionaltoolbox, which will be covered in volume 2. This limitation does not have a big impacton our choice of Scilab as our software all through out our course. Also it lacks GUIeditor like from Matlab. There are toolbox available but not fully tested and still withbugs.
Conventions
This handbooks assumes that you have already installed Scilab in your machine.Below are the conventions used in this book.
• Codes are displayed in Courier format.
Scilab Quick Reference (Early Access) Preface 1
• Code with --> before the command are executed in the console.
• Code without --> are saved in an external file then loaded in scilab.
• Enclosed in <> are optional arguments, may or may not be present.
• Keywords categories:
– %name - variables.
– name - functions and reserved words. Function name is followed by paren-thesis specifying argument list. Parenthesis can be eliminated if there are noarguments needed.
– symbol - operators.
Chapter 1
Scilab Basics
Scilab Quick Reference (Early Access) Chapter 1: Basics 3
1 Scilab Basics
1.1 Objectives
• To understand the features of scilab and its significance in numerical simulation.
• To know how to create a matrix in scilab.
• To know how to manipulate matrix.
• To know special type of matrices such as sparse and its impact in computing largematrices with more zero elements.
• To know other types of flexible matrices such as cell, list, and struct.
• To know the complete reference for built-in math functions in Scilab.
• To know the basic of plotting a data and a function.
• To know how to manipulate polynomials.
• To know how to manipulate complex numbers in Scilab.
1.2 Definition of terms
Complex number A mathematical expression that involves an imaginary number.
Elementwise operation Operations are performed element-by-element correspond-ingly to its position.
LU decomposition Decomposing the matrix into two matrix which when multipliedwill get the original matrix. L stands for lower and U stands for Upper Triangularmatrix.
Matrix Array of numbers arranged in a tabular form, that is, arranged in rows andcolumns.
Polynomial An algebraic expression that involves only one variable and that the ex-ponent is decreasing.
Reduced-row echelon form or rref, refers to the augmented matrix transformingthe left square matrix into an identity matrix.
Scilab Quick Reference (Early Access) Chapter 1: Basics 4
Scalar A single number or a single variable that represents a number.
Square matrix A type of matrix whose number of rows is the same as the number ofcolumns.
Submatrix A matrix that is part of a bigger parent matrix.
Symbolic variable A variable that retains its symbol as a result of a mathematicaloperation.
1.3 Introduction
Scilab is a numerical software that process data by batch, that is, stored in a ma-trix. Mathematical capabilites of Scilab aside from built-in math functions and matrixmanipulation involve plotting, polynomial operation and complex numbers.
1.4 Mode of Scilab
Scilab Window Scilab environment with menus and toolbars and the console.
Scilab Command Prompt Run in a native command prompt for optimized perfor-mance. Same functionalities with its window counterpart but it does not includethe menus and toolbars. Calling help window and scipad editor is also pos sible.
1.5 Some useful windows in Scilab
Scipad editor Window where source code are edited.Command: scipad.
Help window Help window where documentation of functions reside. Command:help.
Graphics window Window container of graphics component of Scilab such as plot-ting and graphical user interface controls. Command: figure, or any plottingfunctions.
Scicos window Block diagraming window interface in Scilab. Command: scicos.
1.6 Basics
Basic usage of scilab as a numerical software is a calculator. Table 1 shows the scalarand matrix computation built-in in Scilab.
Scilab Quick Reference (Early Access) Chapter 1: Basics 5
Figure 1: Scilab Window
Scilab Quick Reference (Early Access) Chapter 1: Basics 6
Figure 2: Scilab console
Data type DescriptionNumeric type Integer such as 1, floating-point such as 3.203, base 10 exponent
such as 2e3 equivalent to 2 ∗ 103 or 200.Boolean type %t for true and %f for false.String type Enclosed in a single or double quotation such as ’hello’ or
"hello".Symbolic type A variable commonly used in a polynomial. Example:
x=poly(0,’x’)
Table 1: Basic data types
Basic data types
Variables
Keywords: type, typeof
Representation or storage of numbers, string of characters, boolean and symbolic.Only 24 characters are accepted as variable name. Since scilab is loosely type, i.e. vari-able type are not declared, to determine the type of a variable just use type commandthat returns an integer mapped to description as shown in the table 2. To return acomplete type name, use typeof command.
Scilab Quick Reference (Early Access) Chapter 1: Basics 7
Figure 3: Scilab editor
Scilab Quick Reference (Early Access) Chapter 1: Basics 8
Figure 4: Help window
Scilab Quick Reference (Early Access) Chapter 1: Basics 9
Figure 5: Graphics Window
Scilab Quick Reference (Early Access) Chapter 1: Basics 10
Figure 6: Scicos Window
Rules: Must start with [a-z], [A-Z], or, underscore(_) followed by [a-z], [A-Z],underscore(_), or, [0-9].
Valid: varname, var_name, anotherVariable, _var2.
Invalid: 5var
Editing variables
Keywords: editvar
Sample Code
Start code
-->a = eye(3,3)
a =
1. 0. 0.
0. 1. 0.
Scilab Quick Reference (Early Access) Chapter 1: Basics 11
Code Type1 Real or complex constant matrix.2 Polynomial matrix.4 Boolean matrix.5 Sparse matrix.6 Sparse boolean matrix.7 Matlab sparse matrix.8 Matrix of integers stored on 1 2 or 4 bytes.9 Matrix of graphic handles.10 Matrix of character strings.11 Un-compiled function (Scilab code).13 Compiled function (Scilab code).14 Function library.15 List.16 Typed list (tlist).17 Matrix oriented typed list (mlist).128 Pointer (See lufact).129 Size implicit polynomial used for indexing.130 Scilab intrinsic (C or Fortran code).
Table 2: Variable types
Scilab Quick Reference (Early Access) Chapter 1: Basics 12
Figure 7: Variable editor window
0. 0. 1.
-->editvar a // shows the variable editor shown below
End code
Variable editor windowFigure 7 shows variable editor window.
Scalar computation
Sample Code
Start code
--> 1 + 1 //scalar addition
ans =
2.
Scilab Quick Reference (Early Access) Chapter 1: Basics 13
--> a=1; //variable assignment
--> a+2 //variable operation
ans =
3.
End code
Note: Putting a semicolon at the end of a statement suppresses the output to display.For variable assignment, variable is already registered in a workspace but not echoed tothe command line. ans is the default variable if no assigned variable specified.
Continuing long command
Long commands that is messy when force to fit to a single line can be sliced up tomultiple lines using ellipsis (3 dots).
Sample Code
Start code
-->a = 1+...
-->1
a =
2.
End code
1.7 Boolean expressions
Expressions that return either true or false. Comparison between the current valueand the base value or checking the property of a variable is it is a not-a-number, infi-nite, real or complex, defined, or empty. Used in specifying conditions in a conditionalstatements and looping statements.
1.8 Built-in math functions and variables
Table 4 shows built-in math variables and functions.
Scilab Quick Reference (Early Access) Chapter 1: Basics 14
Command Description%t A variable that represent true value.%f A variable that represent false value.> Greater than.>= Greater than or equal.< Less than.<= Less than or equal.== Equal.~= Not equal. Same as <>.& And operator.~ Not operator.| Or operator.isdef Check if variable is defined in a workspace.isempty Check if variable is empty.isnan Check if variable is not-a-number.isreal Check if variable is real or complex.isinf Check if variable is infinite.isequal Check if 2 objects are equal.
Table 3: Boolean variable, comparison operator, and boolean functions
1.9 Matrix
Built-in math functions is also applicable to a matrix.
Matrix are created by enclosing array of numbers by a pair of brackets. Rows areseparated by a return key or a semicolon. Columns are separated by a space or acomma.
Matrix construction
Keywords: bracket([]), comma(,), space, semicolon(;), return key
Sample CodeStart code
-->//1st solution
-->//comma as column separator
-->//semicolon as row separator
Scilab Quick Reference (Early Access) Chapter 1: Basics 15
Command Description%pi Equivalent to π = 3.1415927.%e Equivalent to e = 2.7182818.cos(t) Cosine of angle t where t is in radians.acos(x) Arccosine of x. cos−1(x). Returns the result in radians.sin(t) Sine of angle t where t is in radians.asin(x) Arcsine of x. sin−1(x). Returns the result in radians.tan(t) Tangent of angle t where t is in radians.atan(x) Arctangent of x. tan−1(x). Returns the result in radians.
cosh(t) Cosine hyperbolic.et + e−t
2.
t=acosh(x) Arcosine hyperbolic. cosh(t) = x.
sinh(t) Sine hyperbolic.et − e−t
2.
t=asinh(x) Arcsine hyperbolic. sinh(t) = x.
tanh(t) Tangent hyperbolic.sinh(t)cosh(t)
.
t=atanh(x) Arctangent hyperbolic. tanh(t) = x.abs(n) Absolute value. Returns a positive value for a scalar argument, n.v=log(x) Natural logarithm with base e. ev = xv=log10(x) Common logarithm with base 10. 10v = xv=log2(x) Logarithm with base 2. 2v = xv=exp(x) ex. Same as %e^x.v=sqrt(x) Square root. v =
√x equivalent to v = x1/2.
Table 4: Math built-in variables and functions
Scilab Quick Reference (Early Access) Chapter 1: Basics 16
--> a = [1,2,3;4,5,6;7,8,9]
a =
1. 2. 3.
4. 5. 6.
7. 8. 9.
-->//2nd solution
-->//return key as row separator
-->//space as column separator
--> b = [6 1 3
9 0 1
3 2 8]
b =
6. 1. 3.
9. 0. 1.
3. 2. 8.
-->//Combination of 1st and 2nd solution
-->//return key and semicolon as row separator
-->//space and comma as column separator
--> c = [5,2,-3
1,0,3;10,-8 3]
c =
5. 2. - 3.
1. 0. 3.
10. - 8. 3.
End code
Matrix operation
Table 5 shows basic operator for matrix operation.Sample Code
Start code
-->a = [4,3,6;1,5,7;6,1,9];
Scilab Quick Reference (Early Access) Chapter 1: Basics 17
Command Description+ Matrix addition.- Matrix subtraction.* Matrix multiplication. Inner dimension must agree, i.e., column
count of the first operand must be equal to the row count of thesecond operand. The resulting dimension is that the resulting rowequals to the row of the first operand and resulting column equalsto the column of the second operand
/ Matrix division. A/B = A ∗B−1
\ Matrix back-division. A\B = A−1 ∗B^ Matrix exponentiation with scalar power. Matrix exponent is pos-
sible but not practical.
Table 5: Operators used in matrix operation
-->b = [3,7,1;8,4,7;0,2,1];
-->a+b
ans =
7. 10. 7.
9. 9. 14.
6. 3. 10.
-->a-c
ans =
- 1. 1. 9.
0. 5. 4.
- 4. 9. 6.
-->a*c
ans =
83. - 40. 15.
80. - 54. 33.
121. - 60. 12.
Scilab Quick Reference (Early Access) Chapter 1: Basics 18
-->a/c
ans =
0.6515152 2.8636364 - 0.2121212
0.5202020 3.3484848 - 0.4949495
0.5 3.5 0.
-->a\c
ans =
1.025974 1.9220779 - 2.6493506
- 0.7142857 3.1428571 - 2.1428571
0.5064935 - 2.5194805 2.3376623
-->a^2,a*a //same result
ans =
55. 33. 99.
51. 35. 104.
79. 32. 124.
ans =
55. 33. 99.
51. 35. 104.
79. 32. 124.
End code
Elementwise operation
Each elements that corresponds to their position are evaluated one-by-one. Matrixaddition and matrix subtraction are already elementwise operation but not multiplica-tion, division and exponentiation. See table 6.
Sample CodeStart code
Scilab Quick Reference (Early Access) Chapter 1: Basics 19
Command Description.* Matrix element-by-element multiplication../ Matrix element-by-element division..^ Matrix element-by-element exponentiation..\ Matrix element-by-element back-division.
Table 6: Operators used in elementwise matrix operation
-->a = [4,3,6;1,5,7;6,1,9];
-->b = [3,7,1;8,4,7;0,2,1];
-->a .* b
ans =
12. 21. 6.
8. 20. 49.
0. 2. 9.
-->b ./ a
ans =
0.75 2.3333333 0.1666667
8. 0.8 1.
0. 2. 0.1111111
-->a .^ b
ans =
64. 2187. 6.
1. 625. 823543.
1. 1. 9.
-->a .\ b
ans =
0.75 2.3333333 0.1666667
8. 0.8 1.
Scilab Quick Reference (Early Access) Chapter 1: Basics 20
0. 2. 0.1111111
End code
Expanding a matrix
Matrix in scilab is dynamic and can expand and shrink in dimension. See samplecode below.
Start code
-->//starting as a scalar
-->e=1,esize=size(e)
e =
1.
esize =
1. 1.
-->e(2)=3,esize=size(e)
e =
1.
3.
esize =
2. 1.
-->e(1,4)=-1,esize=size(e)
e =
1. 0. 0. - 1.
3. 0. 0. 0.
esize =
2. 4.
Scilab Quick Reference (Early Access) Chapter 1: Basics 21
-->e(3,3)=5,esize=size(e)
e =
1. 0. 0. - 1.
3. 0. 0. 0.
0. 0. 5. 0.
esize =
3. 4.
-->e(4,:)=[2 9 8 1],esize=size(e)
e =
1. 0. 0. - 1.
3. 0. 0. 0.
0. 0. 5. 0.
2. 9. 8. 1.
esize =
4. 4.
-->//size of matrix e is changing
End code
Submatrix extraction
Table 7 shows the symbol and operator used to extract element of submatrix of agiven matrix.Initializing matrix
Start code
-->a = [4,3,6;1,5,7;6,1,9]
a =
4. 3. 6.
1. 5. 7.
Scilab Quick Reference (Early Access) Chapter 1: Basics 22
Command Description$ Last index.: All indices.a(r,c) Accessing rth row cth column. r and c can be a scalar, vector or a
matrix.a(n) Accessing nth number counted from top to bottom then left to
right. n can be a scalar, vector or a matrix.
Table 7: Operators and syntax used for extracting element or submatrix
6. 1. 9.
-->b = [3,7,1;8,4,7;0,2,1]
b =
3. 7. 1.
8. 4. 7.
0. 2. 1.
-->c = [a,b]
c =
4. 3. 6. 3. 7. 1.
1. 5. 7. 8. 4. 7.
6. 1. 9. 0. 2. 1.
End code
Scalar index
Syntax: a(r,c) or a(n)Start code
-->//accessing row 1, col 1
-->a(1,1)
ans =
4.
-->//accessing row 2, col 3
-->a(2,3)
Scilab Quick Reference (Early Access) Chapter 1: Basics 23
ans =
7.
-->//accessing row 3, last col
-->a(3,$)
ans =
9.
-->a(5)
ans =
5.
End code
Vector index
Syntax: a([ri,rj,rk],[cp,cq,cr])
The syntax above is interpreted as
a((ri, rj, rk) ,
cpcqcr
)
The result is aip aiq air
ajp ajq ajr
akp akq akr
Start code
-->//accessing rows 1 and 2, col 3
-->a([1,2],3)
ans =
6.
Scilab Quick Reference (Early Access) Chapter 1: Basics 24
7.
-->//accessing rows 1 and 2, cols 2 and 3
-->a([1,2],[2 3])
ans =
3. 6.
5. 7.
-->//accessing rows 1 and 3, all columns
-->a([1 3],:)
ans =
4. 3. 6.
6. 1. 9.
-->//accessing rows 1 and 3, last column
-->a([1 3],$)
ans =
6.
9.
-->a([1,3,5,9])
ans =
4.
6.
5.
9.
-->//error: accessing submatrix beyond the dimension
-->a([1 2 4],:)
!--error 21
Invalid index.
End code
Matrix index
Scilab Quick Reference (Early Access) Chapter 1: Basics 25
Row or column indeces are matrix.
Syntax: a([ri,rj;rk,rm],[cp,cq;cr,cs])
The syntax above is interpreted as
a(
(ri rj
rk rm
),
(cp cqcr cs
))
Expanding into group of vector indices, a((ri, rj) ,
(cpcr
)) a((ri, rj) ,
(cqcs
))
a((rk, rm) ,
(cpcr
)) a((rk, rm) ,
(cqcs
))
The result is
aip air aiq ais
ajp ajr ajq ajs
akp akr akq aks
amp amr amq ams
Start code
-->c([1,2;2,3],[1,3;5,6])
ans =
4. 7. 6. 1.
1. 4. 7. 7.
1. 4. 7. 7.
6. 2. 9. 1.
-->c([1,2],[1,3;5,6])
ans =
4. 7. 6. 1.
1. 4. 7. 7.
-->c([1,2;2,3;4,8])
ans =
Scilab Quick Reference (Early Access) Chapter 1: Basics 26
4.
1.
3.
1.
6.
7.
End code
Replacing a submatrix
When replacing a submatrix, first extract the submatrix and then store a new ma-trix having the same dimension with the extracted one. If the original submatrixdoes not have the same dimension as the new matrix, the error would be ’Inconsistentrow/column dimensions’ with error code equal to 6.
Sample CodeStart code
-->//creating a 3x4 matrix and store to d
-->d=[1,2,6,2;3,9,8,7;3,7,5,1]
d =
1. 2. 6. 2.
3. 9. 8. 7.
3. 7. 5. 1.
-->//replace submatrix comprising of 2nd and last row then 3rd and last column
-->// by [9 8]
-->// [7 6]
-->d([2,$],[3,$]) = [9,8;7,6]
d =
1. 2. 6. 2.
3. 9. 9. 8.
3. 7. 7. 6.
Scilab Quick Reference (Early Access) Chapter 1: Basics 27
End code
Deleting matrix or submatrix
Can be done by assigning it with a [] (bracket). Submatrix deletion involves elim-ination of row(s) or column(s). Arguments for submatrix extraction must be either ofthe case: single or multiple rows and all columns, or, single or multiple columns and allrows.
Sample CodeStart code
-->//using the same matrix as initialized above
-->a,b,c
a =
4. 3. 6.
1. 5. 7.
6. 1. 9.
b =
3. 7. 1.
8. 4. 7.
0. 2. 1.
c =
4. 3. 6. 3. 7. 1.
1. 5. 7. 8. 4. 7.
6. 1. 9. 0. 2. 1.
-->//deleting all elements in matrix, a
-->a=[]
a =
[]
-->//deleting rows 1 and 2
-->b([1,2],:) = []
b =
Scilab Quick Reference (Early Access) Chapter 1: Basics 28
0. 2. 1.
-->//deleting columns 2 and 3
-->c(:,[2 3])=[]
c =
4. 3. 7. 1.
1. 8. 4. 7.
6. 0. 2. 1.
-->//error: 5th column is out of bounds
-->c([1,2],[1,5])
!--error 21
Invalid index.
End code
Deleting submatrix with matrix as index
If the index is a matrix, the result is the submatrix retaining the matrix index forthe row and the remaining columns eliminating the matrix index in the column.
Sample CodeStart code
-->//recall c
-->c
c =
4. 3. 7. 1.
1. 8. 4. 7.
6. 0. 2. 1.
-->// same as c([1,2;3,2],4)
-->// since columns [1,2,3] are eliminated
-->c([1,2;3,2],[1,3;2,3])=[]
c =
1.
Scilab Quick Reference (Early Access) Chapter 1: Basics 29
1.
7.
7.
End code
Matrix manipulation
Table 8 shows the functions used for matrix manipulation.
Element lookup in a matrix
Table 9 shows functions and syntax to search a certain element in a matrix.Sample Code
Start code
-->g=int(rand(4,4)*10+1)
g =
9. 9. 2. 3.
7. 1. 5. 6.
2. 9. 8. 3.
1. 1. 10. 5.
-->and(g)
ans =
T
-->or(g)
ans =
T
-->g(4,3)=0
g =
Scilab Quick Reference (Early Access) Chapter 1: Basics 30
Command Descriptiondiag(a) Diagonal of a matrix. If a is a matrix, it extracts the diagonal
elements of a matrix. If a is a vector, it creates a matrix placingall elements along the diagonal with zero other elements.
trace(a) Sum up the diagonal elements of a square matrix. Error if argumentis not a square matrix.
[L,U]=lu(a) Perform LU decomposition to a matrix. Error if output argumentsis not atleast 2.
rref(c) Reduced-row echelon form of matrix c where c is an augmentedmatrix result of a and b. Uses LU transformations. It can alsosolve any kind of matrix.
det(a) Solves for the determinant of a matrix. Error if a is a vector.inv(a) Solves for the inverse of a matrix. Error if a is a vector.a’ Transpose of a matrix.unique Returns the unique set of numbers in a given matrix.max(a) Maximum value of a given matrix. max(a,’r’) returns the maxi-
mum value in every column resulting to a row vector. max(a,’c’)returns the maximum value in every row resulting to a columnvector.
min(a) Minimum value of a given matrix. min(a,’r’) returns the mini-mum value in every column resulting to a row vector. min(a,’c’)returns the minimum value in every row resulting to a column vec-tor.
prod(a) Product of all elements in a matrix. prod(a,’r’) returns theproduct of elements in every column resulting to a row vector.prod(a,’c’) returns the product of elements in every row resultingto a column vector.
sum(a) Sum of all elements in a matrix. sum(a,’r’) returns the productof elements in every column resulting to a row vector. sum(a,’c’)returns the product of elements in every row resulting to a columnvector.
cumprod(a) Cumulative product of a matrix. cumprod(a,’r’) returns the cu-mulative product of elements in every column resulting to a ma-trixmatrix. cumprod(a,’c’) returns the cumulative product ofelements in every row resulting to a matrix.
cumsum(a) Cumulative sum of a matrix. cumsum(a,’r’) returns the cumula-tive sum of elements in every column resulting to a matrixmatrix.cumsum(a,’c’) returns the cumulative sum of elements in everyrow resulting to a matrix.
flipdim(a,d) Flip matrix vertically or horizontally. If d=1, matrix is flipped ver-tically, same as a($:-1:1,:). If d=1, matrix is flipped horizontally,same as a(:,$:-1:1).
Table 8: Functions used to manipulate a matrix
Scilab Quick Reference (Early Access) Chapter 1: Basics 31
Command Descriptionand(m) Test if a vector or matrix are all true or greater than zero. Checking
by row or by column: and(m,’r’) - checks each column and returna row vector;and(m,’c’) - checks each row and return a columnvector;
or(m) Test if a vector or matrix has atleast 1 true or greater thanzero.Checking by row or by column: or(m,’r’) - checks each col-umn and return a row vector;or(m,’c’) - checks each row andreturn a column vector;
find(m) Find indices of a given boolean condition from a given vector ormatrix greater than zero. find(m bool_op n) where m is a ma-trix, bool op is a boolean operator such as <,<=,>,>=,==,<>,~=, nis the limit number. If values are to be displayed instead of indicesuse m(find(m bool_op n)).
m(m bool_op n) Display the elements that satisfies the condition.
Table 9: Functions and syntax for searching elements in a matrix that satisfies a criteria
9. 9. 2. 3.
7. 1. 5. 6.
2. 9. 8. 3.
1. 1. 0. 5.
-->and(g)
ans =
F
-->or(g)
ans =
T
-->// returns the indices of elements with g>5
-->find(g>5)
ans =
1. 2. 5. 7. 11. 14.
Scilab Quick Reference (Early Access) Chapter 1: Basics 32
-->g(find(g>5)) //same as g(g>5)
ans =
9.
7.
9.
9.
8.
6.
-->g(find(g>5))=-1 //same as g(g>5)=-1
g =
- 1. - 1. 2. 3.
- 1. 1. 5. - 1.
2. - 1. - 1. 3.
1. 1. 0. 5.
End code
Auto-generation of matrices
Table 10 shows functions to generate a matrix.Sample Code
Start code
-->// single input has a scalar output, first element only
-->// same behavior as zeros and ones function
-->eye(3,3)
ans =
1. 0. 0.
0. 1. 0.
0. 0. 1.
-->ones(3,3)
ans =
Scilab Quick Reference (Early Access) Chapter 1: Basics 33
Command Descriptioneye(r,c) Identity matrix.ones(r,c) Matrix with elements all equal to 1.zeros(r,c) Matrix with elements all equal to 0.rand(r,c) Matrix with elements generated randomly between 0 to 1. Use
to generate test matrix. Formula: int(rand(m,n)*maxN+startN),generates an m-by-n matrix with each elements randomly selectedbetween startN and maxN .
linspace(n,x,p) Linear spacing of a vector with specified number of points. n asminimum number, x as maximum number, and p as the number ofpoints.
logspace(n,x,p) Same as linspace but spaced logarithmically.n:i:x Linear spacing of a vector. n as minimum, x as maximum, and
i as interval from n and x. Valid syntax: n:x has default i=1.Decreasing interval starting from maximum has a syntax, x:-i:n.
testmatrix(t,n) Generates an nxn matrix depending on the typet=’magi’|’frk’|’hilb’. Type can be ’magi’ to generate a magicsquare, ’frk’ to generate a Franck matrix, and ’hilb’ to generateinverse of hilbert matrix.
toeplitz(v) A test matrix that generates a matrix symmetrical along the diag-onal. v is a vector.
Table 10: Functions used to generate a matrix
Scilab Quick Reference (Early Access) Chapter 1: Basics 34
1. 1. 1.
1. 1. 1.
1. 1. 1.
-->zeros(3,3)
ans =
0. 0. 0.
0. 0. 0.
0. 0. 0.
-->rand(1,3)
ans =
0.2113249 0.7560439 0.0002211
-->linspace(1,10,5)
ans =
1. 3.25 5.5 7.75 10.
-->logspace(1,10,5)
ans =
10. 1778.2794 316227.77 56234133. 1.000D+10
-->1:3:10 // increasing
ans =
1. 4. 7. 10.
-->10:-3:1 // decreasing
ans =
10. 7. 4. 1.
-->testmatrix(’magi’,3)
ans =
Scilab Quick Reference (Early Access) Chapter 1: Basics 35
8. 1. 6.
3. 5. 7.
4. 9. 2.
-->testmatrix(’frk’,3)
ans =
3. 2. 1.
2. 2. 1.
0. 1. 1.
-->testmatrix(’hilb’,3)
ans =
9. - 36. 30.
- 36. 192. - 180.
30. - 180. 180.
-->toeplitz([1,2,3,4])
ans =
1. 2. 3. 4.
2. 1. 2. 3.
3. 2. 1. 2.
4. 3. 2. 1.
End code
Kinds of matrices
Table 11 shows different kinds of matrices.
Scilab Quick Reference (Early Access) Chapter 1: Basics 36
Kind of matrix Sample matrix Sample scilab command
Identity matrix
1 0 00 1 00 0 1
-->eye(3,3)
Symmetric matrix
1 2 32 1 23 2 1
-->toeplitz([1,2,3])
Upper triangular matrix
1 2 30 4 50 0 6
-->[1,2,3;0,4,5;0,0,6]
Lower triangular matrix
1 0 02 4 03 5 6
-->[1,0,0;2,4,0;3,5,6]
Null matrix
0 0 00 0 00 0 0
-->zeros(3,3)
Table 11: Kinds of matrices
1.10 Special types of matrices
List, Struct and Typed List
Table 12 shows basic special types of matrices that stores different data type objects.
Creating and manipulating listStart code
-->m = list() // creating an empty list
m =
()
-->m(1) = [1 2] // assigning vector with constant values to first list
m =
m(1)
1. 2.
-->m(2) = ’hello’ //assigning string the second list
m =
Scilab Quick Reference (Early Access) Chapter 1: Basics 37
Command Descriptionlist(a1,...) List of values of different types such as numbers, strings, or objects.
a1,... are scilab objects such as numbers, string, etc. Adding datain a list can be one-by-one or in one batch. Empty parameterscreate a list object with empty data.
struct(fn,fv,...) Values of different types (numbers, strings, or objects) are associ-ated with a field name. fn is the field name and fv is the fieldvalue. Adding fields in a struct can be one-by-one or in a singlecall specifying the field name and field values in a respective order.Empty parameter creates a struct object with empty fields.
tlist(f,a1,...) Same as list but a string type can be used to access an objectwithin the list. f as the field names, a1,... are scilab objects suchas numbers, string, etc. Similar to struct but differs on accessingthe fields and the values. Field names can be possibly accessed,a vector which is the first parameter of the tlist. Note: Firstfieldname is the name of the typed list and not included as fieldname.
Table 12: List, struct and tlist
m(1)
1. 2.
m(2)
hello
-->size(m) //number of elements in a list
ans =
2.
-->typeof(m(1)) //check type of first list
ans =
constant
-->typeof(m(2)) // check type of second list
ans =
string
Scilab Quick Reference (Early Access) Chapter 1: Basics 38
-->m(2) = null(); // remove the second value within list
-->size(m)
ans =
1.
End code
Creating and manipulating structStart code
-->g = struct() // creating an empty struct
g =
0x0 struct array with fields:
-->g.shapename = ’square’ //adding a new field and assign a field value
g =
shapename: "square"
-->g.sides = 4
g =
shapename: "square"
sides: 4
-->g.areequalsides = %t
g =
shapename: "square"
sides: 4
areequalsides: %t
-->typeof(g.areequalsides) //check type of stored field value
ans =
boolean
End code
Creating and manipulating tlistStart code
Scilab Quick Reference (Early Access) Chapter 1: Basics 39
Command Descriptioncell Matrix with different types. A special type of struct that has one
field named entries used for accessing values of a cell.sparse Sparse matrixfull Convert sparse to full matrix including zero elements.size Returns the size of the sparse matrix. Can be used in list and
matrices which output the dimension of the argument.length Maximum of what size returns.
Table 13: Functions used for creating and manipulating a special matrix
-->t = tlist([’tlistname’,’vec’,’str’,’bool’],[1 2],’hello’,%t);
-->t.vec
ans =
1. 2.
-->t.str
ans =
hello
-->t.bool
ans =
T
End code
Table 13 shows other functions used to create and manipulate a special type ofmatrix.
Other special types
Sample CodeStart code
-->//create a sparse matrix
-->sp=sparse([1,2;4,5;3,10],[1,2,3])
sp =
( 4, 10) sparse matrix
Scilab Quick Reference (Early Access) Chapter 1: Basics 40
( 1, 2) 1.
( 3, 10) 3.
( 4, 5) 2.
-->size(sp)
ans =
4. 10.
-->length(sp)
ans =
10.
-->full(sp)
ans =
0. 1. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 3.
0. 0. 0. 0. 2. 0. 0. 0. 0. 0.
End code
1.11 Miscellaneous functions
Table 14 shows functions used to manipulate a number.
1.12 Formatting numeric precision display
This does format a single value but formats all values to be displayed in console.Table 15 shows commands how to format display precision.
Syntax
Sample CodeStart code
-->//default precision: format(10) - 8 significant figures
-->v=10.342341123
v =
10.342341
Scilab Quick Reference (Early Access) Chapter 1: Basics 41
Command Descriptionceil(n) Round towards + inf. ceil(3.45) returns 4. ceil(-3.45) returns
-3.factor(n) Returns prime factors of an integer in vector. verb—factor(45)—
returns [3, 3, 5].fix(n) Round towards − inf. fix(3.45) returns 3. fix(-3.45) returns
-3.round(n) Rounds to nearest integer. round(3.45) returns 3. round(-3.45)
returns -3. round(3.67) returns 4. round(-3.67) returns -4.floor(n) Round towards 0. floor(3.45) returns 3. floor(-3.45) returns
-2.int(n) Extracts the integer part. int(3.45) returns 3. int(-3.45) re-
turns -3.primes(x) Returns the prime numbers between 2 and x in vector.modulo(d,n) Remainder for d/n.pmodulo(d,n) Positive remainder for d/n.base2dec Conversion from base b to decimal base.hex2dec Conversion from base 16 to decimal base.oct2dec Conversion from base 8 to decimal base.bin2dec Conversion from base 2 to decimal base.dec2oct Conversion from base 10 to base 8.dec2hex Conversion from base 10 to base 16.dec2bin Conversion from base 10 to base 2.sort Matrix sorting.lex_sort Lexicographical sorting.diff Cumulative difference between adjacent elements of a vector.perms Permutation of a number.permute Permute a given vector.intersect Intersection of 2 vectors.union Union of 2 vectors.vectorfind Find vector.rat Approximate rational expression.binomial Binomial distribution.
Table 14: Other functions used to manipulate a number in scilab
Scilab Quick Reference (Early Access) Chapter 1: Basics 42
Command Description%eps Smallest number in scilab. Default value: 2.220D − 16 equivalent
to 2.220 ∗ 10−16
format(’t’,d) Where ’t’ can be ’v’, for variable, or ’e’, for scientific nota-tion, and, d is the number of significant digits minus 2 (extradigits). Other valid call: format(’v’) - default variable format,format(’e’) - default scientific notation format, format(10) - (de-fault format) formats ’v’ and ’e’ into 8 significant digits.
clean Rounds off very small number, value of %eps to zero.
Table 15: Formatting functions
-->a=1.23124,b=15.123125423
a =
1.23124
b =
15.123125
-->//formats number of scientific notation
-->// to 6 (minus-2) significant digits
-->format(6)
-->a,b
a =
1.231
b =
15.12
-->format(’v’)
-->a,b
a =
Scilab Quick Reference (Early Access) Chapter 1: Basics 43
1.23124
b =
15.123125
-->format(’e’)
-->a,b
a =
1.231D+00
b =
1.512D+01
End code
See printf function for more flexible and accurate formatting of output.
1.13 Basic of polynomials
Keywords: poly
Constructing polynomial is very handy in Scilab by using poly function. Creatingpolynomial can be done in 3 ways: symbolically, through given roots, and through givencoefficients. It can also be used to solve for the characteristic polynomial (eigenpoly-nomial) of a given system2 matrix.
Polynomial operation in Scilab involves only one variable. Attempt to add twodifferent variables will result to an error. More symbolic operation will be achievedthrough interoperating Maxima with Scilab.
Syntax
A = poly(m,’s’<,’flag’>)
2System matrix a term used in control systems
Scilab Quick Reference (Early Access) Chapter 1: Basics 44
m m can be a scalar or a matrix. If it is a scalar the result is s−m with s as the symbolicvariable. If it is a vector without a third argument (flag), then it is assumed asroots of the polynomial, else if specified are coefficients. If it is a matrix the resultis |s ∗ I −m|, where I is an identity matrix with same dimension as m.
’s’ A string that stand as a symbolic variable used by the polynomial. It can be ’s’,’x’, ’mypoly’, or any variable you like as long as it does not exceed 4 characters.For the case of ’mypoly’, it is cut down to ’mypo’.
’flag’ Flag can be any of the two string: ’roots’(default) and ’coeff’. Use ’roots’ if thegiven vector data are roots and use ’coeff’ if they are coefficients of the polynomial.
Constructing polynomial symbolically
Sample CodeStart code
-->//Creating a symbolic variable
--> s = poly(0,’s’)
s =
s
--> s = %s // built-in variable: %s and %z
s =
s
-->//Using the symbolic variable in math
-->//operatorion to create a polynomial
--> p = 1+2*s+s*s
p =
2
1 + 2s + s
-->(s-1)*(s-2)*(s-3)*(s-4)
ans =
2 3 4
24 - 50s + 35s - 10s + s
End code
Scilab Quick Reference (Early Access) Chapter 1: Basics 45
Constructing polynomial via roots
Sample CodeStart code
-->//same as poly([1 2 3 4],’s’) with ’roots’ by default as flag
-->poly([1 2 3 4],’s’,’roots’)
ans =
2 3 4
24 - 50s + 35s - 10s + s
End code
Constructing polynomial via coefficients
Sample CodeStart code
-->poly([1 2 3 4],’s’,’coeff’)
ans =
2 3
1 + 2s + 3s + 4s
End code
Polynomial operation
Only one variable is allowed. Error if operation consists of 2 different variables. Table16 where p1 and p2 are polynomials and n is a number which can be a scalar or a matrix.
Polynomial manipulation
Table 17 shows commands to manipulate a polynomial object.Sample Code
Start code
Scilab Quick Reference (Early Access) Chapter 1: Basics 46
Command Descriptionp1+p2 Adds two polynomials.p1-p2 Subtracts p2 from p1.p1*p2 Multiply two polynomials and expand.p2/p1 Divide two polynomials and simplify.p1\p2 Back-division or reverse division.p1^n Exponent must be a number and not a polynomial.
Table 16: Operators used in polynomial operation
Command Descriptionroots(p) Solve for the roots of a polynomial. Where p is a polynomial.coeff(p) Extracts the coefficients of a polynomial starting from the constant.
Where p is a polynomial.numer(p) Extracts the numerator of a rational polynomial. Where p is a
polynomial.denom(p) Extracts the denominator of a rational polynomial. Where p is a
polynomial.degree(p) Degree of the polynomial or the highest order of the polynomial.
Where p is a polynomial.pol2str(p) Polynomial to string conversion. Where p is a polynomial.eval(pol2str(p)) Evaluates a polynomial with the current value of the variable used
by the polynomial. Error if variable is not in the workspace.. p isa polynomial.
p($:-1:1) Reverses polynomial coefficients.varn(p,newvar) Change the variable used in the polynomial. Where p a polynomial
and newvar is a character string type.
Table 17: Functions used to manipulate a polynomial
Scilab Quick Reference (Early Access) Chapter 1: Basics 47
-->p=poly([1 2 3 4],’s’,’coeff’)
p =
2 3
1 + 2s + 3s + 4s
-->varn(p,’x’)
ans =
2 3
1 + 2x + 3x + 4x
End code
1.14 Evaluating a function in string form
Keywords: eval, feval
Preparing a function to be evaluated later is declared in string form. Then using eval
to evaluate the function using the variables available in the workspace. For multiplevariable function, make sure to create all variables in the workspace. Error if there arevariables undeclared in the workspace.
The function can also be evaluated in a piecewise manner by defining the functionas scilab function then use feval to evaluate the function to a given value.
Sample Code
Start code
-->f = ’sin(t)+exp(-t)’; // declaring a function in string
-->t = 1; // create a variable t and assign a value
-->eval(f) // evaluate the function applying the value of t
ans =
1.2093504
-->sin(1) + exp(-1) // checking the answer
ans =
1.2093504
Scilab Quick Reference (Early Access) Chapter 1: Basics 48
-->deff(’[z]=f(x,y)’,’z=x^2+y^2’);
-->feval(1:10,1:5,f)
ans =
2. 5. 10. 17. 26.
5. 8. 13. 20. 29.
10. 13. 18. 25. 34.
17. 20. 25. 32. 41.
26. 29. 34. 41. 50.
37. 40. 45. 52. 61.
50. 53. 58. 65. 74.
65. 68. 73. 80. 89.
82. 85. 90. 97. 106.
101. 104. 109. 116. 125.
End code
1.15 Complex numbers
Keywords: %i
Complex construction
Treating %i as variable with value equal to√−1 and use it makes the number be-
comes a complex.
Sample Code
Start code
--> a = 3+4*%i
A =
3 + 4i
End code
Scilab Quick Reference (Early Access) Chapter 1: Basics 49
Command Descriptioncomplex(a,b) Create a complex number where a is the real part and b the imag-
inary part. a and b can be a matrix to create a complex matrix.Both matrix should have the same dimension. This avoids affixingof %i.
abs(z) Magnitude of a complex number.real(z) Real part of a complex.imag(z) Imaginary part of a complex.conj(z) Conjugate of a complex.inv(z) Inverse of a complex.[r,theta]= r as magnitude, theta as angle in radians.polar(a+b*%i) theta can also be computed as atan(imag(z),real(z)).
Table 18: Functions used to manipulate complex numbers
Complex operation
Keywords: +, -, *, /, \, ^
Sample CodeStart code
--> a = 3+4*%i, b = 5+12*%i
a =
3 + 4i
b =
5 + 12i
--> a*b //complex multiplication
ans =
-33. + 56.i
End code
Complex manipulation
Below is a list of built-in functions use to manipulate complex numbers. Unfor-tunately, no function for computing the angle. Table 18 shows commands used tomanipulate a complex number. It is also applicable to a complex matrix.
Scilab Quick Reference (Early Access) Chapter 1: Basics 50
Command Descriptionzmat’ Transposes a complex matrix, zmat, and applying conjugate at the
same time.
Table 19: Transposing a complex matrix
Sample CodeStart code
--> a = 3+4*%i; // same as a = complex(3,4)
--> abs(a)
ans =
5
End code
Complex matrix
Keywords: ’
Matrix operation and some math operations in real numbers are still applicable incomplex matrix except transpose of a complex matrix. Table 19 shows the behavior ofcomplex matrix transpose.Sample Code
Start code
-->zmat = int(rand(2,3)*10+1)+12*%i
zmat =
3. + 12.i 9. + 12.i 4. + 12.i
3. + 12.i 7. + 12.i 10. + 12.i
-->zmat’
ans =
3. - 12.i 3. - 12.i
9. - 12.i 7. - 12.i
4. - 12.i 10. - 12.i
Scilab Quick Reference (Early Access) Chapter 1: Basics 51
Command Descriptionplot(x, Plot x vs. y1, x vs. y2, and so on[y1,y2,...,yn]) overlaying each plot. x, y1, y2, . . . , yn must be a column vector. For
row vector, use matrix transpose to transform to column vector.xgrid Adds a horizontal and vertical grid to the plot.xtitle( Adds xlabel, ylabel and title to the plot.’t’,’x’,’y’) ’t’ as title of the plot, ’x’ as label of x-axis, ’y’ as label of y-axis.
Table 20: Functions used for plotting and customizing plot
End code
1.16 Basic of plotting
Tackles the following:
Plotting a data Data are pair of points.
Plotting a function Same as plotting a data by assigning set of values to be evaluatedwith the given function.
Customizing plot Customizing properties such as the line specifications, grid, titlefor the graph and the axis.
Customizing plot properties graphically
Plot can be customized after generating it such as changing the properties of theaxes, ticks, tick label, title, line color, line style, etc. There are commands used tocustomized such properties but in this chapter we will be using the graphical axesproperties editor. Axes editor window can be accessed through the menu provided bygraphics window. Figures 8 and 9 shows screenshots of axes property editor.
Sample Code
Start code
1 -->x=[0:0.01:2*%pi];
2 -->y=sin(x)+cos(x);
3 -->plot(x,y,’k-’)
Scilab Quick Reference (Early Access) Chapter 1: Basics 52
Figure 8: Axes properties editor menu
4 -->xgrid
5 -->xtitle(’y=sin(x)+cos(x)’,’x’,’y’)
End code
Line 1 Creates a vector starting from 0 to 2π with 0.01 interval then store to variablex.
Line 2 Create a set of values for a given function, y = sinx + cosx, that substituteseach element of x.
Line 3 Call plot function of scilab to draw a plot with x as horizontal parameter andy as vertical parameter. The third argument is a custom property of the graph, kfor black color, - for solid lines connecting the points.
Line 4 Adds horizontal and vertical grids to the plot.
Line 5 Adds a label to x, y and the title of the plot.
Output
Figure 10 shows the sample output plot.
Scilab Quick Reference (Early Access) Chapter 1: Basics 53
Figure 9: Axes properties editor window
Scilab Quick Reference (Early Access) Chapter 1: Basics 54
Figure 10: Sample plot output
Scilab Quick Reference (Early Access) Chapter 1: Basics 55
1.17 Exercises
1. Matrix manipulation
(a) Construct a matrix of random integers between 1 and 10 with dimension 4×5,i.e. 4 rows and 5 columns.
(b) Delete the 5th column to create a square matrix.
(c) Find the indices and values of elements less than 5.
(d) Replace all elements less than 5 by 0.
(e) Create a second matrix with 4× 2 dimension.
(f) Apply matrix multiplication that avoids error and store result to c.
(g) Flip matrix c horizontally, i.e. rearrange the column in reverse order such thatthe last column becomes the first column, and so on. Hint: use transpose andsubmatrix extraction whichever is applicable.
2. Complex matrix manipulation
(a) Create a complex number where real and imaginary part are integers that arerandomly generated between 10 and 20.
(b) Create a 4 × 3 matrix of complex values where real and imaginary part arerandom integers between 10 and 20.
(c) Insert the following column vector to the last column to make the matrix asquare
3 − 4i5 − 12i2 − 10i−1 − i
(d) Locate the complex elements with real part greater than or equal to 15. Dis-
play the real values that satisfies the condition.
(e) Locate the complex elements with imaginary part greater than or equal to 17.Display the imaginary values that satisfies the condition.
(f) Compute the magnitude of each element.
(g) Locate the complex elements with magnitude greater than or equal to 23.Display the magnitude values that satisfies the condition.
Scilab Quick Reference (Early Access) Chapter 1: Basics 56
(h) Rotate the original 4× 3 complex matrix by 180 degrees. Hint: use transposeand submatrix extraction whichever is applicable.
3. Polynomial matrix manipulation
(a) Create a polynomial with degree equal to 5 and coefficients are integers thatare randomly generated between -50 and +50. Hint: use (−1)n where n israndom number from 1 to any positive integer to randomly generate a negativenumber.
(b) Create a polynomial matrix where each element follows the same criteria asabove.
(c) Search for elements whose roots are all integer, all complex, all positive inte-gers, and all negative integers.
4. Plotting
(a) Plot the following data:
{[5, 12], [2, 10], [0, 3], [5, 1], [8,−1], [9, 10], [−1, 5], [3, 9]}
(b) Plot the function below at t values between [-5,0] with 100 points linearlyspaced.
f = e−t − t− 10
df = −e−t − 1
Chapter 2
Programming Basics
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 58
2 Programming Basics
2.1 Objectives
• To know the basic construct of a function in scilab.
• To know how to load and execute a function.
• To know how to use nested function.
• To know how to manipulate input and output arguments as well as variable argu-ments both input and output.
• To know how to create a script.
• To know how to read and write data to a file.
• To know how to read input from the user.
• To know how to display data with formatted output to the screen.
• To differentiate functions from scripts.
• To create an inline function using deff command that behaves like an externalfunction.
• To iterate values of a matrix through a loop such as for and while loop.
• To handle error and exceptions in scilab statements.
• To determine the significance of a nested for loop.
• To know how to break inner loop or outer loop using break command.
• To know how to skip statements within a loop using continue command.
2.2 Definition of terms
Arguments See Parameters.
Comment lines Enclosed in double backslash. Lines skipped by scilab because theyare just description added by programmers and is not part of the interpretation.
Boolean expression An expression that evaluates to either true or false.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 59
Condition See Boolean Expression.
Function A function consists of statements that receives and process input argumentsand return a specified output Function filenames end with .sci extension.
Function call Executing a function specifying the correct parameters required by afunction.
Loop A loop is like a cycle that repeatedly execute a certain process but in everyrepetition there is an update on some values.
Parameters Variables assigned as input in a function definition and for output asvariable in a function call.
Programming Arranging series of statements to be executed in a single function call.
Regular expression Patterns used to target a specific string or subsets of string froma complete set of strings.
Script A script consists of statements that can be run in a command line but are keptin a file with .sce extension.
Variables Used to represent a number.
Variable Arguments Variable input and variable output arguments. Non-fixed, dy-namic parameters when executing a function.
2.3 Introduction
Programming a function or a script can be external or inline. External meanscreating an external file that will be loaded to Scilab workspace for execution. Inlinefunction are constructed and executed directly in a console without creating externalfile.
2.4 Scipad editor window
Commands issued in the console are saved only in the history but not on externalfile. Scilab provides an environment where you can edit your script or function calledScipad Editor. There are 3 ways to open the scipad editor, you can click Applicationmenu then Editor menu item, you can click the toolbar button with tooltip ’Launch
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 60
Figure 11: Scipad editor
Scipad’ on the leftmost area, and the last option is to type edit.. The last option, i.e.edit, is useful when you are writing a function because it opens the scipad editor withcode template of a function and saved with untitled.sci filename. You can also specifyname of the function to do such just call edit(’myfun’), opens the scipad editor withfunction name myfun and saved in myfun.sci.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 61
2.5 Scripts
Usage
Process a list of statements as a single batch. After the script is executed, allvariables inside the script are available in the workspace. Consuming extra memoryspace for unncessary variables. Filename for scripts ends with .sce extension.
Syntax
<stmt1>
<stmt2>
<stmt3>
...
Replace <stmt1>, <stmt2>, <stmt3> by a valid scilab statements.
Note: Statements are separated by a newline, a comma or a semicolon. Statementswithout semicolon display the result. Statements with semicolon does not display theresult but already loaded to the workspace.
Sample Code
Start code
// create a test matrix of random numbers between
// 1 and 10
A = int(rand(3,3)*10+1);
// determinant of a matrix
detA = det(A);
// Eigen polynomial of matrix A
eigenpolyA = poly(A,’s’);
End code
Loading and executing the script
1. Open the scipad editor by clicking the Editor menu.
2. Enter the sample code above.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 62
3. Save the file with .sce extension, say, test script.sce. Any filename will do butchoose for a descriptive filename.
4. Load the script by clicking menu Execute >> Load into Scilab menu item underthe scilab editor. You may use exec(’test_script.exe’). Prior to that is tochange the current working directory of the console using cd command. Keyboardshortcuts: ctrl+l.
5. Check the console. The output is shown below.Start code
-->A,detA,eigenpolyA
A =
1. 8. 3.
6. 2. 3.
7. 6. 3.
detA =
78.
eigenpolyA =
2 3
- 78 - 76s - 6s + s
End code
2.6 Functions
Introduction
Function consists of scripts that are surrounded by a function block. In Scilab, inputand output arguments are specified. Arguments can be fixed or dynamic. Dynamicarguments, also called variable arguments, will be discussed on the later section.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 63
Basic syntax of a function
Keywords: function, endfunction
Usage
A function process list of statements that receives input arguments and the result isstored into the output arguments. Variables inside the function are localized inside thefunction block. After execution, only the output variables exist in the workspace. Thissaves memory space eliminating unncessary variables. Filename for functions ends with.sci extension.
Syntax
function output_args = function_name( input_args )
statements;
endfunction
where
output args Output argument vector. For multiple output, enclose the arguments bya bracket each separated by a comma. Such as [out_arg1,out_arg2,out_arg3,...].Single output enclosed in a bracket is also allowed such as [out_arg] but practi-cally without a bracket.
function name Name of the function which is also the name of the file to avoid con-fusion.
input args Input argument vector. For multiple input, separate arguments by acomma. Such as in_arg1,in_arg2,....
statements Statements to be executed when calling the function. Separated by anewline or a comma for multiple statements in a single line.
Sample Code
Start code
function f = factorial(x)
// calling built-in gamma function, x!
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 64
f = gamma(x+1);
endfunction
End code
Note: Text after // are comment lines and are ignored by Scilab.
Loading and executing the function
1. Open the scipad editor by clicking the Editor menu.
2. Enter the sample code above.
3. Save the file having same filename as the function name with .sci extension, fac-torial.sci.
4. Load the function by clicking Execute >> Load into Scilab menu item. Alternativeto loading of a user-defined function is executing exec command with functionname in string as argument in a console. Such as exec(’factorial.sci’). Thecurrent directory of scilab console must be set to the directory where the functionresides. You can view the current directory through pwd command. To changedirectory, use cd.
5. Test the function by typing under the scilab console, f3=factorial(3).
6. The output should be, f3=6.
2.7 Nested function
Keywords: function, endfunction
Usage
Useful if there are repetitive simple task and creating a new external file is notpractical. Nested function can be located anywhere inside the main function and canbe accessed after the declaration.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 65
Sample Code
Save the code below under filename, nCk.sci.Start code
function b = nCk(n,k)
//b = factorial(n) % error: Undefined variable: factorial
function f=factorial(x), f=gamma(x+1), endfunction
b = factorial(n)/(factorial(k)*factorial(n-k));
endfunction
End code
2.8 Multiple functions in one file
Keywords: function, endfunction
Usage
Almost same concept with nested function but other functions are outside the mainfunction. This makes outside function possible to be declared in any order. Mainfunction is the one with the same name as the filename. Note: Variables inside thefunction is not available and cannot be called within the other function.
Sample Code
Save the code below under filename, nCk.sci.Start code
function b = nCk(n,k)
b = factorial(n)/(factorial(k)*factorial(n-k));
endfunction
function f=factorial(x)
f=gamma(x+1);
endfunction
End code
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 66
2.9 Mixed scripts and functions
To add functions inside a script, just declare the function anywhere inside the script.This is very tricky since it is allowed to be saved as script (*.sce) or as a function (*.sci).Both returns the same result. To save some external file, you may declare the functionand utility function inside a single function file including its test script. As shown incase 1 below, saved as fun internal.sce and allowed to be fun internal.sci.
To call user-defined function, change the directory to where the function resides thenuse exec(’fun_name.sci’) to load the function and make it usable anywhere in thescript and console.
1. Case 1: Function internal to script
fun_internal.sce
<use factorial function here>
function f=factorial(x)
f=gamma(x+1);
endfunction
<or use factorial function here>
End code
2. Case 2: Function external to script
Full path of factorial.sci - c:\scilab\mixed\factorial.sci.
factorial.sci
function f=factorial(x)
f=gamma(x+1);
endfunction
End code
fun_external.sce
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 67
cd c:\\scilab\\mixed\\factorial.sci
exec(’factorial.sci’)
<use factorial function here>
End code
2.10 Inline function
Keywords: deff
Usage
Function that can be created and loaded directly inline to the console without savinginto an external file.
Syntax
deff(’[output_args]=function_name( input_args )’,statements <,flag>)
where
output args Output argument list. Multiple arguments are separated by a comma.Such as [out1,out2,...].
input args Input argument list. Multiple arguments are separated by a comma. Suchas [in1,in2,...]
statements Statements to be executed when calling the inline function. Type is ofcharacter strings. For multiple statements, they are arranged as matrix of charac-ter strings, that is enclosed in a bracket. Such as [’<stmt1>’,’<stmt2>’,...].Replace <stmt1> and <stmt2> by a valid scilab statements.
flag Optional flag character.
’c’ Function is ”compiled” (default). Recommended.
’n’ Function is not ”compiled”.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 68
Sample Code
Start code
deff(’[x]=myplus(y,z)’,[’x=y+z’])
End code
Executing an inline function
1. Type the inline function above under the scilab console.
2. Initialize y and z variables, y=5 and z=4. y and z can also be matrices with uniformdimension.
3. Call the inline function by typing, x=myplus(y,z).
4. The result should be. x=9.
2.11 Sequential statements
Keywords: if, elseif, else, select, case, end
Usage
Used in selecting statements to execute based on conditions.
if-elseif-else-end
Syntax
if condition
statements;
<elseif condition
statements;>
<else
statements;>
end
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 69
Sample Code
Start code
grade = 85;
if grade>=90 & grade<=100
disp(’Excellent’)
elseif grade>=80 & grade<90
disp(’Very good’)
elseif grade>=70 & grade<=80
disp(’Good’)
else
disp(’Study more’)
end
End code
Output
Very good
select-case-else-end
Same concept with if-else, selecting which statements are to be executed dependingwhich case the value equals to.
Syntax
select value
case case1
statements;
case case2
statements;
case case3
statements;
case case4
statements;
<else>
statements;
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 70
Sample Code
Start code
month = 8
select month
case 1
disp ’January has 31 days.’
case 2
disp ’February has 28 days, except in leap year, 29 days.’
case 3
disp ’March has 31 days.’
case 4
disp ’April has 30 days.’
case 5
disp ’May has 31 days.’
case 6
disp ’June has 30 days.’
case 7
disp ’July has 31 days.’
case 8
disp ’August has 31 days.’
case 9
disp ’September has 30 days.’
case 10
disp ’October has 31 days.’
case 11
disp ’November has 30 days.’
case 12
disp ’December has 31 days.’
else
disp ’No month associated.’
end
End code
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 71
Output
month =
8.
August has 31 days.
2.12 Looping statements
for-loop
Keywords: for, end
Usage
Useful in processing data in a matrix that iterates through a vector indices.
Syntax
for var = vector_expression
statements;
end
Sample Code
Start code
//test_for.sce
a = [4,5,1,6];
for k = 1:length(a)
a(k) = a(k) + 1;
end
End code
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 72
Output
-->a
a =
5. 6. 2. 7.
while-loop
Keywords: while, end
Usage
Iteratively process statements that test condition every iteration.
Syntax
while condition
statements;
end
Sample Code
Start code
i = 1;
while i<=5
//additional statements here
i = i+1; //update i
end
End code
2.13 Nested loop
Keywords: for, while, end
Usage
Useful in processing data of a two-dimensional matrix.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 73
Cases
Case 1 for-for
for var1 = vector_expr
stmt1;
for var2 = vector_expr
stmt3;
stmt4;
end
stmt5;
end
Case 2 while-for
while cond
stmt1;
for var2 = vector_expr
stmt2;
stmt3;
end
stmt4;
end
Case 3 for-while
for var1 = vector_expr
stmt1;
while cond
stmt2;
stmt3;
end
stmt4;
end
Case 4 while-while
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 74
Command Descriptionbreak Used in exiting the loop, without executing the remaining state-
ments, when specified condition is met. Cannot break outer loopin nested loops.
continue Used in skipping statements inside the loop when specified condi-tion is met.Cannot break outer loop in nested loops.
Table 21: Break and continue statement for loop
while cond1
stmt1;
while cond2
stmt2;
stmt3;
end
stmt4;
end
2.14 Using break and continue in a loop
Usage
Can be placed anywhere inside a loop. Table 21 shows how to use break andcontinue command.
Sample Code
Start code
for k=1:10
if k==5 //skip k=5
continue;
end
disp(k)
if(k>=7) //stop if k=7 is reached
break;
end
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 75
Command Descriptionvarargin Storage for variable number of input. Must be the last argument.varargout Storage for variable number of output. Must be the last argument.[out,in]=argn Counts the number of arguments, inputor and output. Result in vector form with firstoutin=argn element as number of output and second element as number of
input.out counts the number of output arguments.in counts thenumber of input arguments. For 1 output, outin, outint(1)=out& outint(2)=in.
Table 22: Variable input and output
end
End code
Output
1.
2.
3.
4.
6.
7.
2.15 Variable input and output arguments
Usage
Variable argument list makes the function more flexible and dynamic as shown intable 22.
Syntax
Redefining basic syntax of a function into a more general expression:
function [<out1<,out2<,...>>><,<varargout>] = fun_name (
<in1<,in2<,...>>><,<varargin>)
<statements>
endfunction
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 76
Cases
Case 1 Fixed output, variable input.
Case 2 Variable output, fixed input.
Case 3 Variable output, variable input.
Case 4 Fixed output + variable output, fixed input + variable input.
Sample Code
Start code
//Main function
function [o1,o2,o3,o4] = varargcases(x)
o1 = case1(x,2*x,3*x); // 18
[o2a,o2b,o2c] = case2(x);
o2 = [o2a,o2b,o2c]; // [3, 6, 9]
[o3a,o3b] = case3(x,2*x,3*x,4*x);
o3 = [o3a,o3b]; // [30, 60]
[o4a,o4b,o4c,o4d] = case4(x,x,x,x,x); // [1, 2, 15, 30]
o4 = [o4a,o4b,o4c,o4d];
endfunction
//Case 1: Fixed output, variable input
function b1 = case1(varargin)
[out_count,in_count] = argn();
//out_count = 1
//in_count = 3
b1 = 0;
for k = 1:in_count
b1 = b1 + varargin(k);
end
endfunction
//Case 2: Variable output, fixed input
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 77
function varargout = case2(x)
[out_count,in_count] = argn();
//out_count = 3
//in_count = 1
for k = 1:out_count
varargout(k) = x*k;
end
endfunction
//Case 3: Variable output, variable input
function varargout = case3(varargin)
[out_count,in_count] = argn();
//out_count = 2
//in_count = 4
in_sum = 0;
for j = 1:in_count
in_sum = in_sum + varargin(j);
end
for k = 1:out_count
varargout(k) = k*in_sum;
end
endfunction
//Case 4: Fixed+Variable output, fixed+variable input
function [o4a,o4b, varargout] = case4(i1,varargin)
[out_count,in_count] = argn();
//out_count = 4
//in_count = 5
in_sum = i1;
for j = 1:in_count-1
in_sum = in_sum + varargin(j);
end
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 78
Command Descriptioninput Reads input from the console.disp Display the value to the screen without its variable name.
disp(value1<,’name1’<...>>)
Table 23: Input data from user and display
o4a = 1;
o4b = 2;
for k = 1:out_count-2
varargout(k) = k*in_sum;
end
endfunction
End code
2.16 Reading input and displaying output
Usage
This can be useful if you want to ask user for an input. Displaying the values isby default can be done by putting a semicolon at the last statement. But formatteddisplaying of output can also be done and is considered flexible and preffered by someof the programmers to control the appearance of the data to be displayed. Table 23shows the syntax.
Sample Code
Start code
-->n = input(’Enter number’)
Enter number: 5
n =
5.
-->n = input(’Enter string’)
Enter string: ’a string must be enclosed with quotation’
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 79
Command Descriptionprintf Prints the formatted output to the console.
printf(’format’, val1, ..., valn)sprintf Returns the formatted output as string.
sprintf(’format’, val1, ..., valn)
Table 24: Formatting printing of output
n =
a string must be enclosed with quotation
-->n = input(’Enter number’,’s’);
Enter string: a string without quotation
n =
a string without quotation
--> //using disp function
-->disp(n,’user input = ’)
user input =
a string without quotation
End code
2.17 Formatting output display
Usage
Formatting output in a tabular form is oftenly used. Table 24 shows the command.
Format
Enclosed in <> are optional parameters.
%<+/-><pad>.<precision>placeholder
+/- +(plus) formats the value with sign prefixed to it, positive or negative. Defaultalignment is right-aligned. -(minus) formats the value left-aligned.
pad Integer number that serve as padding to the value adding space if pad value isgreater than the number of characters of the value to be formatted.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 80
Placeholder Descriptiond Integer placeholdere Scientific notation placeholder.f Floating-point placeholder.g Chooses between %f and %e. Whichever has the shortest format.s String placeholder.c Character placeholder.
Table 25: Placeholder for printf
precision Integer number that serve as the number of decimal places.
placeholder Placeholder for values, either d,e,f,g,s,c.
Placeholder
Table 25 shows placeholder used by printf formatter.
Sample Code
Start code
-->//format left-aligned, with padding of 10
-->//characters and with fixed 4 decimal places
-->printf("%-10.4f",12.41212532)
12.4121
-->s = sprintf("%-10.4f",12.41212532)
s =
12.4121
End code
2.18 Reading and writing data to a file
Usage
Saving to an file is useful for external storage of commands and data. Also, can beused for logging purposes. Table 26 shows reading of data from external file.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 81
Command Descriptionfscanf Read data from a file.
[out1,...,outn]=fscanf(’file’,’format’,var1,...,varn)
fprintf Output data to a file.fprintf(’file’,’format’,var1,...,varn)
diary(filename) Save current command from console to a filename. To stop savingto the file use diary(0) or open another diary with a new filename.Be careful of opening an existing file because the data inside willbe lost if you do so.
save Save current result from console to a file in *.dat format.load Load *.dat file into scilab workspace as matrix data.file Manage accessing of external file.pwd Print working directory.
Table 26: External file processing
Sample Code
Start code
-->//print the current working directory
-->pwd
ans =
C:\
-->//Save 5.2342 to mysample.txt file
-->fprintf(’mysample.txt’,’%0.4f’,5.234235)
-->//Reads a floating-point number from mysample.txt file
-->a=fscanf(’mysample.txt’,’%f’)
a =
5.2342
-->diary(’scilab_diary.txt’)
-->a=1
a =
1.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 82
-->hello
!--error 4
Undefined variable: hello
-->g=int(rand(3,3)*10+2)
g =
2. 9. 4.
7. 3. 4.
8. 7. 4.
-->diary(0)
-->not_recorded=’not in the text file’
not_recorded =
not in the text file
End code
scilab_diary.txt
-->a=1
a =
1.
-->hello
!--error 4
Undefined variable: hello
-->g=int(rand(3,3)*10+2)
g =
2. 9. 4.
7. 3. 4.
8. 7. 4.
-->diary(0)
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 83
Command Descriptionlasterror Get last recorded error message.errcatch Set a trap for a specified error and perform an action.error Issue an error with specified number and error message.errclear Clears the action of an error handler of type n if a error number is
specified, otherwise, clears all error.iserror Returns 1 if error occurs, and 0 otherwise.
Table 27: Error handling commands
2.19 Error handling and exceptions
Keywords: try, catch, lasterror, errcatch, error, end, errclear. iserror
Usage
Handling exceptions make the program robust without stopping program executon.Such exceptions like limiting input to a numeric character, warning message for out-of-bounds accessing of element in a matrix, and other user specified criteria, error reading afile or the file does not exist. To view the tabular list of errors, type help error_table.Table 27 shows command to handle errors.
Syntax
try
statements;
catch
[error_str,n,line,fname]=lasterror(<flag>)
end
error str Error string.
n Error code number.
line Error line.
fname Function name.
flag If %t (default) the error is cleared, if %f the error is retained for the next call.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 84
Sample Code
Start code
try
b = eyes(3,3)
catch
[s,n,line,fname]=lasterror()
end
End code
Output
fname =
line =
0.
n =
4.
s =
Undefined variable: eyes
2.20 Character and string manipulations
Usage
String manipulation is useful when parsing a string input.
Executing a command enclosed in a string
Table 29 shows how to evaluate a string command.
Regular Expression
Table 30 shows the basic syntax of regular expression. Same syntax with Perl regularexpression.Syntax
[start<,end<,token>>]=regexp(str,pattern<,’o’>)
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 85
Command Descriptionstring Converts other type to string type. After converting try to check
the type by issuing the command typeof with variable as argu-ment.
strtod Convert string to double.strcmp String compare.length Number of characters in a string.ascii Ascii equivalent in string form.grep Find string from list of strings.strrev Reverses a string.part Extracting substring.strtok Tokenize or split strings based on a given delimiter.strindex Searches a position of character(s) in a string.isalphanum Check if string is an alphanumeric character.isascii Check if string is an ascii character.isdigit Check if string is a digit.isletter Check if string is a letter.isnum Check if string is a numeric.
Table 28: String processing syntax
Command Descriptionevstr(str_array) Evaluate array of statements enclosed in string.eval(str_array) (Alternative of evstr) Evaluate array of statements enclosed in
string.exectr(instr) Execute a scilab instructions enclosed in string format. Instructions
are arrays of string statements separated by semicolon.
Table 29: Executing scilab command in string form
Command Descriptionregexp Finding a substring that matches the regular expression.
Table 30: Regular expression
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 86
where
str String input to search.
pattern Pattern of substring to locate.
’o’ Optional input parameter for locating substring once.
start Start index position of substring in a larger string.
end End index position of substring in a larger string.
token The text of each string that matches the pattern.
Start code
-->[a b c] = regexp(’this is a not-so-long string’,’/this/’)
c =
this
b =
4.
a =
1.
End code
2.21 Date and time
Table 31 shows some functions in processing date and time.
2.22 Miscellaneous functions
Table 32 shows some miscellaneous functions.
2.23 Exercises
1. Function, varargin, sprintf, printf, error handling
(a) Create a function that formats a floating-point number to a specified decimalprecision. The function receives two numbers, a floating-point and an integerand outputs a string formatted number. Use sprintf function, and try-catchto catch errors.
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 87
Command Descriptioncalendar Shows the current month calendar.clock Shows the current date and time. Format:
[year,month, day, hour,min, sec].date Current date showing day, month, and year.datenum Current date in long number type.datevec(t) Convert date in long format to date format
[yr,mo, day, hr,min, sec]. Sample: datevec(731129) returns[2001.10.5.0.0.0.] which means October 5, 2001 with zero hour,zero min and zero seconds.
eomday(y,m) End of month day, returns the last day of the month of a givenyear. Used to query how many days in a month of a given year.
etime([t2],[t1] Elapsed time.getdate Return current date and time information.now Returns the current time and date in long format.realtime(t) Set date origin if called once. Successive call waits till the the
argument time, t is reached.realtimeinit Set time unit. Used side-by-side by realtime.sleep(t) Suspend Scilab execution in t milliseconds.tic Start stopwatch timer.timer CPU time since preceding call of timer function.toc Stop stopwatch timer and return the elapsed time starting from
calling tic.weekday(t) Return day of the week given t milliseconds.
Table 31: Date and time
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 88
Command Descriptionpause Interrupts evaluation of a function. Useful for debugging purposes
which check for variables used inside the function. Level of inter-ruption is indicated by -n-> where n is the level.
abort Used to exit pause mode and return to standard level prompt, i.e.,from -n-> to -->.
[w1]=return(f1) Same function as resume but returns a variable from withinthe function to be loaded to the workspace. w1 is acopy of variable f1 from function which is loaded into theworkspace. Variable to be copied can be extended to any num-ber, [w1,w2,...]=return(f1,f2,...).
quit Exit Scilab.resume Interrupt pause mode and resume to next lower pause level, i.e.,
from -n-> to -(n-1)->.lines Paging of Scilab output showing the number of vertical lines and
columns to display before giving a prompt to continue display.Valid syntax: lines - shows the current paging setting, lines(0)- disable vertical line paging, lines(r) - sets number of lines todisplay to r, lines(r,c) - sets number of lines to r and columnsto c.
clc Clear the console display deleting previous commands from theconsole but not from the history.
tohome Clear the console display but does not delete the previous com-mands issued by the user. Can still use the scroll bar to browsepreviouse command.
editvar(’var’) Edit a variable var. Display a tabular editor for matrix type vari-able.
Table 32: Miscellaneous functions
Scilab Quick Reference (Early Access)Chapter 2: Programming Basics 89
(b) Create a function that outputs data in tabular form. The function receivesa variable input in pairs specifying the column name and the array of data.Number of columns vary depending on the input. No output to return butjust display a tabular form. Note: Do not format the data leave its formatthe way it is given. Mind the alignment of each column where column widthdepends on the longest character. Use try-catch to catch errors.
2. Scripts, inline function, string, regexUse try-catch to catch errors.
(a) Create a script that extracts all numbers in a given string equation.
(b) Create a script that extracts all variables in a given string equation.
(c) Create a script that extracts the constant of the equation in a given stringequation.
(d) Create a script that extract the coefficient matrix, constant matrix, and thevariables used. Your script must query for the number of equations and inputfrom user the equations in string format and save it in a string array. Insideyour script are an 3 different inline functions that extract coefficients, extractvariables and extract constant.
Chapter 3
Plotting
Scilab Quick Reference (Early Access) Chapter 3: Plotting 91
3 Plotting Basics
3.1 Objectives
• To know how to create a 2D plot from a given data or function.
• To learn how to customize plot properties.
• To know how to divide a graphics window to contain multiple plot.
• To know what are other plotting capabilities for Scilab.
• To know how to animate plotting in Scilab.
3.2 Definition of terms
Animation For demo purposes, used to visualize slow changing of properties.
Axis Determines the dimension of a plot.
Bar chart Chart where data are represented by bars in horizontal or vertical form.
Chart Pair of points arranged in an axes-bound diagram.
Figure Refers to the graph or plot.
Plot See Chart.
Pie chart Chart dividing a circle by percentage.
3.3 Introduction
Plotting, also known as charting, is very handy in Scilab as well as animating theplot. There are a lot of plotting function but we will select only those basic function.
3.4 Basic plotting
Keywords: plot, plot2d, plot2d, plot2d1, plot2d2, plot2d3, plot2d4
Scilab Quick Reference (Early Access) Chapter 3: Plotting 92
s Styles c Color m Marker- solid r red + plus-- dashed g green o circle: dotted b blue * asterisk-. dash-dotted c cyan . point
m magenta x crossy yellow s squarek black d diamondw white ^ up-pointing triangle
v down-pointing triangle> left-pointing triangle< right-pointing triangle
none No marker(default)
Table 33: Line specifications
Usage
Basic plotting involves 2 basic Scilab function, plot and plot2d. plot has anadvantage of being the same syntax with Matlab plot, that is if you are planning touse Matlab. While plo2d syntax is limited to Scilab only and other open-source mathsoftware but it is flexible compared to plot function.
plot
Syntax
plot(x,y[,’scm’])
• xvec - x data vector.
• yvec - y data vector.
• ’scm’ - line specifications. Characters can be reordered. Table 33 displays thecomplete list of line specifications.
Sample Code
Start code
Scilab Quick Reference (Early Access) Chapter 3: Plotting 93
Figure 12: Plot output
plot([1:5],2*[1:5],’k-*’)
End code
Output
Figure 12 shows the output for the plot.
3.5 plot2d
Syntax
plot2d(<x>,y<,prop1=value1,prop2=value2,...>)
Scilab Quick Reference (Early Access) Chapter 3: Plotting 94
Property Value Descriptionstyle -14|...|0|1|...|32 Value ≤ 0 styles the point marker while value ≥ 1
sets the line color.rect [xmin,ymin,xmax,ymax] Sets the minimum and maximum boundary of x
and y axis.logflag ’nn’|’nl’|’ln’|’ll’ Scale the axes linearly (’n’) or logarithmically (’l’).frameflag 0|...|8 Sets the frame bounding box of the graph.axesflag 0|...|5 Sets axes property how it is drawn. 0-plot the
data without axes; 1-plot the data enclosed in abox with x-tick on the bottom and y-tick on theleft with minimum tick as the minimum values; 2-plot the data enclosed in a box without x-tick andy-tick; 3-plot the data with x-tick on the bottomand y-tick on the left; 4-same as 1; 5-same as 1but starts at zero if minimum data is non-zero andhorizontal line at y = 0.
nax [nx,Nx,ny,Ny] nx,ny are minor ticks and Nx,Ny are major ticks.leg ’plot_name’ Sets the legend of the plot shown at the bottom
part of the graph below the x-axis.
Table 34: Plot2d properties and property values
x Horizontal matrix data. If omitted, generates 1:length(y).
y Vertical matrix data.
prop Properties of plot and its corresponding values, prop=value. Multiple propertiesare separated by commas. Table 34 shows the corresponding property values.
Sample Code
Start code
-->clf
-->//using 3 dots to continue command to next line
-->plot2d(-1:5,sin(-1:5),...
-->leg=’this is a caption’,...
-->style=3,...
-->axesflag=5)
Scilab Quick Reference (Early Access) Chapter 3: Plotting 95
Figure 13: Plot2d sample plot
End code
Output
Figure 13 shows sample output using plot2d.
plot2dx series
Table 35 shows the plot2d command with specific purpose.
Scilab Quick Reference (Early Access) Chapter 3: Plotting 96
Command Descriptionplot2d1 Plot a curve with logarithmic scale.plot2d2 Plot a curve as step function.plot2d3 Plot a curve with vertical bars.plot2d4 Plot a curve with arrows.
Table 35: Plot2dx series
3.6 Plotting a function
Keywords: fplot2d
Plotting a function is best done when defined first then use fplot2d command toplot it in a piecewise manner. Sample code is given below. The output displays a plotlike a mountain with smooth line interconnections.
Sample Code
Start code
-->deff("[y]=f(x)","y=sin(x)+cos(x)")
-->x=[0:0.1:10]*%pi/10;
-->fplot2d(x,f)
End code
3.7 Customizing plot
Grids and ticks
Usage
Table 36 shows some commands used to customize grids and axes ticks.
Sample Code
Start code
-->//using the figure generated by the previous code
-->//getting the handle of the current figure
Scilab Quick Reference (Early Access) Chapter 3: Plotting 97
Command Descriptionxgrid(<n>) Add x and y grid to the graph drawn in imaginary lines. To change
the color of the grid just specify the value of n.h=get(prop) Properties such as ’current_figure’ and ’current_axes’. Store
the handle to a variable and the properties will be displayed. Youcan set the property of figure or axes through dot operator.
set(prop,val) Setting the property of the figure or the axes. Value will be dis-played when storing the handle of figure or axes to a variable.
delete(h) Delete or remove an entity such as the figure, axes, children offigure or axes, or a callback with argument h as its handle.
drawaxis(opt) Manually change the orientation of the axis in the graphics window.opt are properties such as x,y,dir,sub_int,fontsize,format_n,seg,textcolor,ticscolor,tics.
copy(h) Copy a graphic entity with handle h.replot(vec) vec is a vector with 4 values designated as x-axis and y-axis bound-
aries.
Table 36: Grids and ticks property
-->f = get(’current_figure’)
f =
Handle of type "Figure" with properties:
========================================
children: "Axes"
figure_position = [156,92]
figure_size = [620,590]
axes_size = [610,460]
auto_resize = "on"
viewport = [0,0]
figure_name = "Graphic window number %d"
figure_id = 0
info_message = ""
color_map= matrix 32x3
pixmap = "off"
pixel_drawing_mode = "copy"
immediate_drawing = "on"
background = -2
Scilab Quick Reference (Early Access) Chapter 3: Plotting 98
visible = "on"
rotation_style = "unary"
event_handler = ""
event_handler_enable = "off"
user_data = []
tag = ""
-->//getting the handle of the current axes of the figure above
-->a = get(’current_axes’)
a =
Handle of type "Axes" with properties:
======================================
parent: Figure
children: ["Compound";"Legend"]
visible = "on"
axes_visible = ["on","on","on"]
axes_reverse = ["off","off","off"]
grid = [-1,-1]
x_location = "origin"
y_location = "origin"
title: "Label"
x_label: "Label"
y_label: "Label"
z_label: "Label"
auto_ticks = ["on","on","on"]
x_ticks.locations = [-1;0;1;2;3;4;5]
y_ticks.locations = matrix 11x1
z_ticks.locations = []
x_ticks.labels = ["-1";"0";"1";"2";"3";"4";"5"]
y_ticks.labels = matrix 11x1
z_ticks.labels = []
box = "on"
filled = "on"
sub_ticks = [3,1]
font_style = 6
Scilab Quick Reference (Early Access) Chapter 3: Plotting 99
font_size = 1
font_color = -1
fractional_font = "off"
isoview = "off"
cube_scaling = "off"
view = "2d"
rotation_angles = [0,270]
log_flags = "nnn"
tight_limits = "off"
data_bounds = [-1,-0.9589243;5,0.9092974]
zoom_box = []
margins = [0.125,0.125,0.125,0.125]
axes_bounds = [0,0,1,1]
auto_clear = "off"
auto_scale = "on"
hidden_axis_color = 4
hiddencolor = 4
line_mode = "on"
line_style = 0
thickness = 1
mark_mode = "off"
mark_style = 0
mark_size_unit = "tabulated"
mark_size = 0
mark_foreground = -1
mark_background = -2
foreground = -1
background = -2
arc_drawing_method = "lines"
clip_state = "clipgrf"
clip_box = []
user_data = []
-->//a.parent is the same as get(’current_figure’)
Scilab Quick Reference (Early Access) Chapter 3: Plotting 100
-->// indicated as parent of axes handle shown above
-->//check the children of axes before accessing handles
-->a.children(1) // compound handle
ans =
Handle of type "Compound" with properties:
==========================================
parent: Axes
children: "Polyline"
visible = "on"
user_data = []
-->a.children(2) // legend handle
ans =
Handle of type "Legend" with properties:
========================================
parent: Axes
children: []
visible = "on"
text = "this is a caption"
font_style = 6
font_size = 1
font_color = -1
fractional_font = "off"
links = "Polyline"
legend_location = "lower_caption"
position = [0.1245902,0.8814130]
line_mode = "off"
thickness = 1
foreground = -1
fill_mode = "off"
background = -2
clip_state = "off"
clip_box = []
user_data = []
Scilab Quick Reference (Early Access) Chapter 3: Plotting 101
Command Descriptionxtitle(’title’) Adds title to the plot shown at the center top of
the plot. To add label on x-axis and y-axis usextitle(’title’,’x-label’,’y-label’<,boxed=1>) whereboxed optional property surround the label with a box.
title(’title’) More styles in setting the title of the plot. Styles arebackgroundcolor, color, edgecolor, fontname, fontsize,position, rotation, visible.
Table 37: Adding label to the plot
Command Descriptionlegend(h,’leg1’) Add legend to the plot of figure with handle h, ’leg1’ is the name
of the plot. Specify another string if there are multiple plots. Is-sues error if the number of plot is less than the number of stringargument.
caption Add a string to the plot specifying a defined location. Syntax:leg = caption(p,’str’,location) returns a legend handle.
Table 38: Legends and captions
End code
Label and title
Table 37 shows some command to add title and label to the plot.
Usage
Legend and caption
Usage
Table 38 shows command how to add legend and captions to the plot.
Multiple plot in a graphics window
Usage
Table 39 shows how to arrange a multiple plot in a single graphics window.
Scilab Quick Reference (Early Access) Chapter 3: Plotting 102
Command Descriptionsubplot(rci) Divides the plot into a matrix of plot. r for row, c for column, and
i for index to place the next plot. Index positioning starts fromtopmost-left going to right then down to the bottom.
Table 39: Multiple plot in a single graphics window
Sample Code
Start code
subplot(221)
plot2d()
subplot(222)
plot3d()
subplot(2,2,3)
param3d()
subplot(2,2,4)
hist3d()
End code
Output
Figure 14 shows the sample output of multiple plot in a graphics window.
Adding text in a plot
Usage
Table 40 shows how to add text to the plot.
Sample Code
Start code
-->plot2d
-->xstring(1,-1.5,’string’)
-->xstring(1,-1.5,’string90’,90)
-->xstring(1,-1.5,’stringM90’,-90)
Scilab Quick Reference (Early Access) Chapter 3: Plotting 103
Figure 14: Multiple plot
Command Descriptionxstring xstring(x,y,’string’<angle<,boxed>>). x and y are coordi-
nates of lower-left point of the string based on the ticks specifiedby the graph. ’string’ is the string of characters to display onthe graph. angle is the angle of inclination of the string in degrees.boxed is either 1 or 0, 1 for drawing a frame around the string and0 (default) for no frame around. Boxed string is possible if angleis zero.
xstringb Draw a string in a box.xstringl Computes the box that surrounds the string.stringbox Compute the bounding rectangle of a text.
Table 40: Adding text to the plot
Scilab Quick Reference (Early Access) Chapter 3: Plotting 104
Figure 15: Text to a plot
End code
Output
Figure 15 shows the sample output for adding string to the plot.
Capturing points from the plot
Usage
Table 41 shows command how to capture mouse click.
Scilab Quick Reference (Early Access) Chapter 3: Plotting 105
Command Descriptionlocate(n) Used to point n coordinates from the plot through mouse click.
After the locate command is issued, the focus is transferred tothe plot.
xclick Wait for mouse button to be clicked. Mouse button captures left,middle (if any) or right mouse click.
Table 41: Capture points in a plot using mouse click
Command Descriptiondraw(h) Called after drawlater. Draws a plot with argument graphic han-
dle of polyline.drawlater Draw the plot later called by draw.drawnow Called when showing the plot after drawlater and draw command.
Table 42: Drawlater commands
Drawing plot later
Usage
Table 42 shows how to plot and draw later.
Sample Code
Start code
subplot(212)
a=gca();
plot2d
drawlater
subplot(211)
plot2d1 // default drawing mode
e=gce();
draw(e.children(2)) // draw a single polyline of the second axes
e.children(1).visible=’off’; // We can choose to make a line invisible
draw(e) // draw Compound and its children <=> draw all the visible polylines
drawnow // ...now!
e.children(1).visible=’on’;
Scilab Quick Reference (Early Access) Chapter 3: Plotting 106
Command Descriptiongcf Get current figure. Returns the current figure. Same as
get(’current_figure’) command.clf Clear current graphics window.
Table 43: Miscellaneous functions
Command Descriptionparamfplot2d Animate the function plotting.twinkle Blink the current polyline of the plot.
Table 44: Animate plot
End code
Note: Code below is excerpted from the help sample code of Scilab.
Miscellaneous
Usage
Table 43 shows some miscellaneous functions in plotting.
Customizing plot graphically
Plot can be customized after generating it such as changing the properties of theaxes, ticks, tick label, title, line color, line style, etc. There are commands used tocustomized such properties but in this chapter we will be using the graphical axesproperties editor. Axes editor window can be accessed through the menu provided bygraphics window. See figure 16 and 17.
3.8 Animating 2D plot
Usage
Animating plot is useful when visualizing a certain chart and emphasizing a plot.Animation gradually changes one of the parameter, commonly the amplitude. Table 44shows how to add animation to the plot for emphasis.
Scilab Quick Reference (Early Access) Chapter 3: Plotting 107
Figure 16: Axes properties editor menu
Sample Code
Start code
/*******************
* animate_plot.sce
*******************/
//function to animate
function y=f(x,t)
y = t*(exp(-x)-x-10);
endfunction
//script to animate function above
x=linspace(-5,0,100);
theta=0:0.05:1;
paramfplot2d(f,x,theta);
// adding a line of intersection
plot(x,zeros(1,length(x)))
Scilab Quick Reference (Early Access) Chapter 3: Plotting 108
Figure 17: Axes properties editor window
Scilab Quick Reference (Early Access) Chapter 3: Plotting 109
Command Descriptionpolarplot Polar plot.histplot Histogram plot.bar Vertical bar plot.barh Horizontal bar plot.pie Pie chart.errbar Error bar plot.
Table 45: Other types of plotting data
Command DescriptionMatplot Plot a matrix data by colors.contour2d Level curves of a surface.champ Plot the vector field with arrow direction.grayplot Plot data by colors.graypolarplot Plot data by colors in polar coordinates.
Table 46: Surface plotting
// blinking the line
a = get(’current_axes’);
twinkle(a.children(1))
End code
Output
The output above shows a graphics window with plot that changes gradually itsamplitude then draws blue line across y = 0 and blink the line for a few times.
3.9 Other types of plot
Data plotting
Table 45 shows other types of data plotting.
Surface plotting
Table 46 shows some surface plotting capabilities of Scilab.
Scilab Quick Reference (Early Access) Chapter 3: Plotting 110
Command Descriptionxpoly Draw a polyline or a polygonxpolys Draw a set of polylines or polygonsxrpoly Draw a regular polygonxsegs Draw unconnected segmentsxfpoly Fill a polygonxfpolys Fill a set of polygons
Table 47: Polygon plotting
Polygon plotting
Table 47 shows some polygon plotting in Scilab.
3.10 Sample Application
Start code
function y = f(x)
y = exp(-x)-x-10;
endfunction
//plot function
fplot2d([-3:0.1:1],f)
//draw horizontal line on x = 0
xpoly([-3,1],[0,0])
xi=[-2.5,0];
i=1;
maxIter = 5;
for k = 1:maxIter
fL = feval(xi(i,1),f);
fU = feval(xi(i,2),f);
plot(xi(i,1)*ones(1,2),[0, fL],’--g’)
plot(xi(i,2)*ones(1,2),[0, fU],’--g’)
// compute approx root, xr
xr(i) = (xi(i,1)+xi(i,2))/2;
fR = feval(xr(i),f);
Scilab Quick Reference (Early Access) Chapter 3: Plotting 111
plot(xr(i)*ones(1,2),[0, fR],’--r’)
// check which interval the root is bracketed
if(fL*fR > 0) //[xR,xU]
xi(i+1,1) = xr(i);
xi(i+1,2) = xi(i,2);
elseif(fL*fR < 0) //[xL,xR]
xi(i+1,1) = xi(i,1);
xi(i+1,2) = xr(i);
else
root = xr(i);
break; //terminate loop
end
if(i>1)
er(i) = abs((xr(i)-xr(i-1))/xr(i))*100;
else
er(i) = 100;//100%
end
msg = char([’Iteration ’,string(i),’:’;...
’xr = ’,string(xr(i)),’’;...
’%er = ’,string(er(i)),’’]);
messagebox(msg,’modal’);
i = i+1;
end
//summary
x_mdialog(’xr’,string(1:length(xr)),string(xr))
x_mdialog(’er’,string(1:length(er)),string(er))
End code
3.11 Exercises
1. Plotting a digital pulse
Scilab Quick Reference (Early Access) Chapter 3: Plotting 112
Figure 18: Digital signal plot output
(a) Plot the digital signal [1, 1, 0, 0, 1, 0, 1] in digital pulse which is a square pulse.
(b) Label x− axis with tick label in center between 2 ticks. Label y − axis tick,and the title as ’Digital Signal’.
(c) Plot the following data in a stair plot.
x = [1, 2, 3, 4, 5]
y = [1, 2, 5, 3, 2]
2. Customizing plot
(a) Add string, legend, ticks, and grid for the plot in problem 1.
Scilab Quick Reference (Early Access) Chapter 3: Plotting 113
3. Animating plot
(a) Animate the plot in problem 1.
4. Capturing mouse interaction
(a) Capture 3 points in the plot using mouse click.
5. Polygon plotting
(a) Create a pentagon with center at (3, 3). Create a nonagon with center at (3, 4)and overlay the plot from the previous plot. Fill the intersection between twopolygons. Compute for the area of intersection.
Chapter 4
Dialogs
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 115
4 Dialogs
4.1 Objectives
• To use dialogs to visualize the resulting data.
• To emphasize given data used for calculation in a dialog.
4.2 Definition of terms
Dialog A popup window that exits after displaying a short info, prompt or confirma-tion.
Modal Mode of displaying a dialog that blocks interaction with the console while thedialog appears.
4.3 Introduction
Dialogs are oftenly used to visualize a data temporarily. It is often used than full-pledge GUI since it is easy to code. As easy as no assigning of dialog ID, callbackfunctions and other controls. Each dialog has its own usage. Table below lists thedialogs available in Scilab excluding the obsolete functions.
Dialog boxes returns the result in string form. To convert string into number youcan use strtod to convert string to double, eval or evstr to evaluate the string asScilab command. Table 48 shows list of available dialog boxes in Scilab.
4.4 messagebox
Figure 19 shows the message box screenshots.
Syntax
[btn] = messagebox(msg<,title<,icon<,but_arr<,modal>>>>)
msg Message in string.
title Title of the dialog in string.
icon String that can be either: ’error’ | ’info’ | ’passwd’ | ’question’ | ’warning’|’scilab’.
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 116
Figure 19: messagebox sample
Figure 20: progressionbar sample
but arr Array of string as label of buttons such as [’ok’,’maybe’,’cancel’].
modal A ’modal’ string used to specify dialog as modal.
4.5 progressionbar
Table 49 shows syntax for displaying progress bar window that shows progress of acommand. Figure 20 shows the pogress bar screenshots.
4.6 waitbar
Table 50 shows syntax for displaying progress bar window that shows progress of acommand with definite percentage of progress. Figure 21 shows the waitbar screenshots.
4.7 x dialog
Figure 22 shows the screenshots.
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 117
Command Descriptionmessagebox Display the message in a popup dialog.progressionbar Display an indefinite progress bar.waitbar Display an updated progress bar.x_dialog Input dialog that accepts input and returns the value in string.x_choices List of choices that uses toggle buttons for list of choices.x_choose A list of string to choose. Double-click the item to select it.x_choose_modeless A modeless dialog version of x_choose.x_mdialog Input dialog arranged in matrix for multiple inputs.x_matrix Similar to x_dialog but used for editing a matrix. If the type
of matrix is numeric, the return type is also numeric rather thanstring.
Table 48: Dialog boxes
Command Descriptionw=progressionbar(str) Displays the indefinite progress bar and returns the handle w.
This is used to initialize progress bar. str is a string such as’Initializing...’.
progressionbar(w,str) Updates the string of the progress bar with handle w.winclose(w) Closes the progress bar.
Table 49: Progress bar
Command Descriptionw = waitbar(str) Displays the indefinite progress bar and returns the handle w.
This is used to initialize progress bar. str is a string such as’Initializing...’.
waitbar(p,str,w) Updates the string of the progress bar with handle w specifying thepercentage p.
winclose(w) Closes the progress bar.
Table 50: Waitbar
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 118
Figure 21: waitbar sample
Figure 22: xdialog sample
Syntax
r = x_dialog(prompt,default)
prompt A string that prompts for the user. Prompt can be multiline by using vectorsof string.
default Default value in string. Can be matrix to extend height of input textfield.
r Output results to [] if cancelled and returns the input in string.
4.8 x mdialog
Figure 23 shows the screenshots.
Syntax
rvec = x_mdialog(title,rowlabel,default_values)
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 119
Figure 23: x mdialog sample
rmat = x_mdialog(title,rowlabel,collabel,default_values)
title A string that prompts the user for input. Prompt can be multiline by usingvectors of string.
rowlabel Vector of row labels.
collabel Vector of column label.
default values It can be column vector for one column or a matrix if row and columnlabel are provided. Note: default values must be a string array. Use string toconvert numeric data to string type.
rvec Vector input data. Output results to [] if cancelled and returns the input instring.
rmat Matrix input data. Output results to [] if cancelled and returns the input instring.
4.9 x choices
Figure 24 shows the screenshots.
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 120
Figure 24: x choices sample
Syntax
result = x_choices(title,list(list(lbl,default_int,choices)...
<,list(’lbl’,default_int,choices)<,...>>))
title A string that prompts the user for input. Prompt can be multiline by usingvectors of string.
list A Scilab keyword that creates a list.
lbl A string which is a label of its respective toogle choice list.
default int An integer value which is the index of the selected choice item.
choices A vector of toggle items in string type.
result A result in vector form for multiple choices which is in integer type specifyingthe selected index of each choice.
4.10 x choose
A modal dialog that shows a list of items. Use x\_choose\_modeless to set thepopup dialog to non-modal, i.e., it does not block interacting the console while thedialog appears. Figure 25 shows the screenshots.
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 121
Figure 25: x choose sample
Syntax
choice = x_choose(item_vec,title<,button_text>)
item vec List of items in vector.
title A string that specifies the popup dialog title.
button text Text of the button below the list. Default value is ’Cancel’.
4.11 x matrix
Figure 26 shows the screenshots.
Syntax
m = x_matrix(prompt,init_mat)
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 122
Figure 26: x matrix sample
prompt Prompt string for the user.
init mat Initial value of the matrix. This determines the dimension of the matrix tobe edited.
m The resulting matrix.
4.12 Sample Application
Start code
function y = f(x)
y = exp(-x)-x-10;
endfunction
//plot function
fplot2d([-3:0.1:1],f)
//draw horizontal line on x = 0
xpoly([-3,1],[0,0])
xi=[-2.5,0];
i=1;
maxIter = 5;
for k = 1:maxIter
fL = feval(xi(i,1),f);
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 123
fU = feval(xi(i,2),f);
plot(xi(i,1)*ones(1,2),[0, fL],’--g’)
plot(xi(i,2)*ones(1,2),[0, fU],’--g’)
// compute approx root, xr
xr(i) = (xi(i,1)+xi(i,2))/2;
fR = feval(xr(i),f);
plot(xr(i)*ones(1,2),[0, fR],’--r’)
// check which interval the root is bracketed
if(fL*fR > 0) //[xR,xU]
xi(i+1,1) = xr(i);
xi(i+1,2) = xi(i,2);
elseif(fL*fR < 0) //[xL,xR]
xi(i+1,1) = xi(i,1);
xi(i+1,2) = xr(i);
else
root = xr(i);
break; //terminate loop
end
if(i>1)
er(i) = abs((xr(i)-xr(i-1))/xr(i))*100;
else
er(i) = 100;//100%
end
msg = char([’Iteration ’,string(i),’:’;...
’xr = ’,string(xr(i)),’’;...
’%er = ’,string(er(i)),’’]);
messagebox(msg,’modal’);
i = i+1;
end
//summary
x_mdialog(’xr’,string(1:length(xr)),string(xr))
x_mdialog(’er’,string(1:length(er)),string(er))
Scilab Quick Reference (Early Access) Chapter 4: Dialogs 124
End code
Chapter 5
Graphical User Interface (GUI)
Scilab Quick Reference (Early Access) Chapter 5: GUI 126
5 Graphical User Interface
5.1 Objectives
• To use UI controls and layout to form an application.
5.2 Definition of terms
User Interface See UI.
UI ,UI controls, user interface controls, or controls, are components used to visualizeand receive input from the user.
Graphical User Interface A form that uses UI controls and layout to simulate anapplication.
GUI See Graphical User Interface.
5.3 Introduction
Graphical user interface is widely used to create an application that arranges visu-alization in an orderly manner for more user-friendly application.
5.4 UI controls
Keywords: uicontrol
Table 51 shows different styles of UI controls.
5.5 Figure properties
Table 52 shows some figure properties.
5.6 UI properties
Table 53 and 54 shows properties of each UI control styles.
Scilab Quick Reference (Early Access) Chapter 5: GUI 127
Controls Descriptiontext Static text used as label.edit Editable text where user can input data.slider Draggable sliders that changes its value and updates bar position.pushbutton A button used for triggering events when clicked.radiobutton A selection button that allows a single selection.checkbox A selection box that allows multiple selection.frame A boundary marker used to group related components.listbox A list of data.popupmenu A list of data that displays one data and the rest of the data are
accessible by cliking the drop down button.
Table 51: UI control styles
Property Valuesbackgroundcolor Vector. [r, g, b] where r, g, b values are between [0, 1]figure_name String.foregroundcolor Vector in [r, g, b] values.position Vector such as [x, y, width, height]tag String.userdata Vector.
Table 52: Figure properties
Property Valuescallback Callback function in string.parent Handle of the parent container where the UI is being laid out.position Contains the position and size of the control given in a vector such
as [x,y,w,h], with (x, y) as coordinates, w and h as width andheight respectively. Unit is in pixel.
relief Border style such as ’groove’ | ’sunken’ | ’raised’string Label within the UI control.style UI contol style such as ’edit’ | ’text’ |tag Identifier of the UI control in string.
Table 53: Basic properties of UI control styles
Scilab Quick Reference (Early Access) Chapter 5: GUI 128
Property Valuesbackgroundcolor Background color of the figure or the UI control.enable Set UI control to enable.fontangle Set the font angle.fontsize Set the font size.fontunits Set the units of the font.fontweight Set the fontweight.fontname Set the fontname.foregroundcolor Color of the font.horizontalalignment Horizontal alignment of the text inside UI control.listboxtop Set the listbox to be on the top.max Sets the maximum values of a specific UI control such as slider.min Sets the minimum values of a specific UI control such as slider.path Sets the path of the UI control.sliderstep Sets the sliderstep of the slider UI control.units Sets the units to be used.userdata Sets the global userdata value.value Value of the UI control.verticalalignment Vertical alignment of the text inside UI control.visible Set visibility of UI control in the figure.
Table 54: Other UI properties
Scilab Quick Reference (Early Access) Chapter 5: GUI 129
Property Valuesgcbo Returns the handle of the calling object.findobj(’tag’,’id’) Returns the handle of UI control with tag equals to id.
Table 55: Callback functions
5.7 Layouting
Layouting Figure
Figure positioning has top-left corner as (x, y) starting coordinates and the referenceis at top-left corner of the screen.
Layouting UI controls
Uses absolute positioning where the origin, (0, 0), is located in the lower-left cornerof the graphics window.
Layouting Axes
Incorporating axes plot in a UI application is sometimes necessary in an application.To position axes, use axes_bounds property.
5.8 Callback functions
Table 55 shows how to target UI object.
5.9 Other useful dialogs
Keywords: uigetdir, uigetfile, uigetcolor
5.10 Sample Application
Start code
function drawaxes()
//drawlater();
newaxes();
a = gca();
Scilab Quick Reference (Early Access) Chapter 5: GUI 130
a.axes_bounds = [1/4,0,2/3,1];
endfunction
// create a figure window with default toolbar and menu
fh = scf();
// hide toolbar
toolbar(fh.figure_id,’off’);
// hide File menu
delmenu(fh.figure_id,’File’);
// hide Tools menu
delmenu(fh.figure_id,’Tools’);
// hide Edit menu
delmenu(fh.figure_id,’Edit’);
// hide ? menu
delmenu(fh.figure_id,’?’);
fh.background = -2;
fh.figure_position = [100,100];
fh.figure_size = [500,310];
// create a textfield UI
tf = uicontrol(’parent’,fh,...
’position’,[13,182,100,20],...
’string’,’text’,...
’tag’,’tfid’,...
’style’,’edit’,...
’backgroundcolor’,[1 1 1],...
’relief’,’groove’);
// create a button UI
but = uicontrol(’parent’,fh,...
’position’,[18,160,85,20],...
’string’,’plot’,...
’tag’,’bid’,...
’style’,’pushbutton’,...
’foregroundcolor’,[1 1 1],...
’callback’,’change_relief’);
Scilab Quick Reference (Early Access) Chapter 5: GUI 131
// call internal function, drawaxes()
drawaxes();
plot(1:5,1:5);
function change_relief()
set(gcbo,’relief’,’sunken’);
sleep(100);
set(gcbo,’relief’,’raised’);
str = get(findobj(’tag’,’tfid’),’string’);
messagebox(string(evstr(str)),’modal’);
f = gcf();
delete(f.children(1));
messagebox(’Deleted previous plot.’,’modal’);
drawaxes();
a = gca();
plot(a,evstr(str),evstr(str));
endfunction
End code