Chapter 1
Chapter 1
Introduction to Scilab
Today, a wide range of software tools are available for scientific and engineering compu-
tations. Among them, Scilab stands out as a robust and accessible platform due to its
open-source nature, cost-free availability, and user-friendly interface. It enables students,
educators, and researchers to efficiently solve complex mathematical problems, perform
simulations, and visualize data without the burden of expensive licensing.
Scilab provides an extensive library of built-in functions for algebra, calculus, sig-
nal processing, numerical analysis, and various other domains. Furthermore, it supports
high-quality two-dimensional and three-dimensional graphics, thereby enhancing the in-
terpretation and presentation of computational results. Its compatibility with multiple
operating systems, including Windows, Linux, and macOS, ensures that it remains widely
accessible across diverse academic and research environments.
For schools, colleges, and universities, Scilab serves as an effective pedagogical tool for
teaching programming, mathematical modeling, and scientific computing. By combin-
ing affordability with powerful computational capabilities, it offers an ideal platform for
fostering analytical thinking and practical problem-solving skills in both academic and
professional contexts.
1
2 Chapter 1. Introduction to Scilab
load operations as needed. Furthermore, users can develop their own modules, making
Scilab adaptable to specialized research problems and domain-specific applications.
Applications of Scilab
Scilab has numerous applications across education, research, and industry, making it an
indispensable platform for scientific and engineering computation. Its major applications
include:
Signal and Image Processing: Provides powerful libraries to analyze, filter, and
process signals and images effectively.
Advantages:
Scilab is a powerful open-source platform widely used for scientific and engineering com-
putation. Like any software, it offers several advantages but also has certain limitations
that users should be aware of.
Open-Source and Free: Scilab is available under the CeCILL license, allowing
unrestricted use, modification, and distribution, which is ideal for academic and
research environments.
Disadvantages
Steep Learning Curve for Beginners: Although user-friendly, new users may
require time to become familiar with its environment and scripting language.
4 Chapter 1. Introduction to Scilab
In the early 1990s, the distribution of Basile by Simulog was discontinued, creating the
need for a new, freely accessible computational platform. In response, a team of re-
searchers from INRIA and the ENPC)(École Nationale des Ponts et Chaussées) collab-
orated to develop what is now known as Scilab. The first official version, Scilab 1.1, was
released in 1994 as an open-source software package, marking the beginning of a new era
in numerical computation and academic research tools.
As the user base of Scilab expanded rapidly across academia and industry, INRIA es-
tablished the Scilab Consortium in 2003. The primary objective of the consortium
was to coordinate its development, ensure long-term sustainability, and create a collab-
orative framework between developers and users. In 2008, the Scilab Consortium was
integrated into the Digiteo Research Network, further strengthening its research and
development ecosystem.
1.2. Getting Started in Scilab 5
In 2010, the creation of Scilab Enterprises marked a significant milestone in the profes-
sionalization of Scilab. With the support of INRIA, Scilab Enterprises assumed responsi-
bility for its continued development, maintenance, and professional support services. In
2017, the company was acquired by ESI Group, a global leader in virtual prototyping
software, thereby reinforcing the strategic importance of Scilab as a robust open-source
alternative to commercial computational tools.
Modern Scilab
Today, Scilab stands as one of the most prominent open-source platforms for scientific
and engineering computation. It offers comprehensive numerical capabilities, seamless in-
tegration with external programming languages, and advanced visualization tools. Sup-
ported by a vibrant global community, Scilab continues to evolve in alignment with
academic, research, and industrial demands, solidifying its position as a powerful and ac-
cessible computational environment for students, educators, and professionals worldwide.
Installing Scilab
Scilab is freely available and can be downloaded from its official website:
https://www.scilab.org/download
1. Access the Official Website: Navigate to the official Scilab download page and
review the available versions to ensure compatibility with your operating system
(Windows, Linux, or macOS).
2. Download the Installer: Select the appropriate installer package based on your
operating system and system architecture (32-bit or 64-bit).
3. Run the Installer: Execute the downloaded installation file and follow the on-
screen instructions provided by the setup wizard.
4. Accept the License Agreement: Read and agree to the CeCILL License terms
to proceed with the installation.
6. Launch Scilab: Once installation is complete, open Scilab from the Start menu
(Windows) or Applications folder (macOS/Linux) to verify that the software has
been successfully installed.
This installation process ensures that Scilab is correctly configured and ready for use in
academic, research, and industrial environments.
Console Window: The primary interactive environment where users can enter
commands, execute scripts, and immediately view computational results.
Editor: A built-in text editor used for creating, editing, and saving scripts (.sce)
and functions (.sci) for modular and reusable code development.
Variable Browser: Displays all active variables, including their names, data types,
dimensions, and values, enabling easy monitoring of computational workflows.
Collectively, these components provide a robust, user-friendly environment for both be-
ginners and advanced users, supporting a wide range of academic, research, and industrial
applications.
1.3. The Scilab Environment 7
Error Handling and Debugging: The console provides clear error messages and
diagnostic information, assisting users in identifying and resolving coding issues.
Integration with the Editor: Commands and scripts developed in the Scilab Ed-
itor can be executed directly from the console, ensuring smooth integration between
script-based and interactive workflows.
For instance, simple arithmetic and scientific computations can be performed directly in
the console, as shown below:
--> 5 + 3
ans = 8
--> 10 - 4
ans = 6
--> 7 * 6
ans = 42
--> 20 / 4
ans = 5
--> 3^2
ans = 9
8 Chapter 1. Introduction to Scilab
--> sqrt(25)
ans = 5
--> sin(%pi/2)
ans = 1
--> cos(0)
ans = 1
--> log(10)
ans = 2.3026
--> exp(1)
ans = 2.7183
This interactive approach makes the console an indispensable tool for both beginners
and experienced users, supporting exploratory learning and rapid algorithm testing in an
academic and research context.
Figure 1.1 illustrates the Scilab Console interface.
of a command, it determines whether the result is immediately printed on the screen. Un-
derstanding this behavior is crucial for writing efficient and organized code, particularly
in large programs or scripts where suppressing unnecessary output improves readability.
When a command is terminated with a semicolon, Scilab executes the command but
suppresses the display of the result in the console. This feature is commonly used in
scripts or functions to avoid cluttering the console with intermediate results that are not
immediately required.
--> a = 5 + 3;
Here, the variable a is assigned the value 8. However, no output is displayed because
the semicolon instructs Scilab to perform the operation silently.
When a command is executed without a semicolon, Scilab computes the result and dis-
plays the output in the console. This is helpful during interactive sessions when the
user wants to verify intermediate results or debug computations.
--> b = 10 - 2
b =
8.
In this example, Scilab not only assigns the value 8 to the variable b but also imme-
diately displays it in the console.
Editor (SciNotes)
The SciNotes in Scilab is an integrated development environment specifically designed
for creating, editing, and managing Scilab scripts. By offering tools such as syntax
highlighting, automatic indentation, and error-checking mechanisms, SciNotes supports
the development of well-organized, readable, and maintainable code.
Integrated Execution: Allows direct execution of scripts from the editor without
switching back to the console.
Debugging Support: Highlights syntax errors and offers basic debugging capa-
bilities to accelerate problem resolution.
Search and Replace: Enables quick location and modification of variables, func-
tions, or text blocks within scripts.
SciNotes can be launched from the Scilab console using the following commands:
To open a blank editor window:
--> scinotes();
--> scinotes(’filename.sce’);
--> editor();
1.4. Semicolon Usage in Scilab 11
Example
--> scinotes(’circleArea.sce’);
Graphics Window
The Graphics Window in Scilab serves as the primary interface for generating and visu-
alizing graphical outputs. It supports both two-dimensional (2D) and three-dimensional
(3D) plots, providing researchers, educators, and engineers with a powerful platform for
data visualization, analysis, and presentation.
Key Features
Remarks
Clearing Figures: Use the clf (clear figure) command before generating new
plots to avoid overlapping graphical elements.
Annotations: Always include appropriate titles, axis labels, legends, and anno-
tations to ensure that visualizations are self-explanatory and suitable for academic
documentation.
12 Chapter 1. Introduction to Scilab
Saving Plots: Save important plots using the xs2png, xs2pdf, or xs2svg func-
tions to maintain a record of results and integrate them seamlessly into reports or
publications.
The following example demonstrates how to generate a simple 2D plot and save it as
a PNG file:
x = 0:0.1:2*%pi;
y = sin(x);
plot(x, y);
title("Sine Wave");
xlabel("x-axis");
ylabel("sin(x)");
xs2png(gcf(), "sine_plot.png");
Help Browser: The help command opens the integrated help browser, which
contains categorized documentation of Scilab’s functions, toolboxes, and examples.
help plot
Keyword Search: The apropos command allows searching for specific keywords
across all documentation topics. This is particularly helpful when the exact function
name is unknown.
apropos("keyword")
apropos("matrix")
1.5. Comments and Continuation Lines in Scilab 13
This command lists all help topics associated with the keyword “matrix.”
demo_gui()
https://help.scilab.org
Remarks
Always download Scilab from the official website to ensure security and authenticity.
Comments in Scilab
In Scilab, single-line comments begin with two forward slashes //. Any text following //
on that line is ignored by the interpreter.
Scilab does not support multi-line comments using a single block syntax (like /* ...
*/ in C). Instead, multiple single-line comments may be used:
14 Chapter 1. Introduction to Scilab
a = 1 + 2 + 3 + 4 + 5 + ...
6 + 7 + 8 + 9 + 10;
Remarks
Proper commenting enhances program maintainability and makes it easier for others
to understand your work.
The following table summarizes some of the most frequently used keywords in Scilab,
along with their descriptions:
Keyword Description
if, then, Used for conditional branching in programs.
elseif, else,
end
for, while, Looping constructs for iterative execution and flow con-
break, trol.
continue
function, Used for defining and terminating user-defined func-
return, tions.
endfunction
select, case, Implements switch-case control structures.
else, end
try, catch, end Handles exceptions and runtime errors gracefully.
global Declares global variables accessible across multiple func-
tions.
nil Represents a null or empty value.
and, or, not Logical operators for conditional expressions.
true, false Boolean constants representing logical truth values.
pause Temporarily halts program execution until user input is
received.
return Exits from a function and optionally returns a value.
abort Immediately terminates program execution.
16 Chapter 1. Introduction to Scilab
Remarks
Keywords are case-sensitive in Scilab. For example, if is valid, but If will result
in an error.
Do not use keywords as variable names to avoid ambiguity and syntax errors.
Variables in Scilab do not require explicit type declarations. A variable is created as soon
as it is assigned a value using the assignment operator (=).
Reserved keywords (e.g., if, for, while, function) cannot be used as variable
names.
Checking Variables
Remarks
To write clean, efficient, and error-free programs, the following practices are recom-
mended:
1. Use descriptive names: Instead of generic names such as x1 or val, use mean-
ingful names like radius or matrixA.
2. Avoid using reserved keywords: Do not assign values to names such as if,
while, or function, as these are reserved for language constructs.
4. Clear unused variables: Free memory by removing variables that are no longer
needed:
clear variable_name
5. Verify variable type: Use the typeof() function when dealing with complex
operations to ensure data type compatibility.
Examples
18 // Boolean operations
19 isTrue = %t ; // Result : true
20 isFalse = %f ; // Result : false
Remarks
%eps is especially useful for numerical methods that require tolerance levels when
comparing floating-point numbers.
1. Numeric Types
Numeric types are the most commonly used data types in Scilab. They include both
integers and floating-point numbers.
a = 10; // Integer
b = 3.14; // Floating point number
Integers
Integers are whole numbers without any fractional or decimal component. Scilab supports
several integer types such as int8, int16, int32, and int64 (both signed and unsigned).
--> a = int16(10)
a =
10
Note: By default, Scilab uses double-precision floating point for numeric operations.
If specific integer precision is required (e.g., for memory optimization), explicit conversion
functions such as int8(), int16(), etc. should be used.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Right Division (A / B means A · inv(B))
\ Left Division (A \ B means inv(A) · B)
^ Exponentiation (Power)
20 Chapter 1. Introduction to Scilab
Addition
--> a = 5;
--> b = 3;
--> c = a + b
c =
8.
Subtraction
--> x = 10;
--> y = 4;
--> z = x - y
z =
6.
Multiplication
--> m = 7;
--> n = 6;
--> p = m * n
p =
42.
Division
Exponentiation (Power)
--> base = 2;
--> exp = 4;
--> power = base ^ exp
power =
16.
Operator Precedence
1. Parentheses ()
2. Exponentiation ^
--> result = (2 + 3) * 4 ^ 2
result =
80.
Here, the parentheses alter the default precedence: 2 + 3 = 5, then 5 * 16 = 80.
Remarks
Floating-Point Numbers
Floating-point numbers are numerical values that contain decimal points. They are pri-
marily used to represent real numbers and are essential in scientific, engineering, and
statistical computations where precision is crucial. By default, all numbers in Scilab
are stored as double-precision floating-point values, which provide approximately 15–16
digits of precision.
--> a = 5.75
a =
5.75
Scientific Notation Scilab supports scientific notation, allowing users to express very
large or very small numbers in a compact form:
--> x = 1e3; // Equivalent to 1000
--> y = 2.5e-2; // Equivalent to 0.025
--> z = -3.2e4; // Equivalent to -32000
22 Chapter 1. Introduction to Scilab
Remarks
Use scientific notation for very large or very small numbers to avoid manual
counting of zeros.
2. Boolean Variables
In Scilab, the Boolean type is used to represent logical values such as %t (true) and %f
(false). Boolean variables are fundamental in decision-making constructs, conditional
execution, and logical operations. They are widely used in control structures such as if,
while, and for loops, as well as in vectorized logical comparisons for matrices.
1.9. Data Types in Scilab 23
Predefined Boolean Constants: Scilab provides two predefined constants for Boolean
values:
%t – Represents logical true
Relational Operators
Relational operators are used to compare values and return Boolean results (%t or %f).
Operator Description
== Equal to
= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Examples:
--> 5 == 5
ans =
T
--> 6 < 3
ans =
F
Boolean Operators
Boolean (logical) operators combine or invert Boolean values. They are essential in
creating complex logical conditions.
Operator Description
& Logical AND (true if both operands are true)
| Logical OR (true if at least one operand is true)
~ Logical NOT (inverts a Boolean value)
&& Short-circuit AND (stops evaluation if first operand is false)
|| Short-circuit OR (stops evaluation if first operand is true)
24 Chapter 1. Introduction to Scilab
Examples:
--> a & b
ans =
F
--> a | b
ans =
T
--> ~a
ans =
F
x = 10;
if x > 5 then
disp("x is greater than 5");
else
disp("x is not greater than 5");
end
Boolean Matrices
Boolean values can also be stored in matrices. Logical operations are applied element-
wise.
A = [1 2 3];
B = [3 2 1];
C = A == B
Output:
C =
F T F
1.9. Data Types in Scilab 25
3. Strings
Strings in Scilab are sequences of characters enclosed in double quotes " ". They are
widely used to represent textual data and support a variety of operations such as con-
catenation, comparison, searching, and transformation. Strings in Scilab can be:
Creating Strings
--> a = "Data";
--> b = "Science";
--> c = a + b
c =
DataScience
—
26 Chapter 1. Introduction to Scilab
2. String Length The length() function returns the number of characters in a string.
4. Changing Case The convstr() function is used to convert the case of a string.
--> s = "Scilab";
--> part(s, 1:3)
ans =
Sci
1.9. Data Types in Scilab 27
8. Splitting and Joining Strings Use strsplit() to split a string into parts using
a delimiter, and strcat() to join them:
9. String Conversion Functions Scilab provides several utility functions for type
conversion:
--> string(123)
ans =
"123"
--> ascii("A")
28 Chapter 1. Introduction to Scilab
ans =
65
--> ascii2str(65)
ans =
"A"
4. Complex Numbers
Scilab natively supports complex numbers, which are numbers of the form a + bi, where a
is the real part and b is the imaginary part. Complex numbers are essential in engineering,
physics, and applied mathematics, particularly for signal processing, electrical circuits,
and control systems.
Scilab provides built-in functions to access the real and imaginary components:
--> real(z)
ans =
3.
--> imag(z)
ans =
4.
Complex Conjugate
--> conj(z)
ans =
3. - 4.i
Addition
Subtraction
Multiplication
Division
5.
Exponential Representation
z = reiθ
Function Description
real(z) Returns the real part of z
imag(z) Returns the imaginary part of z
conj(z) Returns the complex conjugate of z
abs(z) Returns the magnitude (modulus) of z
arg(z) Returns the phase angle (argument) of z in radians
polar(r, θ) Converts polar coordinates to rectangular form
exp(%i*θ) Returns the exponential form of a complex number
isreal(z) Checks if a number is purely real
isrealpart(z) Checks if the real part of a number is non-zero
isrealwithtol(z, tol) Checks if a number is real within a tolerance
--> abs(A)
ans =
2.2361 5.
Validate results using isreal() or tolerance checks when dealing with near-zero
imaginary parts.
For a detailed study of matrix operations, advanced properties, and related functions,
please refer to Chapter 2. This section provides only a brief introduction to the concept
to establish the relationship between basic data types and their matrix representation in
Scilab.
6. Polynomial Type
In Scilab, polynomials are treated as a distinct data type that allows symbolic manipula-
tion, evaluation, and algebraic operations. Polynomials can be created either from their
coefficients or roots using the poly() function.
32 Chapter 1. Introduction to Scilab
Defining Polynomials
Operations on Polynomials
Scilab supports standard arithmetic operations on polynomials using the same syntax as
algebraic expressions.
p1 = s^2 + 2*s + 1;
p2 = s + 3;
// Addition
sum = p1 + p2;
// Subtraction
diff = p1 - p2;
// Multiplication
prod = p1 * p2;
For scalar operations, constants can be added, subtracted, multiplied, or divided directly
with polynomials:
p = s^2 + 4*s + 4;
p + 2; // Adds 2 to the constant term
p * 3; // Multiplies every term by 3
1.9. Data Types in Scilab 33
Function Description
poly(v, ’x’, ’roots’) Creates a polynomial from its roots.
poly(v, ’x’, ’coeff’) Creates a polynomial from its coefficients.
roots(p) Returns the roots of the polynomial p.
coeff(p) Returns the coefficient vector of the polynomial p.
degree(p) Returns the degree of the polynomial p.
derivat(p) Computes the derivative of p.
integrat(p) Computes the integral of p.
horner(p, x) Evaluates p at a specific value x.
pdiv(p1, p2) Divides two polynomials and returns both quotient and
remainder.
pfactors(p) Factorizes a polynomial into linear factors.
clean(p) Removes negligible coefficients (close to zero) from p.
spec(p) Returns the roots of the polynomial, similar to roots(),
but optimized for characteristic polynomials.
polyder(p, n) Computes the nth derivative of p (repeated differentia-
tion).
polyint(p, c) Computes the integral of p with optional constant c.
Example
// Coefficients
coeff(p)
ans =
1. 6. 11. 6.
// Roots
roots(p)
ans =
-3.
-2.
-1.
// Derivative
derivat(p)
ans =
3s^2 + 12s + 11
34 Chapter 1. Introduction to Scilab
// Integral
integrat(p)
ans =
0.25s^4 + 2s^3 + 5.5s^2 + 6s
7.1 Lists
A list in Scilab is an ordered collection of elements, where each element can be of any
type (numbers, strings, matrices, polynomials, functions, etc.). Lists are created using
the list() function.
// Accessing elements
L(1) // 12
L(2) // ’Scilab’
// Modify elements
L(1) = 100;
L(3) = [5 6; 7 8];
// Remove element
L(2) = null();
A tlist (typed list) is a structured data container where each element is associated with
a field name. This is similar to records or structures in other programming languages.
Creating a tlist
T = tlist([’person’, ’name’, ’age’, ’marks’], ’Alice’, 21, [90 85 95]);
T
ans =
person
name: Alice
age: 21
marks: 90. 85. 95.
// Modify fields
T.age = 22;
36 Chapter 1. Introduction to Scilab
Checking Type
typeof(T) // person
Creating an mlist
M
ans =
matrixInfo
rows: 3
cols: 4
Applications of mlist
lists: General-purpose containers for storing mixed data (e.g., results of iterative
computations, grouped data for analysis).
tlists: Structured data types for better readability and field-based access (e.g.,
defining a ”person” record or custom configuration).
Prefer tlist() or mlist() when data needs meaningful field names or object-like
behavior.
Use typeof() or ;isdef() to check the type before manipulating lists programmat-
ically.
Avoid excessive nesting of lists for better readability; consider structured objects
instead.
Document field names clearly when designing tlist() or mlist() for toolbox de-
velopment.
In this example, the control system sys is stored as an mlist, providing field-based
access and specialized operations (like simulation and response analysis).
Conclusion: lists, tlists, and mlists form the backbone of complex data manage-
ment in Scilab. While lists are versatile containers for general data storage, typed lists
and matrix lists bring structure, clarity, and object-oriented capabilities that are crucial
for advanced Scilab programming and toolbox development.
8. Structures
A structure in Scilab is a powerful data type that allows grouping related but heteroge-
neous data into a single variable. It is conceptually similar to the struct in C or record
in Pascal and is widely used for organizing data in a clear and meaningful way.
Structures are particularly useful for applications involving record-keeping, database-
like storage, or passing multiple parameters between functions.
38 Chapter 1. Introduction to Scilab
A structure is created using the struct() function, which accepts field names and cor-
responding values:
name: "Ravi"
age: 21
marks: [1x3 matrix]
--> student.name
ans =
Ravi
--> student.age
ans =
21
--> student.marks
ans =
85. 90. 78.
--> fieldnames(student)
ans =
"name" "age" "marks" "department"
--> s1 = struct(’name’,’Anu’,’age’,20);
--> s2 = struct(’name’,’Kumar’,’age’,21);
--> students = [s1, s2];
--> students(1).name
ans =
Anu
--> students(2).age
ans =
21
Function Description
struct(f1, v1, ...) Creates a new structure with specified fields and values.
fieldnames(s) Returns all field names of the structure s.
isfield(s, ’field’) Checks if a field exists in the structure s.
rmfield(s, ’field’) Removes a field from a structure (alternate to null()).
size(s) Returns the size of the structure array.
// Access values
config.method // Runge-Kutta
config.tolerance // 1.0D-6
--> x = 1
x =
1.
--> x + 1
ans =
2.
--> x = "food"
x =
food
--> x + "stall"
ans =
foodstall
2. Type Checking
You can determine the type of a variable at runtime using the typeof() function:
--> typeof(x)
ans =
string
--> y = 10;
--> typeof(y)
ans =
constant
42 Chapter 1. Introduction to Scilab
Flexibility: A single variable can hold different data types during program execu-
tion.
Data-driven programming: Ideal for handling inputs whose type may change
based on runtime conditions.
Avoid frequent and unnecessary type changes for the same variable.
For large projects, use consistent naming conventions to indicate the expected vari-
able type.
When required, perform explicit conversions using functions like string(), int(),
or double().
This example demonstrates how a single variable can hold a numeric value, a string,
and a boolean vector at different points in a program.
1.11. Elementary Mathematical Functions in Scilab 43
−1 y
atan(y, x) – tan : Arctangent considering the sign of both arguments
x
x = 4.7;
round(x); // 5
floor(x); // 4
ceil(x); // 5
sign(x) – Returns:
−1, x < 0
sign(x) = 0, x=0
1, x>0
modulo(10, 3); // 1
Function Description
sin(x), cos(x), tan(x) Trigonometric functions
asin(x), acos(x), atan(x), atan(y,x) Inverse trigonometric functions
exp(x), log(x), log10(x) Exponential and logarithmic functions
x^n, sqrt(x) Power and root functions
round(x), floor(x), ceil(x) Rounding functions
abs(x), sign(x) Absolute value and sign functions
modulo(x,y) Modulo (remainder) function
Best Practices
Always ensure that trigonometric inputs are in radians unless explicitly converted.
Use vectorized operations instead of loops for efficiency when applying these func-
tions to arrays or matrices.
Validate inputs before applying logarithmic or square root functions to avoid domain
errors.
Demonstrations in Scilab
Scilab provides an extensive set of built-in demonstrations that enable users to explore
the software’s capabilities through practical, visual examples. These demonstrations are
particularly beneficial for beginners to understand fundamental operations, as well as for
advanced users who wish to explore complex functionalities such as control systems or
optimization techniques. By using these demonstrations, learners can quickly familiar-
ize themselves with Scilab’s environment and workflow in an interactive and self-guided
manner.
Accessing Demonstrations
To launch the demonstration interface in Scilab, execute the following command in the
console:
--> demo_gui()
This command opens the Scilab Demo GUI, a graphical interface that organizes
demonstrations into clearly defined categories for easy navigation.
Categories of Demonstrations
The demonstration interface typically includes, but is not limited to, the following cate-
gories:
Signal Processing: Provides examples for filtering, Fourier analysis, and signal
transformations.
Optimization: Showcases algorithms and methods for solving linear and nonlinear
optimization problems.
Exploring Demonstrations
1. Sample Code: Pre-written Scilab scripts that illustrate a specific concept or func-
tion.
2. Interactive Execution: The ability to run and modify the code directly from the
demo window.
These demonstrations act as guided tutorials, allowing learners to experiment with the
code, observe changes in output, and gain a deeper understanding of Scilab functionalities.
Modify the provided demo code to test different parameters and observe how the
results change.
Use the demonstrations as a reference when writing your own scripts for similar
problems.
Take note of related functions mentioned within the demonstration scripts for ex-
tended learning.
Remarks
Users should ensure they are using the latest version of Scilab to access updated
demonstrations and examples.
Complex demonstrations can be combined with the help and apropos commands
to explore related documentation.
Macros in Scilab
A macro in Scilab is a user-defined function or a set of instructions stored in a file,
enabling code reuse, modular programming, and improved program readability. Macros
in Scilab are conceptually similar to functions in other programming languages and are
an essential component for developing structured and maintainable code.
A macro is created using the function and endfunction keywords and saved with the
file extension .sci. Once defined, the macro must be executed or loaded before it can
be used.
48 Chapter 1. Introduction to Scilab
// File: computeArea.sci
// This macro calculates the area of a circle for a given radius.
--> exec(’computeArea.sci’);
--> computeArea(5)
ans =
78.5398
This single workflow illustrates macro definition, loading, and output execution in a
clear manner.
Test macros with various input values to ensure correctness and reliability.
Save commonly used macros in a .sav file for easy reuse across projects.
Remarks
Macros are a fundamental feature of Scilab that promote efficient and structured program-
ming. By following proper naming conventions, documentation practices, and modular
design, macros can significantly enhance the productivity of both learners and profes-
sionals in academic and research contexts.
Types of Toolboxes
Toolboxes in Scilab can be broadly classified into two categories:
Accessing ATOMS
The following example demonstrates how to install and load the Signal Processing Tool-
box:
Verify compatibility between the Scilab version and the toolbox version before in-
stallation.
Read the documentation of each toolbox for correct syntax and usage of its func-
tions.
Remarks
Toolboxes significantly enhance Scilab’s functionality for research and teaching in
specialized fields.
Users can also develop custom toolboxes to encapsulate their own libraries of macros
and share them with the community.
Toolbox management through ATOMS ensures ease of use and reduces the com-
plexity of handling dependencies.
By mastering the use of toolboxes, learners and researchers can leverage Scilab as
a powerful platform for scientific computation, data analysis, and engineering problem-
solving.
Time Efficiency: Automates repetitive tasks and eliminates the need for manual
command entry.
exec(’student_analysis.sce’, -1);
The script will execute automatically, and the results will be displayed in the console
along with the graph.
3. Validate Input Data: Include basic checks to ensure data correctness before
execution.
4. Reusability: Write modular scripts that can be reused for different datasets.
5. Use Clear File Names: Name scripts descriptively (e.g., marks analysis.sce
instead of script1.sce).
6. Automate Plots: Include appropriate titles, labels, and legends for better visual-
ization.
7. Error Handling: Use try-catch blocks for scripts that involve complex compu-
tations to prevent runtime interruptions.
Remarks
Batch processing is ideal for assignments, research projects, and repetitive analysis
tasks.
Scripts enhance reproducibility and can be easily shared among students and re-
searchers.
By combining batch scripts with functions, Scilab can serve as a powerful tool for
large-scale academic and industrial computations.
whos() – Provides a detailed view of variables, including size and memory usage.
Note: Increasing stack size should be done cautiously and only when necessary, as
allocating excessive memory may impact system performance.
2. Monitor Memory: Use whos() to track memory usage during intensive compu-
tations.
3. Modular Programming: Write smaller functions and macros to limit the number
of global variables in memory.
4. Optimize Data Types: Use appropriate data sizes (e.g., avoid unnecessarily large
matrices).
56 Chapter 1. Introduction to Scilab
5. Increase Stack Size Only When Needed: Do not allocate excessive stack
memory unless computations require it.
Remarks
Efficient memory management is crucial in simulations, image processing, and big
data computations.
Clearing unused variables improves both speed and stability in long-running pro-
grams.
1.2 What is the significance of using semicolons (;) in Scilab commands? Illustrate with
examples.
1.3 Differentiate between keywords and variables in Scilab. Provide at least three
examples of each.
1.4 List and explain any five predefined mathematical variables available in Scilab.
1.5 Describe the different data types in Scilab with suitable examples.
1.8 Explain the concept of batch processing in Scilab. How is it useful for automation?
1.9 What is memory management in Scilab? Mention any two commands used for
memory management.
1.10 Write the difference between list, tlist, and structure in Scilab.
1.12 Write a program to demonstrate the use of semicolons by printing output with and
without a semicolon.
1.13 Create variables of different data types (integer, float, string, and boolean) and
display their types using typeof().
1.15 Write a program to find the power and square root of a number entered by the user.
1.17 Write a program to demonstrate dynamic variables in Scilab by changing the type
of a single variable from numeric to string to boolean.
1.18 Write a Scilab script to demonstrate batch processing by executing multiple com-
mands from a script file.
1.19 Write a program to display current memory usage in Scilab and clear all variables
from memory.