Sei sulla pagina 1di 20

EXERCISE NOTES:

MAIN WINDOWS
Scilab’s user interface consists of three main windows:
1. The Console, which pops up when Scilab is opened and on which it outputs
textual data (numeric answers, error messages, etc.)
2. The Editor, which is the main tool for writing, saving, and executing scripts
(programs)
3. The Graphics Window, on which Scilab presents plots.
SAMPLE SCRIPT
Plot y=0.5xsin(2x) from x=0 to x=10

Step 1: On the console, click the Editor icon on the toolbar. The Editor should pop
up.
Step 2: Define what variables your function needs. In row 1, type
x=[0:.1:10]’; a=.5*x;
Step 3: Next, define the function. In row 2, type y=a*sin(2*x);
Step 4: Finally, write the plot command. In row 3, type plot (x,y)
Step 5: Save the script by clicking on the Save icon, and name it wave1.sce.
Step 6: Finish by running the script. Click the Execute icon.
Step 7: Up pops the Graphic window with the plot of the defined equation. Sketch
the graph below.

THE HELP MENU


The help menu may be accessed by:
1. Clicking on the ______________ found in the menu bar.
2. Using the shortcut key ________.
3. Directly typing help on the command line in the Console and pressing Enter.
What happened after you pressed Enter? _______________________

Or to get help on the Scilab command module, simply type --> help module on the
command line.

Use the “help” menu to find what the following words denote or are used for:
a. ans _________________________________________
b. typeof ______________________________________
c. clear _______________________________________
d. clc _________________________________________
e. comma _____________________________________
f. semicolon ___________________________________
g. exists _______________________________________
h. who ________________________________________
i. list _________________________________________
j. rand ________________________________________
k. comments ___________________________________
l. disp ________________________________________
m. length ______________________________________

VARIABLES
Variables are case-sensitive and cannot contain blanks or spaces. To load a value
into a variable, use the equal sign. Try the following exercises for simple arithmetic
operations:
-->a=5 assigns the value 5 to variable a
-->b=2; assigns the value 2 to variable b
-->c=a+b _________________________
-->d=a-b _________________________
-->e=a*b _________________________
-->f=a/b _________________________
-->g=a^b _________________________
-->who _________________________
_________________________
Note that Scilab evaluates immediately lines that end with a carriage return.
Instructions that end with a semi-colon are evaluated but are not displayed on
screen.

SCILAB DATA OBJECTS


Scilab recognizes several data types. Scalar objects are constants, Booleans,
polynomials, strings and rationals (quotients of polynomials). These objects in turn
allow to define matrices which admit these scalars as entries. The other basic
objects lists, typed-lists and functions, along with polynomials, will not be explained
in this activity.
Special Constants
These variables, such as %i, %e and %pi, are considered as “predefined.” They
are protected, cannot be deleted and are not saved by the save command.
Boolean (logical) constants are %t and %f.
Try the following exercises to see what values are returned by Scilab:
a. %i _______________________________________
b. %e ______________________________________
c. %pi ______________________________________
d. %eps ____________________________________
e. %inf _____________________________________
f. %nan ____________________________________
g. %t _______________________________________
h. %f _______________________________________

Constant Matrices
Scilab considers a number of data objects as matrices. Scalars and Vectors are
all considered as matrices.

Scalars
Scalars are either real or complex numbers. The values of scalars can be assigned
to variable names chosen by the user.
Output
-->A=3 ______________________
-->B=5+3*%i ______________________

Try assigning the following values to the indicated variables:


1. Assign 10 to the variable X ______________________
2. Assign 3i to the variable Y ______________________
3. Assign 10i+12 to the variable Z
_____________________________________________

Vectors
 The usual way of creating vectors is as follows:
Output
--> v=[2, -3+%i, 7] ______________________
--> w=[4 16 28*%i] ______________________
--> x=[-7; -7+%i; 19] ______________________
______________________
______________________
-->y=[-5 <return> ______________________
2 <return> ______________________
%pi] ______________________

What do you notice about the use of commas, blanks, semicolons and carriage
return in creating vectors?
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________

 Without clearing the window, type the following


-->r = v’
-->s = w’
-->t = x’

The single quote ( ‘ ) is used for ______________________


________________________________________________

 Note with the following examples the role of the position of the blank:
Output
--> a=[1 +3] ____________________________
--> b=[1 + 3] ____________________________
--> c=[1+ 3] ____________________________
--> d=[1, + 8- 7] ____________________________

 Vectors of elements which increase or decrease incrementally are constructed as


follows
--> v = 5 : -0.5 : 3

The resulting vectors begins with the first value and ends with the third value
stepping in increments of the second value. When not specified the default
increment is one.

Try the following exercises.


-->v1=1:7

-->v2=1:2:7

-->v3=-1:3:9

-->v4=1: -3: 9

-->v5=10 : -2 : 0

-->v6=10 : -2 :1

-->v7 = 10 : 4 : 0

 The linspace function creates a linearly spaced vector with the arguments from,
to, number of points. The default value is 100 points.
--> linspace(0,3,6)

--> linspace(9,6,5)

Matrices
 Row elements are separated by commas or spaces and column elements by
semi-colons.

Try the following exercises and write what values are returned by Scilab:

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

2. --> B=ones(2,3)

3. -->A.*B
4. -->A*B

5. --> C=zeros(2,4)

6. -->D=[1,2,3; 4,5,6;7,8,9]

Notice that the ones operator with two real numbers as arguments separated by
a comma creates a matric of ones using the arguments as dimensions (same for
zeros).

 Matrices can be used as elements to larger matrices. Furthermore, the


dimensions of a matrix can be changed.

Try the following exercises and write what values are returned by Scilab:
-->A=[1 2; 3 4]

-->B=[5 6; 7 8]

-->C=[9 10;11 12]

-->D=[A;B;C]
-->E=matrix(D,3,4)

-->F=eye(E)

-->G=eye(4,3)

Notice that matrix D is created by using other matrix elements. The matrix
primitive creates a new matrix E with the elements of the matrix D using the
dimensions specified by the second two arguments.

The element ordering in the matrix D is top to bottom and then left to right.
Explain the ordering of the rearranged matrix in E
________________________________________________________________
________________________________________________________________
________________________________________________________________

Matrices of Character Strings


Character strings can be created by using single or double quotes.
Concatenation of strings is performed by the + operation. Matrices of character
strings are constructed as ordinary matrices using brackets. A very important
feature of matrices of character strings is the capacity to manipulate and create
functions.

Try the following exercises:


1. --> A=[‘x’ ‘y’ ; ‘z’ ‘w+v’]

2. -->a=’’<________________>” //first name

-->b=”<spaces>” //space

-->c=”<________________>” //last name

-->a+b+c
In mathematics, a matrix (plural: matrices) is a rectangular array of numbers,
symbols, or expressions, arranged in rows and columns. For example, the dimensions
of the matrix below are 2 × 3 (read "two by three"), because there are two rows and
three columns:

The individual items in an m × n matrix A, often denoted by ai,j, where max i = m


and max j = n, are called its elements or entries. Provided that they have the same size
(each matrix has the same number of rows and the same number of columns as the
other), two matrices can be added or subtracted element by element (see Conformable
matrix). The rule for matrix multiplication, however, is that two matrices can be
multiplied only when the number of columns in the first equals the number of rows in the
second (i.e., the inner dimensions are the same, n for Am,n × Bn,p). Any matrix can be
multiplied element-wise by a scalar from its associated field. A major application of
matrices is to represent linear transformations, that is, generalizations of linear functions
such as f(x) = 4x. For example, the rotation of vectors in three-dimensional space is a
linear transformation, which can be represented by a rotation matrix R: if v is a column
vector (a matrix with only one column) describing the position of a point in space, the
product Rv is a column vector describing the position of that point after a rotation. The
product of two transformation matrices is a matrix that represents the composition of
two transformations. Another application of matrices is in the solution of systems of
linear equations. If the matrix is square, it is possible to deduce some of its properties
by computing its determinant. For example, a square matrix has an inverse if and only if
its determinant is not zero. Insight into the geometry of a linear transformation is
obtainable (along with other information) from the matrix's eigenvalues and
eigenvectors.

Applications of matrices are found in most scientific fields. In every branch of


physics, including classical mechanics, optics, electromagnetism, quantum mechanics,
and quantum electrodynamics, they are used to study physical phenomena, such as the
motion of rigid bodies. In computer graphics, they are used to manipulate 3D models
and project them onto a 2-dimensional screen. In probability theory and statistics,
stochastic matrices are used to describe sets of probabilities; for instance, they are
used within the PageRank algorithm that ranks the pages in a Google search. Matrix
calculus generalizes classical analytical notions such as derivatives and exponentials to
higher dimensions. Matrices are used in economics to describe systems of economic
relationships.

A major branch of numerical analysis is devoted to the development of efficient


algorithms for matrix computations, a subject that is centuries old and is today an
expanding area of research. Matrix decomposition methods simplify computations, both
theoretically and practically. Algorithms that are tailored to particular matrix structures,
such as sparse matrices and near-diagonal matrices, expedite computations in finite
element method and other computations. Infinite matrices occur in planetary theory and
in atomic theory. A simple example of an infinite matrix is the matrix representing the
derivative operator, which acts on the Taylor series of a function.

Although Scilab is a useful calculator, its main power is that it gives a simple way
of working with matrices. Remember to keep typing in the commands as they
appear here, and observe and understand the Scilab response.

EXERCISE 1
Find x1, x2, and x3 so that
x1 + 2x2 − x3 = 1
−2x1 − 6x2 + 4x3 = −2
−x1 − 3x2 + 3x3 = 1

Although these problems can be solved manually by eliminating unknowns, this is


unpleasant. Besides, errors usually occur. The problem may be rewritten in matrix-
vector notation as Ax = b, where
A = 1 2 -1 x=[ x1, x2, x3] b= 1
-2 -6 4 -2
-1 -3 3 1

In spite of the new notation, it is still just as unpleasant to find the solution. In Scilab,
we can set up the equations and find the solution x using simple commands.

-->A=___________________________; //Set up A
-->b=___________________; //Set up b
-->x=___________________ // Find x

x=

-->A*x // Check that Ax and b are the same

-->b

-->b-A*x //So that we do not miss small


differences, check that b - Ax=0

The vector b − Ax is known as the residual.


EXERCISE 2
-->A = [1 2 3 4 ; 1 4 9 16 ; 1 8 27 64 ; 1 16 81 256 ]

-->A’

-->det(A)

-->spec(A)

-->inv(A)

Use the “help” menu to find what the following were used for in the above exercise:
a. ‘ ________________________________________
b. det______________________________________
c. spec________________________________________
d, inv_________________________________________

EXERCISE 3
-->a=”Scilab” //a 1x1 string matrix

-->b=rand(2,2) //a matrix

-->b = b>=0.5 //a Boolean matrix

-->L=list(a,b) //a list


EXERCISE 4 Matrix creation

--> eye(2,1)

-->3*ones(2,3)

--> linspace(3,9,4)

--> zeros(1,4)

-->A= [eye(2,1), 3*ones(2,3); linspace(3,9,4); zeros(1,4)]

Observation/s:
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________

EXERCISE 5 Matrix creation

-->A= [eye(2,1), 3*ones(2,3); linspace(3,9,4); zeros(1,4)]

-->x=diag(A) //main diagonal of A


-->d=diag(A)’ //main diagonal of A as a row matrix

-->B=diag(d) //build a diagonal matrix

-->C=matrix(d,2,2) //reshape vector d

Observation/s:
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________

EXERCISE 6 Assignment, Deletion and Extraction


To specify a set of matrix entries for the matrix A we use the syntax A(B) or A(B,C),
where B and C are numeric or boolean matrices that are used as indices. The
interpretation of A(B) and A(B,C) depends on whether it is on the left- or right-hand
side of an assignment = if an assignment is present.

If we have A(B) or A(B,C) on the left, and the right-hand side evaluates to a nonnull
matrix, then an assignment operation is performed. In that case the left member
expression stands for a submatrix description whose entries are replaced by the
ones of the right matrix entries. Of course, the right and left submatrices must have
compatible sizes, that is, they must have the same size, or the right-hand-side
matrix must be a scalar.

If the right-hand-side expression evaluates to an empty matrix, then the operation


is a deletion operation. Entries of the left-hand-side matrix expression are deleted.
Assignment or deletion can change dynamically the size of the left-hand-side
matrix.
Observation
-->A(2,4)=1 ______________________
______________________
______________________

-->x=int(5*rand(2,2)) ______________________
______________________
______________________

-->A([1,2],[1,2])=x ______________________
______________________
______________________

-->A([1,2],[1,3])=[ ] ______________________
______________________
______________________

-->A(: ,1)= 8 ______________________


______________________
______________________

-->A(:,$)=[ ] ______________________
______________________
______________________

-->A(:,$+1)=[4;5] ______________________
______________________
______________________

What does ‘ : ‘ denote?


________________________________________________________________
________________________________________________________________

What does ‘ $ ‘ denote?


________________________________________________________________
________________________________________________________________

When an expression A(B) or A(B,C) is not the left member of an assignment, then
it stands for a submatrix extraction and its evaluation builds a new matrix.

-->A = int(10*rand(3,7))

-->B=A([1,3],$-1:$) Observation:______________________
______________________
______________________
______________________
______________________
______________________
______________________

EXERCISE 7 Assignment, Deletion and Extraction


-->A = [1 2 3 4 ; 1 4 9 16 ; 1 8 27 64 ; 1 16 81 256 ]

-->A(2,3)

-->A(1:2,2:4)

-->A(:,2)

-->A(3,:)

-->A(2:$,$)

-->A($,:)

In general A( i:j, k:l ) means the square sub–block of A between rows i to j and
columns k to l . The ranges can be replaced by just ‘:’ if all rows or columns are
to be included. The last row or column is designated $.

How would you display the bottom left 2 × 3 corner of A?


-->
How would you find the determinant of the upper left 3 × 3 block of A?
-->

Plotting in Scilab Part 1

A plot is a graphical technique for representing a data set, usually as a graph


showing the relationship between two or more variables. The plot can be drawn by
hand or by a mechanical or electronic plotter. Graphs are a visual representation
of the relationship between variables, very useful for humans who can quickly
derive an understanding which would not come from lists of values. Graphs can
also be used to read off the value of an unknown variable plotted as a function of
a known one. Graphs of functions are used in mathematics, sciences, engineering,
technology, finance, and other areas.
CREATING ARRAYS OF VALUES

To create a simple plot of a quantity "y" versus another quantity "x",


1. create the "x" array
2. create the "y" array
3. call the plot command

It's often simplest to create an array of "x" values using Scilab's "implicit for loop".
Try the statement:

x = 0 : 0.5 : 10

This creates an array which starts at 0, ends at 10, and increases by 1 at


each step. Thus, how does it looks like?

Observation:______________________________________________________
________________________________________________________________
________________________________________________________________

In most cases, when you call a function with an array as an argument, the
function will be applied to each element of the array individually, and the results
stored in an output array of the same size. Thus, if the function plusone adds 1.0
to its argument, then

y=x+1

will yield an array y which looks like this:


Observation:______________________________________________________
________________________________________________________________
________________________________________________________________

CALLING PLOT

Once you have two arrays of the same size, you can plot one against the
other via the plot command.

Carry out the following:


--> x = 0 : 0.1 : 10;
--> y = sin(x);
--> plot(x, y);
creates a window which looks like this:

Observation:______________________________________________________
________________________________________________________________
________________________________________________________________

OPTIONS TO THE PLOT COMMAND

There are a number of options to the plot command, which you can read
by typing help plot in the Scilab Control Window. Perform the following:

A) Plot individual points together with a connected line:


--> x = 0 : 0.1 : 10;
--> y = sin(2*x);
--> plot(x, y, 'o');
creates a window which looks like this:

Observation:______________________________________________________
________________________________________________________________
________________________________________________________________

B)Plot several different sets of data together:


--> x = 0 : 0.1 : 10;
--> y = sin(2*x);
--> z = cos(3*x);
--> plot(x, y, x, z);

creates a window which looks like this:

Observation:______________________________________________________
________________________________________________________________
________________________________________________________________

OTHER USEFUL PLOT-RELATED FUNCTIONS


Another useful command is mtlb_axis, which lets you control the size of
the axes. If we already created the plot with both sine and cosine functions, we
can resize it by typing

-->mtlb_axis([-2, 5, -3, 3]);

which changes the plotting window so it looks like this:

Observation:______________________________________________________
________________________________________________________________
________________________________________________________________

To put labels on your graph, you can call


the xlabel, ylabel and title commands.
Execute the commands:
--> x = 0 : 0.1 : 10;
--> y = sin(x);
--> plot(x, y);
--> xlabel ('Time since 1934');
--> ylabel ('Value of GE Stock');
--> title ('Volatility in the Market');

which changes the plotting window so it looks like this:

Observation:______________________________________________________
________________________________________________________________
_______________________________________________________________
Finally, the clf command allows you to control whether each plotting
command draws on top of the existing graph, or clears the window before drawing.

Look at the difference between this:


-->x = 0 : 0.1 : 10;
-->y = sin(x);
-->z = sin(2*x);
-->plot(x, y);
-->plot(x, z, '+');

which superimposes all the data and plotting window so it looks like this:

Observation:______________________________________________________
________________________________________________________________
________________________________________________________________

This sequence, which uses the clf command to wipe the graphics window
clean after the first graph has been displayed.
-->x = 0 : 0.1 : 10;
-->y = sin(x);
-->z = sin(2*x);
-->plot(x, y);
-->clf;
-->plot(x, z, '+');

Thus creates the window:


Observation:
________________________________________________________________
________________________________________________________________
________________________________________________________________

Potrebbero piacerti anche