0% found this document useful (0 votes)
4 views58 pages

Chapter 1

SCILAB CHAPTERS

Uploaded by

Udaya Shivani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views58 pages

Chapter 1

SCILAB CHAPTERS

Uploaded by

Udaya Shivani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

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.1 What is Scilab?


Scilab is a powerful, open-source, and freely available software platform widely used
for scientific computation, engineering applications, and educational purposes. From a
software perspective, Scilab is an interpreted language, meaning that code is executed
line-by-line without requiring prior compilation. This approach significantly facilitates
rapid prototyping, algorithm development, and interactive problem-solving. It also ac-
celerates the development process by providing direct access to a high-level language
enriched with a comprehensive library of built-in features.
Scilab is highly extensible, allowing users to define custom data types and even over-

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.

From a licensing standpoint, Scilab is distributed under the CeCILL license, a


French open-source license that is fully compatible with the GNU General Public License
(GPL). This licensing model grants users the freedom to use, modify, and redistribute
the software, thereby making Scilab an ideal choice for both academic and professional
environments. The availability of the source code ensures transparency and allows users
to access and customize Scilab’s internal components when required.

From a scientific perspective, Scilab initially focused on linear algebra functionalities.


However, its capabilities have rapidly evolved to encompass a wide range of scientific and
engineering domains, including numerical analysis, signal processing, control systems,
optimization, and data visualization.

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:

ˆ Education: Used as a teaching tool for mathematics, programming, numerical


methods, and algorithm development in alignment with NEP-based curricula.

ˆ Research: Applied in areas such as applied mathematics, physics, engineering,


optimization, computational fluid dynamics, and control systems for modeling, sim-
ulation, and data analysis.

ˆ Signal and Image Processing: Provides powerful libraries to analyze, filter, and
process signals and images effectively.

ˆ Data Visualization: Supports high-quality 2D and 3D plotting for interpreting


and presenting computational results.

ˆ Industrial Applications: Used in process control, automation, system design,


and performance analysis as a cost-effective alternative to commercial software.

ˆ Customization and Extensibility: Enables the development of user-defined


modules and toolboxes tailored to specific academic and industrial needs.

ˆ Data Science and AI: Facilitates numerical computation and visualization in


emerging fields such as artificial intelligence and machine learning.
1.1. What is Scilab? 3

ˆ Cross-Platform Compatibility: Runs seamlessly on Windows, Linux, and ma-


cOS, ensuring accessibility for all users.

ˆ Community and Collaboration: Backed by a strong open-source community


that provides continuous updates, support, and collaborative opportunities.

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.

ˆ Cost-Effective Solution: Eliminates the need for expensive commercial licenses,


making it highly suitable for students, educators, and research institutions.

ˆ Extensive Computational Libraries: Provides built-in functions for linear al-


gebra, calculus, numerical methods, signal processing, optimization, and data visu-
alization.

ˆ Cross-Platform Compatibility: Supports Windows, Linux, and macOS, ensur-


ing accessibility for a wide range of users.

ˆ Customizability and Extensibility: Users can create custom modules, tool-


boxes, and scripts to extend its functionality for specialized domains.

ˆ Educational Relevance: Well-suited for NEP-based curricula, enabling students


to learn algorithmic thinking and computational problem-solving through hands-on
experience.

ˆ Community Support: Backed by a large, active community that provides re-


sources, documentation, and regular updates.

ˆ High-Quality Visualization: Offers robust 2D and 3D plotting features for clear


representation of data and results.

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

ˆ Limited Industry Adoption: Compared to commercial software like MATLAB,


Scilab has relatively lower penetration in some industrial sectors.

ˆ Performance Limitations: May be less efficient for extremely large-scale com-


putations compared to highly optimized commercial platforms.

ˆ Third-Party Toolbox Availability: The number of specialized toolboxes and


add-ons is fewer compared to proprietary alternatives.

ˆ Documentation Gaps: While community-driven resources exist, some advanced


features lack detailed official documentation.

Overall, Scilab is an academically robust, cost-effective, and flexible platform, but


users should be mindful of its limitations when selecting it for advanced industrial or
large-scale computational tasks.

Origins and Early Development


The origins of Scilab can be traced back to the 1980s at the French Institute for Research
in Computer Science and Automation INRIA(Institut National de Recherche en Infor-
matique et en Automatique). During this period, INRIA developed a software package
called Blaise, primarily intended for research in automatic control systems and numerical
computation. Blaise was later renamed Basile and distributed by Simulog, a technology
transfer company associated with INRIA, which helped in bringing this computational
tool to academic and research communities.

The Birth of 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.

Growth and Expansion

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

Scilab Enterprises and Industry Adoption

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.

1.2 Getting Started in Scilab

Installing Scilab
Scilab is freely available and can be downloaded from its official website:

https://www.scilab.org/download

The installation procedure is straightforward and can be completed by following these


steps:

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.

5. Complete the Installation: Specify the installation directory if required, then


allow the installer to configure the necessary components.
6 Chapter 1. Introduction to Scilab

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.

1.3 The Scilab Environment


Upon launching Scilab, the user is presented with an integrated development environ-
ment (IDE) designed to facilitate scientific computation, algorithm development, and
data visualization. The main components of the interface are as follows:

ˆ 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.

ˆ File Browser: Provides a convenient directory navigation system, enabling users


to manage files and projects directly within the Scilab workspace.

ˆ Graphics Window: A dedicated visualization interface for rendering two-dimensional


(2D) and three-dimensional (3D) plots, allowing effective graphical representation
of data and results.

ˆ Help Browser: Offers comprehensive documentation, built-in examples, and func-


tion references to assist users in learning and applying Scilab features efficiently.

ˆ Variable Browser: Displays all active variables, including their names, data types,
dimensions, and values, enabling easy monitoring of computational workflows.

ˆ Command History: Records previously executed commands, allowing users to


review, modify, and re-execute commands to improve workflow efficiency.

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

1.3.1 Scilab Console


The Scilab Console serves as the primary interactive interface for executing commands,
performing numerical computations, and testing algorithms in real time. It functions as
an advanced command-line environment, enabling both basic arithmetic operations and
complex scientific calculations. The console is particularly useful for rapid prototyping,
immediate verification of results, and seamless interaction with other components of the
Scilab environment.

ˆ Command Execution: Users can enter mathematical expressions, run scripts,


and call functions directly within the console for immediate evaluation.

ˆ History Management: Previously executed commands can be retrieved using


the arrow keys, improving workflow efficiency and reducing repetitive typing.

ˆ Variable Display: Computational results, including variable names and values,


are displayed in real-time, ensuring transparency in the evaluation process.

ˆ 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.

Figure 1.1: Scilab Console Interface

1.4 Semicolon Usage in Scilab


In Scilab, the semicolon (;) plays an essential role in controlling the display of command
outputs in the console. While it does not influence the actual execution or computation
1.4. Semicolon Usage in Scilab 9

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.

Command Execution with Semicolon

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.

Command Execution without Semicolon

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.

Key Features of SciNotes

ˆ Syntax Highlighting: Improves code readability by visually distinguishing be-


tween keywords, functions, comments, and variables.

ˆ Automatic Indentation: Enforces structured coding practices, enabling consis-


tent formatting across scripts.
10 Chapter 1. Introduction to Scilab

ˆ Integrated Execution: Allows direct execution of scripts from the editor without
switching back to the console.

ˆ Multiple File Management: Facilitates working with several scripts simultane-


ously using a tabbed interface.

ˆ 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.

Figure 1.2: SciNotes Editor Interface in Scilab

SciNotes can be launched from the Scilab console using the following commands:
ˆ To open a blank editor window:

--> scinotes();

ˆ To open a specific file in SciNotes:

--> scinotes(’filename.sce’);

ˆ To use the alternate editor command:

--> editor();
1.4. Semicolon Usage in Scilab 11

Example

The following command opens a script named circleArea.sce in SciNotes, provided it


exists in the current working directory:

--> 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

ˆ Comprehensive Plotting Capabilities: Supports a wide range of graphical


representations, including line plots, scatter plots, bar charts, contour plots, and
3D surface plots, enabling in-depth data analysis.

ˆ Advanced Customization: Allows users to enhance visualizations by adding


titles, axis labels, legends, annotations, grid lines, and customizable color schemes
to improve clarity and interpretability.

ˆ Interactive Tools: Provides interactive functionalities such as zooming, panning,


rotating (for 3D plots), and data point inspection for detailed exploration of results.

ˆ Export and Documentation: Enables exporting plots in multiple formats (e.g.,


PNG, JPEG, PDF, SVG) for inclusion in academic publications, research reports,
and presentations.

ˆ Multi-Window Support: Facilitates the simultaneous management of multiple


graphics windows, making it easier to compare datasets or visualize different aspects
of the same problem.

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 Features in Scilab


Scilab offers an extensive and well-structured help system that provide direct access to
documentation, keyword-based search, and interactive demonstrations, enabling users to
learn and explore Scilab efficiently without requiring third-party material.

Available Help Features

ˆ Help Browser: The help command opens the integrated help browser, which
contains categorized documentation of Scilab’s functions, toolboxes, and examples.

help or help function_name

help plot

This displays the documentation page for the plot function.

ˆ 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.”

ˆ Demonstration Interface: Scilab provides a graphical demonstration utility ac-


cessible via the demo gui command. It showcases pre-built examples that illustrate
various Scilab features.

demo_gui()

This opens an interactive window containing categorized examples and tutorials.

ˆ Online Documentation: Scilab maintains an official online documentation portal


where the latest manuals, function references, and guides are available:

https://help.scilab.org

ˆ Community Forums and User Contributions: In addition to the built-in


help, Scilab’s user community provides forums, Q&A sections, and user-contributed
scripts that further enhance the learning experience.

Remarks

ˆ Always download Scilab from the official website to ensure security and authenticity.

1.5 Comments and Continuation Lines in Scilab


Readable and well-documented code is essential in both academic and industrial program-
ming. In Scilab, comments and continuation lines improve code clarity, make debugging
easier, and facilitate collaborative development. While comments explain the purpose
and logic of the program, continuation lines allow lengthy statements to be split across
multiple lines, improving readability.

Comments in Scilab
In Scilab, single-line comments begin with two forward slashes //. Any text following //
on that line is ignored by the interpreter.

// This is a single-line comment


a = 10; // Assign 10 to variable ’a’

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

// This function computes the


// factorial of a number using
// a recursive approach

Alternatively, for documentation purposes in larger projects, descriptive comments should


be placed above functions and key program sections.

Continuation Lines in Scilab


When a command or expression is too long to fit comfortably on a single line, Scilab
allows the use of the continuation operator ... (three dots). This improves readability
by breaking long lines into manageable parts.

a = 1 + 2 + 3 + 4 + 5 + ...
6 + 7 + 8 + 9 + 10;

Example: Well-Documented Program with Continuation Lines

1 // Function to compute the sum of squares from 1 to n


2 // Input : n - positive integer
3 // Output : total - sum of squares
4

5 function total = sumOfSquares ( n )


6 total = 0;
7 for i = 1: n
8 total = total + ...
9 i ^2; // Accumulate square of each number
10 end
11 endfunction
12

13 // Call the function


14 result = sumOfSquares (10) ;
15 disp ( " Sum of squares from 1 to 10: " + string ( result ) ) ;

Remarks

ˆ Proper commenting enhances program maintainability and makes it easier for others
to understand your work.

ˆ Continuation lines are especially useful in engineering and scientific applications


where equations span multiple terms.
1.6. Keywords in Scilab 15

ˆ Following consistent documentation practices improves the quality and publishabil-


ity of academic or industrial Scilab projects.

1.6 Keywords in Scilab


Keywords in Scilab are reserved words that carry predefined meanings and are an integral
part of the language’s syntax and structure. They cannot be used as identifiers (such as
variable names or function names), because they are interpreted by the Scilab interpreter
to perform specific tasks.

Commonly Used Keywords in Scilab

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.

1.7 Variables in Scilab


Variables in Scilab are used to store and manipulate data such as numbers, strings,
matrices, and other data types. They act as symbolic names that reference memory
locations where values are stored. Understanding variables is fundamental to writing
effective Scilab programs.

Declaring and Assigning Variables

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 (=).

1 // Example : Assigning different data types


2 x = 5; // Integer variable
3 y = 3.14; // Floating - point variable
4 name = " Scilab " ; // String variable
5 A = [1 2 3; 4 5 6]; // Matrix variable

Rules for Naming Variables

When creating variables in Scilab, the following rules must be followed:

ˆ Variable names must start with a letter (a--z or A--Z).

ˆ They may contain letters, digits (0--9), and underscores ( ).

ˆ Scilab is case-sensitive, meaning X and x are treated as two different variables.

ˆ Reserved keywords (e.g., if, for, while, function) cannot be used as variable
names.

ˆ Variable names should be meaningful and descriptive to improve program readabil-


ity.
1.8. Predefined Mathematical Variables in Scilab 17

Checking Variables

Scilab provides commands to check variables during program execution:

--> who // Lists all defined variables


--> typeof(x) // Displays the data type of a variable
--> clear x // Removes a specific variable
--> clear // Removes all variables from memory

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.

3. Maintain case consistency: Since Scilab is case-sensitive, use a consistent nam-


ing convention (e.g., camelCase or snake case).

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.

1.8 Predefined Mathematical Variables in Scilab


Scilab provides several Predefined mathematical constants and variables that are initial-
ized automatically at the start of every Scilab session. These predefined variables allow
users to perform scientific and engineering computations without redefining fundamental
constants.
18 Chapter 1. Introduction to Scilab

List of Predefined Mathematical Variables

Variable Description and Value


%pi Represents the mathematical constant π ≈ 3.1415927
%e Euler’s number e ≈ 2.7182818 used in exponential and logarithmic functions

%i Imaginary unit i = −1 for complex number operations
%inf Represents positive infinity ∞
%-inf Represents negative infinity −∞
%nan Represents ”Not a Number” (undefined result, e.g., 0/0)
%t Boolean constant true
%f Boolean constant false
%eps Floating-point precision ≈ 2.2204 × 10−16

Examples

1 // Calculate the area of a circle with radius r


2 r = 5;
3 area = %pi * r ^2; // Result : 78.5398
4

5 // Exponential calculation using Euler ’ s number


6 expVal = %e ^2; // Result : 7.3891
7

8 // Define a complex number


9 z = 3 + 4* %i ; // Result : 3 + 4 i
10

11 // Operations with infinity


12 a = 5 / 0; // Returns %inf
13 b = -5 / 0; // Returns % - inf
14

15 // Handling undefined results


16 c = 0 / 0; // Returns %nan
17

18 // Boolean operations
19 isTrue = %t ; // Result : true
20 isFalse = %f ; // Result : false

Remarks

ˆ Predefined constants are read-only; they should not be reassigned or modified.


1.9. Data Types in Scilab 19

ˆ %eps is especially useful for numerical methods that require tolerance levels when
comparing floating-point numbers.

1.9 Data Types in Scilab


Scilab supports a variety of data types that allow users to store and manipulate different
kinds of information. Understanding these data types is essential for efficient program-
ming.

1. Numeric Types
Numeric types are the most commonly used data types in Scilab. They include both
integers and floating-point numbers.

ˆ Integers – Whole numbers without any decimal part.

ˆ Floating Point Numbers – Numbers that contain decimal parts.

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.

Basic Arithmetic Operators

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

--> num = 20;


--> den = 4;
--> result = num / den
result =
5.

Exponentiation (Power)

--> base = 2;
--> exp = 4;
--> power = base ^ exp
power =
16.

Operator Precedence

Scilab evaluates arithmetic expressions based on the standard precedence rules:


1.9. Data Types in Scilab 21

1. Parentheses ()

2. Exponentiation ^

3. Multiplication and Division *, /, \

4. Addition and Subtraction +, -


--> result = 2 + 3 * 4 ^ 2
result =
50.
4^
2 = 16, then 3 * 16 = 48, then 2 + 48 = 50.

Example: Using Parentheses to Control Precedence

--> result = (2 + 3) * 4 ^ 2
result =
80.
Here, the parentheses alter the default precedence: 2 + 3 = 5, then 5 * 16 = 80.

Remarks

ˆ Always use parentheses () for clarity in complex expressions.

ˆ Use descriptive variable names to avoid confusion in mathematical expressions.

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

Precision Considerations Floating-point arithmetic may introduce small rounding


errors due to hardware-level representations. For example:

--> r = 0.1 + 0.2


r =
0.30000000000000004

This is expected behavior in most numerical computing environments.

Remarks
ˆ Use scientific notation for very large or very small numbers to avoid manual
counting of zeros.

ˆ Be cautious of rounding errors in iterative calculations; use functions such as


round(), floor(), or ceil() where needed.

ˆ Prefer double precision for high-accuracy computations; avoid unnecessary type


conversions.

ˆ Validate results by using isnan() or isinf() for detecting invalid floating-point


results.

Example: Rounding Functions


--> val = 5.6789;
--> round(val) // Rounds to nearest integer
ans =
6.

--> floor(val) // Rounds down


ans =
5.

--> ceil(val) // Rounds up


ans =
6.

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

ˆ %f – Represents logical false


--> a = %t
a =
T
--> b = %f
b =
F

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 = %t; b = %f;

--> a & b
ans =
F

--> a | b
ans =
T

--> ~a
ans =
F

Boolean Expressions in Conditional Statements

Boolean expressions control the flow of execution:

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:

ˆ Scalar Strings – A single string value.

ˆ Vectors of Strings – A one-dimensional array of strings.

ˆ Matrices of Strings – A two-dimensional array of strings.

Creating Strings

A string is created by assigning text enclosed in double quotes:

--> s = "Hello Scilab";


s =
Hello Scilab

You can also create a vector or matrix of strings:

--> names = ["Alice", "Bob", "Charlie"];


--> subjects = ["Math" "Science"; "History" "Art"];

String Operations and Functions

1. String Concatenation The + operator is used to concatenate two or more strings.

--> a = "Data";
--> b = "Science";
--> c = a + b
c =
DataScience

For concatenation with a separator, use strcat():

--> strcat(["Data", "Science"], " ")


ans =
Data Science


26 Chapter 1. Introduction to Scilab

2. String Length The length() function returns the number of characters in a string.

--> str = "Scilab";


--> len = length(str)
len =
6

For vectors or matrices of strings, use size() to determine dimensions.


3. String Comparison Strings can be compared using either == (element-wise) or the


strcmp() function for more robust comparisons.

--> "apple" == "apple"


ans =
T

--> strcmp("apple", "APPLE")


ans =
F

Use strcmpi() for case-insensitive comparison:

--> strcmpi("apple", "APPLE")


ans =
T

4. Changing Case The convstr() function is used to convert the case of a string.

--> str = "Scilab";


--> upper = convstr(str, "u") // Convert to uppercase
--> lower = convstr(str, "l") // Convert to lowercase

5. Extracting Substrings The part() function extracts a substring from a given


string.

--> s = "Scilab";
--> part(s, 1:3)
ans =
Sci
1.9. Data Types in Scilab 27

6. Searching in Strings The strindex() function finds the starting position of a


substring:

--> str = "DataScience";


--> strindex(str, "Science")
ans =
5

If a substring is not found, it returns an empty matrix.

7. Replacing Substrings The strsubst() function replaces occurrences of a sub-


string with a new substring.

--> str = "Scilab is great";


--> newstr = strsubst(str, "great", "powerful")
newstr =
Scilab is powerful

8. Splitting and Joining Strings Use strsplit() to split a string into parts using
a delimiter, and strcat() to join them:

--> words = strsplit("Data,Science,AI", ",")


words =
"Data" "Science" "AI"

--> strcat(words, " ")


ans =
Data Science AI

9. String Conversion Functions Scilab provides several utility functions for type
conversion:

ˆ string() – Converts numbers, matrices, or Boolean values into strings.

ˆ ascii() – Returns the ASCII codes of characters.

ˆ ascii2str() – Converts ASCII codes back into strings.

--> 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.

Creating Complex Numbers

Complex numbers in Scilab can be defined in multiple ways:

--> z = 2 + 3*%i // Using %i (imaginary unit)


z =
2. + 3.i

--> z = complex(3, 4) // Using complex() function


z =
3. + 4.i

Accessing Real and Imaginary Parts

Scilab provides built-in functions to access the real and imaginary components:

--> real(z)
ans =
3.

--> imag(z)
ans =
4.

Complex Conjugate

The conj() function returns the complex conjugate of a number:


1.9. Data Types in Scilab 29

--> conj(z)
ans =
3. - 4.i

Arithmetic Operations with Complex Numbers

Scilab supports all basic arithmetic operations on complex numbers.

Addition

--> (2 + 3*%i) + (4 + 5*%i)


ans =
6. + 8.i

Subtraction

--> (5 + 6*%i) - (2 + 3*%i)


ans =
3. + 3.i

Multiplication

--> (1 + 2*%i) * (3 + 4*%i)


ans =
-5. + 10.i

Division

--> (3 + 4*%i) / (1 - 2*%i)


ans =
-1. + 2.i

Polar and Exponential Forms

Complex numbers can also be represented in polar or exponential form.



ˆ Magnitude (Modulus): |z| = a2 + b 2
b
ˆ Argument (Phase): arg(z) = arctan
a
--> z = 3 + 4*%i;
--> abs(z) // Magnitude
ans =
30 Chapter 1. Introduction to Scilab

5.

--> arg(z) // Phase angle (in radians)


ans =
0.9273

To convert polar coordinates to rectangular form:

--> polar(5, %pi/4)


ans =
3.5355 + 3.5355i

Exponential Representation

Complex numbers can also be expressed using Euler’s formula:

z = reiθ

Scilab provides direct operations with the exponential function:

--> r = 5; theta = %pi/3;


--> z = r * exp(%i * theta)
z =
2.5 + 4.3301i

Useful Functions for Complex Numbers

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

Operations on Arrays of Complex Numbers

Scilab supports vectorized operations on complex arrays:


1.9. Data Types in Scilab 31

--> A = [1 + 2*%i, 3 + 4*%i];


--> B = conj(A)
B =
1. - 2.i 3. - 4.i

--> abs(A)
ans =
2.2361 5.

Best Practices for Complex Numbers

ˆ Use complex(a,b) for programmatic clarity instead of a + b* %i in function ar-


guments.

ˆ Use abs(z) and arg(z) for numerical stability in polar conversions.

ˆ Validate results using isreal() or tolerance checks when dealing with near-zero
imaginary parts.

5. Matrices and Vectors


In Scilab, vectors are one-dimensional arrays, whereas matrices are two-dimensional
arrays. All data in Scilab is internally represented as matrices, which allows uniform
handling of both scalar and multi-dimensional data.

A = [1 2 3]; // Row vector


B = [1; 2; 3]; // Column vector
C = [1 2; 3 4]; // 2x2 matrix

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

// Defining polynomial variable ’s’


s = poly(0, ’s’);

// Polynomial using symbolic form


p = s^2 + 5*s + 6;

// Polynomial using coefficients (from highest degree to lowest)


p = poly([1 5 6], ’s’, ’coeff’);

// Polynomial using roots


p = poly([-2 -3], ’s’, ’roots’); // (s + 2)(s + 3)

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;

// Division (quotient and remainder)


[q, r] = pdiv(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.

Table 1.1: Common Polynomial Functions in Scilab

Common Polynomial Functions in Scilab

Example

--> s = poly(0, ’s’);


--> p = s^3 + 6*s^2 + 11*s + 6;

// 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. Lists, tlists, and mlists


In Scilab, lists and their specialized variants (tlists and mlists) provide powerful data
structures that allow the storage and manipulation of heterogeneous data. They are
widely used in various domains such as symbolic computations, control theory, and cus-
tom data modeling.

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.

Creating and Accessing Lists

// Create a list with mixed data types


L = list(12, ’Scilab’, [1 2; 3 4]);

// Display the list


L
ans =
(1)
12
(2)
Scilab
(3)
1. 2.
3. 4.

// Accessing elements
L(1) // 12
L(2) // ’Scilab’

Modifying and Extending Lists


1.9. Data Types in Scilab 35

// Modify elements
L(1) = 100;
L(3) = [5 6; 7 8];

// Add new element


L($+1) = ’New Element’;

// Remove element
L(2) = null();

Key Properties of Lists


ˆ Lists can hold heterogeneous data types.

ˆ Indexing starts from 1 (like other Scilab objects).

ˆ Elements can be dynamically added or removed.

ˆ Useful for grouping related but dissimilar data.

7.2 Typed Lists (tlists)

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.

Accessing and Modifying Fields


// Access fields
T.name // ’Alice’
T.marks // 90. 85. 95.

// Modify fields
T.age = 22;
36 Chapter 1. Introduction to Scilab

Checking Type

typeof(T) // person

7.3 Matrix Lists (mlists)

An mlist is an extension of tlist optimized for object-oriented programming in Scilab.


While a tlist provides field access, an mlist can also be associated with specific op-
erations (via overloading). Many Scilab toolboxes internally use mlists to represent
complex objects (e.g., state-space systems in control theory).

Creating an mlist

M = mlist([’matrixInfo’, ’rows’, ’cols’], 3, 4);

M
ans =
matrixInfo
rows: 3
cols: 4

Applications of mlist

ˆ Used for symbolic computations.

ˆ Internal representation of linear systems (e.g., syslin objects).

ˆ Enabling operator overloading for custom-defined data types.

7.4 Applications of Lists, tlists, and mlists

ˆ 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).

ˆ mlists: Advanced objects enabling toolbox-specific features (e.g., control system


modeling, symbolic algebra).
1.9. Data Types in Scilab 37

7.5 Best Practices

ˆ Use list() for simple heterogeneous collections.

ˆ 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.

7.6 Example: Practical Usage in Control Theory

// Example: State-space representation of a system using mlist


A = [0 1; -2 -3];
B = [0; 1];
C = [1 0];
D = 0;

sys = syslin(’c’, A, B, C, D); // sys is internally an mlist


typeof(sys) // "syslin"

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

8.1 Creating a Structure

A structure is created using the struct() function, which accepts field names and cor-
responding values:

--> student = struct(’name’, ’Ravi’, ’age’, 21, ’marks’, [85 90 78])


student =

name: "Ravi"
age: 21
marks: [1x3 matrix]

8.2 Accessing Structure Fields

Fields in a structure can be accessed using the dot (.) operator:

--> student.name
ans =
Ravi

--> student.age
ans =
21

--> student.marks
ans =
85. 90. 78.

8.3 Modifying Structure Fields

You can update the value of any existing field:

--> student.age = 22;


--> student.marks = [88 91 85];

8.4 Adding New Fields

New fields can be dynamically added to a structure:

--> student.department = ’Mathematics’;


1.9. Data Types in Scilab 39

8.5 Listing Fields in a Structure

The fieldnames() function returns all fields in a structure:

--> fieldnames(student)
ans =
"name" "age" "marks" "department"

8.6 Removing Fields

To remove a field from a structure, assign it to null():

--> student.age = null();

8.7 Array of Structures

Structures can be stored in arrays, making it easy to manage multiple records:

--> 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

8.8 Useful Structure Functions

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.

Table 1.2: Common Structure Functions in Scilab


40 Chapter 1. Introduction to Scilab

8.9 Applications of Structures

ˆ Storing student records, employee details, or database-like entries.

ˆ Grouping parameters for numerical simulations or algorithms.

ˆ Managing complex configurations in engineering applications.

ˆ Passing multiple related variables to a function without separate arguments.

8.10 Best Practices for Using Structures

ˆ Use clear and descriptive field names for better readability.

ˆ Prefer arrays of structures when handling multiple records.

ˆ Validate field existence with isfield() before accessing.

ˆ Avoid deep nesting of structures to maintain simplicity.

ˆ Combine structures with functions for modular program design.

8.11 Example: Real-World Use Case

// Define a configuration structure for simulation parameters


config = struct(’method’, ’Runge-Kutta’, ’timestep’, 0.01, ...
’maxTime’, 10, ’tolerance’, 1e-6);

// Access values
config.method // Runge-Kutta
config.tolerance // 1.0D-6

Conclusion: Structures in Scilab provide an efficient way to organize heterogeneous data


under meaningful labels. They are essential for building readable, modular, and scalable
programs, especially in scientific and engineering applications.

1.10 Dynamic Variables


Scilab is a dynamically typed language, meaning that the type of a variable is deter-
mined at runtime rather than being explicitly declared in advance. This feature provides
flexibility and makes Scilab an effective tool for rapid prototyping, data analysis, and
scientific computing.
1.10. Dynamic Variables 41

1. Variable Type Changes


A variable in Scilab can hold different types of values at different points in a program.
There is no need for explicit type declaration or conversion.

--> x = 1
x =
1.

--> x + 1
ans =
2.

Here, x is initialized as a numeric variable. Scilab performs arithmetic operations


without requiring any type declaration.

--> x = "food"
x =
food

--> x + "stall"
ans =
foodstall

Now, x is reassigned as a string. String concatenation is performed automatically,


demonstrating Scilab’s dynamic type assignment.

2. Type Checking
You can determine the type of a variable at runtime using the typeof() function:

--> typeof(x)
ans =
string

For numeric types:

--> y = 10;
--> typeof(y)
ans =
constant
42 Chapter 1. Introduction to Scilab

3. Advantages of Dynamic Typing


ˆ No explicit declarations: Variables do not require predefined data types.

ˆ Flexibility: A single variable can hold different data types during program execu-
tion.

ˆ Ease of prototyping: Facilitates rapid development without worrying about strict


type rules.

ˆ Data-driven programming: Ideal for handling inputs whose type may change
based on runtime conditions.

4. Best Practices for Dynamic Variables


Although dynamic typing is convenient, it must be managed carefully to avoid runtime
errors:

ˆ Use typeof() to check variable types before performing type-specific operations.

ˆ 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().

5. Example: Practical Usage


// Variable type changes during execution
data = 42; // Numeric
disp(typeof(data)); // Output: constant

data = "Result: " + string(data);


disp(typeof(data)); // Output: string

data = [%T, %F, %T]; // Boolean vector


disp(typeof(data)); // Output: boolean

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.11 Elementary Mathematical Functions in Scilab


Scilab provides a comprehensive set of built-in elementary mathematical functions, which
are extensively used in scientific, engineering, and mathematical computations. These
functions work seamlessly with scalars, vectors, and matrices, making them suitable for
both basic and advanced numerical operations.

1.11.1 Trigonometric Functions


Trigonometric functions in Scilab accept input in radians:

ˆ sin(x) – sin(x) : Sine of angle x

ˆ cos(x) – cos(x) : Cosine of angle x

ˆ tan(x) – tan(x) : Tangent of angle x

1.11.2 Inverse Trigonometric Functions


These functions return the angle (in radians) corresponding to a given trigonometric
value:

ˆ asin(x) – sin−1 (x) : Arcsine

ˆ acos(x) – cos−1 (x) : Arccosine

ˆ atan(x) – tan−1 (x) : Arctangent

−1 y
 
ˆ atan(y, x) – tan : Arctangent considering the sign of both arguments
x

1.11.3 Exponential and Logarithmic Functions


ˆ exp(x) – ex : Exponential function

ˆ log(x) – ln(x) : Natural logarithm (base e)

ˆ log10(x) – log10 (x) : Common logarithm (base 10)

1.11.4 Power and Root Functions


ˆ x^n – xn : Raises x to the power n

ˆ sqrt(x) – x : Square root of x
44 Chapter 1. Introduction to Scilab

1.11.5 Rounding Functions


ˆ round(x) – Rounds x to the nearest integer

ˆ floor(x) – ⌊x⌋ : Rounds x downwards

ˆ ceil(x) – ⌈x⌉ : Rounds x upwards

x = 4.7;
round(x); // 5
floor(x); // 4
ceil(x); // 5

1.11.6 Absolute and Sign Functions


ˆ abs(x) – |x| : Absolute value of x

ˆ sign(x) – Returns: 


 −1, x < 0

sign(x) = 0, x=0



1, x>0

1.11.7 Modulo Function


ˆ modulo(x, y) – x mod y : Remainder after division of x by y

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

Table 1.3: Elementary Mathematical Functions in Scilab


1.12. Demonstrations and Macros in Scilab 45

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.

ˆ Prefer atan(y,x) over atan(y/x) to correctly handle quadrant information.

ˆ Validate inputs before applying logarithmic or square root functions to avoid domain
errors.

ˆ Use rounding functions carefully when precision is important in numerical compu-


tations.

1.12 Demonstrations and Macros in Scilab

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:

ˆ Elementary Functions: Covers basic mathematical operations, matrix manipu-


lations, and fundamental programming concepts.
46 Chapter 1. Introduction to Scilab

ˆ Plotting and Graphics: Demonstrates 2D and 3D plotting techniques, cus-


tomization of figures, and interactive graphics tools.

ˆ Signal Processing: Provides examples for filtering, Fourier analysis, and signal
transformations.

ˆ Control Systems: Includes demonstrations on transfer functions, state-space


modeling, and system response analysis.

ˆ Optimization: Showcases algorithms and methods for solving linear and nonlinear
optimization problems.

Figure 1.3: Scilab Demonstration GUI Window

Exploring Demonstrations

Each demonstration provides:

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.

3. Graphical Output: Visualization of results in the graphics window for better


interpretation of concepts.
1.12. Demonstrations and Macros in Scilab 47

4. Step-by-Step Understanding: Clear code comments and documentation em-


bedded in each example.

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.

Best Practices for Using Demonstrations

ˆ Begin with elementary demonstrations before progressing to advanced topics such


as control systems or optimization.

ˆ 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

ˆ Demonstrations are an excellent resource for self-learning and teaching, especially


in academic settings.

ˆ 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.

Defining and Executing a Macro

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

Example: A Complete Macro Workflow The following example demonstrates how


to create, execute, and use a macro in Scilab.

// File: computeArea.sci
// This macro calculates the area of a circle for a given radius.

function area = computeArea(radius)


area = %pi * radius^2;
endfunction

Steps to Run the Macro:

1. Save the macro file as computeArea.sci.

2. Load the macro in Scilab using:

--> exec(’computeArea.sci’);

3. Call the macro with the desired input:

--> computeArea(5)
ans =
78.5398

This single workflow illustrates macro definition, loading, and output execution in a
clear manner.

Viewing Defined Macros

You can view all currently loaded macros using:

--> who(’f’) // Lists all functions (macros)

Saving and Loading Macros

Macros can be saved and reloaded for future sessions:

--> save(’myMacros.sav’) // Saves all current macros


--> load(’myMacros.sav’) // Loads previously saved macros
1.13. Toolboxes in Scilab 49

Advantages of Using Macros

ˆ Code Reusability: Write once and reuse across multiple scripts.

ˆ Modular Programming: Break down complex problems into manageable com-


ponents.

ˆ Reduced Errors: Encapsulate logic to minimize code duplication and mistakes.

ˆ Improved Readability: Macros make programs easier to understand and main-


tain.

Best Practices for Using Macros

ˆ Always include comments in macros to explain their purpose and logic.

ˆ Store macros in dedicated files or directories for better organization.

ˆ Use meaningful macro names that describe the functionality clearly.

ˆ 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.

1.13 Toolboxes in Scilab


Toolboxes in Scilab are structured collections of macros, functions, and utilities designed
to extend Scilab’s core capabilities for specialized domains. They enable users to ef-
ficiently perform advanced computational tasks in engineering, scientific research, and
data analysis without needing to develop every function from scratch. Toolboxes can be
developed by the Scilab community or provided officially by Scilab Enterprises.

Types of Toolboxes
Toolboxes in Scilab can be broadly classified into two categories:

ˆ Official Toolboxes: Developed and maintained by the Scilab team to ensure


stability and compatibility. These include:
50 Chapter 1. Introduction to Scilab

– Control System Toolbox – For modeling, analyzing, and designing linear


and nonlinear control systems.
– Signal Processing Toolbox – For operations such as filtering, spectral anal-
ysis, and convolution.
– Optimization Toolbox – For solving linear programming (LP), nonlinear
programming (NLP), and constrained optimization problems.
– Statistics Toolbox – For probability distributions, regression, hypothesis
testing, and data visualization.
– Image Processing Toolbox – For image filtering, transformations, segmen-
tation, and analysis.

ˆ Third-Party Toolboxes: Developed by the Scilab community or external con-


tributors to add domain-specific functionalities, such as machine learning, symbolic
computation, or specialized engineering libraries.

Managing Toolboxes in Scilab


Scilab provides the ATOMS (Automatic Toolboxes Manager for Scilab) system for installing,
updating, and managing toolboxes.

Accessing ATOMS

ˆ atomsGui() – Opens a graphical interface to browse, install, and manage toolboxes.

ˆ atomsInstall(’toolbox name’) – Installs a specific toolbox from the ATOMS


repository.

ˆ atomsLoad(’toolbox name’) – Loads an installed toolbox into the current session.

ˆ atomsRemove(’toolbox name’) – Uninstalls a toolbox from the system.

ˆ atomsSearch(’keyword’) – Searches for available toolboxes related to a given key-


word.

ˆ atomsUpdate() – Updates all installed toolboxes to their latest versions.

Example: Installing and Loading a Toolbox

The following example demonstrates how to install and load the Signal Processing Tool-
box:

--> atomsInstall(’signal_processing’); // Install toolbox


--> atomsLoad(’signal_processing’); // Load toolbox into session
1.14. Batch Processing in Scilab 51

Verifying Installed Toolboxes


To check the list of installed and loaded toolboxes:

--> atomsGetInstalled() // Displays installed toolboxes


--> atomsGetLoaded() // Displays currently loaded toolboxes

Best Practices for Using Toolboxes


ˆ Always use atomsUpdate() regularly to ensure toolboxes are up to date.

ˆ Verify compatibility between the Scilab version and the toolbox version before in-
stallation.

ˆ Use meaningful and domain-specific toolboxes to avoid unnecessary overhead.

ˆ Read the documentation of each toolbox for correct syntax and usage of its func-
tions.

ˆ Test new toolboxes in a controlled environment before deploying them in academic


or production work.

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.

1.14 Batch Processing in Scilab


Batch processing in Scilab enables the automated execution of a sequence of commands
stored in a script file. This feature is particularly useful for repetitive computations,
simulations, and data analysis tasks, allowing users to run programs without manual
intervention.
52 Chapter 1. Introduction to Scilab

Importance of Batch Processing


Batch processing offers several advantages:

ˆ Time Efficiency: Automates repetitive tasks and eliminates the need for manual
command entry.

ˆ Error Reduction: Reduces human error by executing predefined commands in a


controlled manner.

ˆ Reproducibility: Ensures consistent results, especially in academic research and


engineering simulations.

ˆ Teaching and Demonstration: Facilitates automated examples for classroom


demonstrations and assignments.

ˆ Visualization Support: Simplifies plotting and analysis of large datasets.

Example: Student Marks Analysis using Batch Processing


The following example demonstrates how to automate the analysis of student marks using
a Scilab batch script.
Save the script as student analysis.sce:
1 // student_analysis . sce
2 // Batch script to analyze student marks
3

4 // Step 1: Define the marks of students


5 marks = [89 , 76 , 45 , 92 , 66 , 58 , 81 , 73 , 95 , 60];
6

7 // Step 2: Compute key statistics


8 average_marks = mean ( marks ) ;
9 highest_mark = max ( marks ) ;
10 lowest_mark = min ( marks ) ;
11

12 // Step 3: Display results


13 disp ( " === Student Marks Analysis === " ) ;
14 disp ( " Average Marks : " + string ( average_marks ) ) ;
15 disp ( " Highest Mark : " + string ( highest_mark ) ) ;
16 disp ( " Lowest Mark : " + string ( lowest_mark ) ) ;
17

18 // Step 4: Plot a bar chart for visualization


19 bar ( marks ) ;
20 xtitle ( " Student Marks Distribution " , " Student Index " , " Marks " ) ;
1.14. Batch Processing in Scilab 53

Figure 1.4: Batch Processing Script Execution in Scilab

Figure 1.5: Output Console for Batch Processing in Scilab

How to Execute the Script


1. Open Scilab.

2. Navigate to the directory containing student analysis.sce.

3. Run the script using:

exec(’student_analysis.sce’, -1);

The script will execute automatically, and the results will be displayed in the console
along with the graph.

Best Practices for Batch Processing


1. Use Comments: Document each section of your script for better readability.

2. Organize Code Logically: Group related commands (data input, computation,


output, visualization).
54 Chapter 1. Introduction to Scilab

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.

1.15 Memory Management in Scilab


Efficient memory management is a fundamental aspect of scientific programming in
Scilab. Since numerical computations often involve large matrices and iterative pro-
cesses, improper memory usage can lead to performance degradation or runtime errors.
Scilab uses dynamic memory allocation for variables and automatically manages unused
memory through an internal garbage collector. However, users can optimize memory
usage by adopting good practices and using built-in memory management tools.

Key Commands for Memory Management


ˆ clear – Deletes specified variables from memory to free up space.

ˆ who – Displays all variables currently stored in the workspace.

ˆ whos() – Provides a detailed view of variables, including size and memory usage.

ˆ gstacksize() – Retrieves or modifies the size of the graphics memory stack.


1.15. Memory Management in Scilab 55

ˆ predef() – Protects or unprotects predefined variables from being accidentally


overwritten.

Managing the Stack Size


Scilab maintains an internal stack to store variables, function calls, and temporary com-
putation data. In cases involving large simulations or matrix operations, the default stack
size may be insufficient.

--> stacksize() // View current stack size


--> stacksize(10000000) // Increase stack size to 10 million (advanced usage)

Note: Increasing stack size should be done cautiously and only when necessary, as
allocating excessive memory may impact system performance.

Example: Clearing Memory and Monitoring Usage

1 // Create large variables


2 A = rand (5000 , 5000) ;
3 B = rand (4000 , 4000) ;
4

5 // Check memory usage


6 whos () ;
7

8 // Clear unused variable


9 clear B ;
10

11 // Verify memory status after clearing


12 whos () ;

Best Practices for Memory Management


1. Remove Unused Variables: Regularly use clear to delete unnecessary variables.

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.

6. Release Graphics Memory: Use gstacksize() for monitoring and managing


graphics memory when working with plots.

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.

ˆ Over-allocating memory may negatively affect other running processes; balance


memory settings based on system capacity.

Exercise 1 – Introduction to Scilab


Answer the following questions. Questions 1.1 to 1.10 are theoretical, and questions
1.11 to 1.20 are practical programming tasks. These exercises are designed to test your
understanding of basic Scilab concepts and their applications.

Part A – Theory Questions


1.1 Define Scilab. Explain its importance in scientific computation.

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.6 What are dynamic variables in Scilab? Explain with an example.

1.7 Write short notes on elementary mathematical functions in Scilab:

(a) Trigonometric functions


(b) Inverse trigonometric functions
(c) Exponential and logarithmic functions
1.15. Memory Management in Scilab 57

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.

Part B – Practical Questions


1.11 Write a Scilab script to display the values of the predefined variables %pi, %e, and
%i.

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.14 Write a Scilab program to compute:

(a) sin(45◦ ), cos(60◦ )


(b) arcsin(0.5), arccos(0.5)
(c) e2 , ln(10)

1.15 Write a program to find the power and square root of a number entered by the user.

1.16 Write a script to round a number to:

(a) Nearest integer using round()


(b) Ceiling value using ceil()
(c) Floor value using floor()

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.

1.20 Write a program to create a workflow in Scilab that:

(a) Defines a variable


58 Chapter 1. Introduction to Scilab

(b) Performs arithmetic and trigonometric operations


(c) Stores the result in a list
(d) Displays the list contents

You might also like