You are on page 1of 22

1 The Scilab environment

To start Scilab:

Double-click the Scilab icon on the PC desktop, or


Go to Start / All Programs / Scilab / scilab (do not select scilab console).
Start Scilab.

Starting Scilab opens the Scilab command window, see the figure below.

The Scilab command window


Scilab commands are executed at the command line by entering the command, and
then clicking the Enter button on the keyboard.
Execute 1+1 (type 1+1 at the command line, and finish with Enter-button).

The result is shown in the command window (see the figure above).

2 Scilab Help
Open Scilab Help by clicking the Help button in the toolbar (the button with the question mark).

The Help window is shown below.

Scilab Help window


As you see from the Help window, the commands and functions are organized in a
number of categories.

As an example, click the Elementary Functions category to see the functions in that category.

The functions are as shown in the figure above.


To get detailed help text about a specific function, click that function.
Click the abs function (in the Elementary Functions category).

The detailed help text for the abs function is shown in the figure below.

The detailed help text for the abs function

You can also search for a function by first clicking the Search button in the Help
window (the magnifying glass button).
Search for sine.

The result of the search is a list of relevant functions, see the figure below.

The result of the search for sine

3 Basic Scilab operations


Typically you use variables in your calculations. To create the variable a and
assigning to it the result of 1+1:
a=1+1 (Enter)

Hereafter, (Enter) will not be shown, but it is assumed that you click the Enter button.

The response is shown in the command window (but shown here). Now, try
(remember to type the semicolon):
b=1+2;

The response is not shown in the command window. The command was actually
executed, but because of the semicolon the response was not shown. To verify that the
variable b actually exists:
b

As you will see, it exists.


If you omit the variable name, the result is assigned to the inbuilt variable ans:
2+2

The response shows that the variable ans has got the value 4.
You can execute one or more commands - separated by semicolon or comma - on one
line:
c=2+3, d=2+4

Scilab is case-sensitive. For example, d and D are two different variables:


d, D

As you see from the response (not shown here), d exists, while D does not exist (since
we have not created D).
Scilab variables exists in the workspace. There are two ways to see the contents of a
workspace:

Executing the command who at the command line, which just lists the variables
in the command window.
Menu Applications / Browser Variables, which opens the Browser Variables
window.
Execute the command who.

The response should be similar to what is shown in the figure below. (The userdefined variables are shown among many other variables.)

The response of the command who


Select the menu Applications / Browser Variables.

This opens the Browser Variables window, see the figure below.

Browser Variables window

The Browser Variables window contains at the bottom a number of utility buttons (not
described in detail here).
Note that if you exit from Scilab, the variables you created in the workspace are
deleted. You can save variables in a file using the save function. However, if you
really need to save variables that are a result of some Scilab expressions, then you
should consider writing these expressions in a Scilab script instead. More about
scripts soon.
There are various ways to enter numbers (the pi is an inbuilt constant). Here are some
illustrative examples (I assume that you see the principles from these examples):
0.1, 1e-1, 2^3, exp(1), pi

The response is shown in the figure below.

Various ways to enter numbers


You can determine how numbers are displayed in the command window with
the format function, but the internal representation of the number in Scilab
isindependent if the display format. We will not look at details. If you need to change
the display format, consult Scilab Help.
Scilab functions are vectorized, i.e. functions can be called with vectorial arguments.
(A vector is simply a one-dimensional matrix. We will return to vector- and matrix

operations in a later section.) In the following example, first a vector of name t is


created, then this vector is used as an argument in the sine function (thesine function
assumes the argument is an angle in radians).
t=[0:10]', sin(0.1*t)

The response is shown in the figure below.

The result of the vectorized function call sin(0.1*t) where t is a vector

4 Scripts
A Scilab script is a text file of name *.sce containing Scilab commands. You can edit
the script using the inbuilt Scipad editor. (Scripts can also have names *.sci. The
default name when saving a fle in Scipad is *.sce.)
You should use scripts even for small tasks because in this way you have all your
"projects" saved in files which is good for documentation and also very convenient
when you want to run all your commands after some changes.
We will now create a simple script, and then run it. Running a script is the same as
executing all the commands (from top to bottom in the script) at the command line
one by one.
Launch the Scipad editor by selecting the Editor menu (or by executing the scipad command).
Then enter the commands shown in the figure below.

The Scipad editor is shown in the figure below. Note that double slashes (//) are used
to start comments in the script.

Scilab script of name script1.sce opened in the Scipad editor

Note that you can open several scripts in the same Scipad window with the File /
New menu.
Save the script with name script1.sce (of course some other name can be used) in the directory
(folder) C:\temp or in any other directory you prefer.

There are two ways to run the script1.sce script:

With the Execute / Load into Scilab menu in Scipad


By executing the command exec script1.sce at the command line

Let us try the Execute menu first:


Select the Execute / Load into Scilab menu in Scipad.

The result is shown in the command window.


Now let us try the exec command:
Execute the command exec script1.sce at the command line.

Scilab responds with an error! See below.

Scilab responds with an error when after executing the command exec script1.sce

The error comes because script1.sce is not in the Current directory of Scilab. The
Current directory is the directory where Scilab looks for your script when you try to
execute it with the exec command. What is then the present Current directory?
Excute the menu File / Get Current Directory.

The response (in the command window) may be different on different PCs. On my PC
the response is
C:\Documents and Settings\User\SciLab
We saved script1.sce in the C:\temp directory which is different from the present
Current Directory. Let us change the Current Directory to C:\temp, and then execute
the script:
Excute the menu File / Change Directory. This opens a window in which you select to become
the Current directory.
Execute the command exec script1.sce at the command line.

Now the script should run without errors.

5 Matrix operations
In Scilab numbers are in general stored in matrices, which can be regarded as a table.
Matrices with only one column or only one row are denoted vectors. (Matrices and
vectors are very similar to arrays as used in programming languages as C, Visual
Basic etc.)
Creating matrices. Retrieving data from matrices
Let us create a 2x2 matrix of name A. In general, comma (or space) is used to separate
numers on a row (or line), and semicolon is used to separate rows.
A=[1,2;3,4]

The figure below shows A as displayed in the command window.

Creating and displaying the matrix A


Create a row vector with first element 0, last element 1 and increment (step size) 0.2:
r=[0:0.2:1]

Create a column vector, note the apostrophe to transpose:


c=[0:0.2:1]'

Create matrix B from given column vectors x and y:


x=[1,2,3]'; y=[4,5,6]'; B=[x,y]

Get the size (dimensions) of matrix B:


size(B)

Get the first element of vector r. Note that 1 (not 0) is the first index!
r(1)

Now try
r(0)

You get an error because index number 0 can not be used.

Get the second column in matrix B, and assign the values to vector v:
v=B(:,2)

Some special matrices


Create an identity matrix of dimension 2x2:
C=eye(2,2)

Create a matrix of dimension 3x2 consisting of ones:


D=ones(3,2)

Create a matrix of dimension 3x2 consisting of zeros:


E=zeros(3,2)

Matrix calculations
Matrices can be used in matrix calculations.
Add two matrices (assuming A and C have been created as explained above):
F=A+C

Multiply two matrices:


G=A*C

Take the inverse of a matrix:


H=inv(A)

Elementwise calculations
Elementwise calculations are made with the dot operator. As an example, to perform
elemenwise multiplication of two vectors:
v1=[1,2], v2=[3,4], z=v1.*v2

The result is shown in the figure below. Element z(1) is v1(1)*v2(1), and element z(2)
is v1(2)*v2(2).

Elementwise multiplication of two vectors

6 Plotting
The basic command for plotting data in a figure is plot. In the following are a number
of examples demonstrating various plotting options. (It is of course up to you if
you type the code from scratch on the command line or in Scipad, or if you
just copy the code. If you type the commands, you may omit the comments which is
the text following the // sign to save time.)
First, let us generate some data that will be used in the following examples.
t=[0:.1:10]'; //t is a column vector
u=-1+0.2*t; //u is a column vector
y=sin(2*t); //y is a column vector

Very basic plotting:


scf(1); //Opens (new) figure with ID 1. (scf = set current fig)
plot(y) //Plots y against y-indexes (integers along x-axis)

Below is shown the Scilab figure with the plot. Along the x-axis are the indexes of the
y vector. The indexes are integers from 1 to 101.

Before we continue with more plotting commands, let us take a look at some buttons
and menus in the Graphics window.
Click the GED button in the figure window.

This opens the Clicking the GED button opens the Graphics Editor, see the figure
below.

The Graphics Editor


With the graphics editor you can change line colours, line style, add labels to the axis,
add grid, etc. The various options will not be described here because it is rather easy
to investigate the possibilities by yourself. Many of the options in the Graphics Editor
can alternatively be set with options to the plot command. This will be shown in
subsequent examples.
You can produce various graphics files from the plot:
Select the menu File / Export in the figure window.

This opens the Export dialog window shown below.

The Export dialog in the figure window


If you want to create a graphis file to put into a document processor, as MS Word or
Scientific Workplace, you should select Enhanced Meta File (EMF), whch is a
vectorized graphics format which means that the picture can be enlarged and still look
sharp. However, EMF files can not be used in native web documents, e.g. in HTMLfiles to be displayed in a web browser. In this case you should select the GIF format
(this format does not give you vectorized graphics).
We continue with looking at more options to the plot command.
Assume that we will plot y against t in Figure 1 which is the same figure as we used
above. This is done with the command plot(t,y) where it is of course assumed that
vectors t and y have the same length (same number of elements).
If you just use the plot command, the new plot adds to the previous plot, showing two
(or more curves). Typically, this is not what you want. To clear the previous plot, we
use the clf (clear figure) command before we use the plot command.
//Clears a plot, and plots in the same figure:
scf(1); //Sets figure 1 to become current figure
clf; //clears the figure
plot(t,y) //Plots in figure 1

The result is shown in the figure below. Observe that the x-axis now contains
the t values.

Suppose you want to show the plot in a new Figure 2 in stead of the previously
opened Figure 1:
scf(2); //Sets figure 2 to become current figure
plot(t,y) //Plots in figure 1

To clear Figure 2:
Just close the Figure 2 window by clicking the close button in the upper right corner of the
window (or with the menu File / Close in the window).

To plot with with grid and plot title and labels:


scf(1); //Opens (new) figure with ID 1. (scf = set current fig)
plot(t,y) //Plots u against t
ax1=gca();ax1.grid=[0,0];//Adds grid. (gca=get current axes)
//[0,0] is colour code for x and y grid, resp. [0,0] is black.
title('Experiment 1')
xlabel('t [s]')
ylabel('y [V]')

The resulting plot is shown in the figure below. (If you think the
code ax1=gca();ax1.grid=[0,0]; is too cumbersome for generating a grid, you can in
stead use the Graphics Editor (by clicking the GED button in the figure window).)

To plot two curves in one plot (note the ordering of the vectors in the plot command):
scf(1);clf; //Opens figure 1 and clears its present content
plot(t,y,t,u) //Plots y against t, and u against t

The result is shown in the figure below.

To plot two curves with options for the line style and colours:
scf(1); clf; //Opens and clears figure 1
plot(t,y,'r--',t,u,'b') //'r--' is red and dashes. 'b' is blue.

(Many more options can be found from Help linespec.) The result is shown in the
figure below.

To plot several subplots in one figure:


scf(1); clf; //Opens and clears figure 1
subplot(211) //Plot number 1 in a 2x1 "table" of plots
plot(t,u)
subplot(212) //Plot number 2 in the 2x1 "table" of plots
plot(t,y)

The result is shown in the figure below.

Subplots

You might also like