Scilab Overview
Scilab version: 4.1.2
Invocation and Help
From the (Unix) command line:
unix> scilab graphical interface with command window unix> scilab -h lists command line switches
In the command window:
help keyword online help for keyword quit terminate Scilab
Expressions and Assignment
Expressions can be terminated with <CRT>, comma or semicolon. The result is echoed in a standard numerical format, except for the semicolon, which implies quiet evaluation.
The standard format for numerical output is changed e.g. as follows:
format('v', 10) variable format, up to 10 digits (default) format('e', 16) exponential format, up to 16 digits
If the result is assigned to a variable:
var = expression
its type and size is (re)allocated automatically.
Operators
Scalar and vector/matrix operations:
+ - * / ^ ** (matrix) exponentiation ( ) arithmetic precendence; also for arguments (of functions) and indices (of vectors and matrices)
Element-wise vector/matrix operations:
.* ./ .^
More matrix operations:
\ left inverse ' Hermitean conjugation .' transposition
Relational operators:
== ~= <> < > <= >=
~= and <> are equivalent.
Logical operators:
& | ~
See also matrix functions and(..), or(..).
Lists:
n1:n2 n1, n1+1, n1+2, .. n1:dn:n2 n1, n1+dn, n1+2*dn, ..
Names
Names in Scilab consist of
letters (case sensitive) digits (digit not as 1st character) special characters % _ # ! $ ? (percent as 1st character only)
- Maximal length is 24 characters (the rest will be ignored).
- It appears that variables and functions share the same name space. In this way, assignments to variables like beta, gamma will hide the corresponding functions (with a warning).
- On the other hand, function calls with an empty argument list often allow to drop the brackets, e.g. clf instead of clf()
Constants
%pi %i %e %eps %inf %nan %t %T %f %F %s ???
Built-in functions
abs sqrt exp log log10 log2 sin cos tan cotg sinh cosh tanh coth asin acos atan asinh acosh atanh gamma gammaln dlgamma beta erf erfc ...
More info:
help elementary
Local and global variables
global a b .. give access to named variables clear a b .. clear named variables clear clear all variables clearglobal a b .. clear named global variables clearglobal clear all global variables who list all current variables who('local') list local variables who('global') list global variables whos() list all variables etc whos -name pat list all variables starting with pat
Data Types
Numerical data are 64bit (double precision) real floating point numbers by default. Complex numbers may appear as input of expressions or results of function calls. In this case, the evaluation will switch to complex arithmetic, and data will be allocated as (double) complex automatically.
Integer data types of different size exist, they have to be specified explicitly (e.g. int8(5)) and are mainly for compact storage, not for computations.
Finally, there are string data.
All data are considered as matrices, with scalars, row and column vectors as special cases. Storage will be allocated as needed.
Complex numbers
z = 3 + 4*%i complex constant z = complex(a,b) z = a + bi for real a, b zc = conj(z) complex conjugate a = real(z) b = imag(z)
Note: Scilab does not support Matlab's notation z = 3 + 4i for complex constants.
Strings
'xyz' or "xyz" + concatenation operator string(x) convert number to string disp(str) display string disp('result = '+string(%pi)) example with string handling
Note: The notation "xyz" is not supported by Matlab.
Matrix Operations
Explicit initialisation
u = [1 3 5] row vector v = [4; 6; 8] column vector A = [1 3 5; 6 4 2] matrix w = [x1:dx:x2] row vector, generated by a list
Special initialisations
zeros(m,n) matrix filled with zeros ones(m,n) matrix filled with ones eye(m,n) unit matrix rand(m,n) random matrix (uniform in [0,1])
In these calls, a sample matrix can be given instead, e.g. zeros(A). But note that zeros(n) has just one element, taking "n" as a sample matrix!
diag(v) diagnonal matrix with entries from vector v
Matrix size
size(A) returns both sizes as a two-component vector size(A,1) size of first dimension size(A,2) size of second dimension length(A) = size(A,1) * size(A,2)
Matrix functions
inv(A), A^(-1) inverse A / B = A * B^(-1) A \ B = A^(-1) * B A' Hermitean conjugation A.' transposition conj(A) complex conjugate diag(A) diagonal sum, prod max, min, norm det, trace, spec and, or ...
In addition, some special functions are defined for square matrices, e.g. expm, sinm, ..
The "normal" functions (exp, sin, ..), applied to a vector or matrix, act element-wise.
Often enough, matrix operations are invoked by mistake: failing to specify element-wise operation, an error message complains about inconsistent matrix dimensions.
A particular case is
1./A ?? 1 ./A element-wise
In the first version, Scilab (in contrast to Matlab!) considers the dot as part of the number. The effect is to try a matrix inversion, which may end up in a "pseudo-inverse", with surprising results! A typical example is
1 ./[1:5] 1./[1:5] help slash help pinv
Functions
Define a function:
function y = myfct(x) y = ... endfunction function [y1, y2] = myfct(x1, x2, x3) y1 = ... y2 = ... endfunction myfct(a, b, c) function call returns y1 [p, q] = myfct(a, b, c) function call returns p=y1, q=y2
- A function can be formulated without a return value and/or with empty or missing argument list.
- If a function returns several items, its call will result in the first one, unless it is assigned to an appropriate list of result items.
- Inside the function's body, assignments are quiet (no need for `;'). Output may be produced with disp(..).
- Local variables of the calling context are available, but "read only". They can be changed locally, but this has no effect on the calling side and is not preserved across calls.
- If an external variable is to be changed from within the function, it has to be declared "global" both in the calling context and in the body of the function.
Numerical Integration
A definite integral can be computed in two ways.
intg needs a function definition in the first place, it does not handle expressions or built-in functions directly:
intg(a, b, fct) function y = fct(x) y = sin(2*x) endfunction intg(0, %pi/2, fct)
integrate is more flexible (but slower), it expects the integrand and the integration variable as strings:
integrate('expr', 'var', a, b) integrate('sin(2*z)', 'z', 0, %pi/2)
Nonlinear Equations
Solve the general (system of) equation(s) fct(x) = 0 with start vector x = x0
fsolve(x0, fct)
Examples:
Solve sin(x) = x/4 with different start values:
function y = fct1(x) y = sin(x) - .25*x; endfunction fplot2d([-5:.1:5], fct1) x0 = [-5:5]; fsolve(x0, fct1)
Solve x^2 + y^2 = 4, x*y = 1:
function v = fct2(u) v(1) = u(1)^2 + u(2)^2 - 4 v(2) = u(1)*u(2) - 1 endfunction fsolve([1 0], fct2) fsolve([0 -1], fct2) ...
Ordinary Differential Equations
Formulate the initial value problem as a (system of) first order equation(s) for the unknown (m-component) function u(t):
du/dt = fct(t,u) u(t0) = u0
and solve it with ode:
u = ode(u0, t0, times, fct) u0 initial values, an m-component column vector t0 initial time times time values for which the solution is to be computed, an n-component vector fct name of the function on the right hand side, with two arguments, a scalar and a vector
ode returns the solution as an (mxn) matrix u. Its ith column u(:,i) represents the solution u(t) at time t=times(i).
Simple example of first order (dy/dt = sin(y)/(1 + t^2), y(0) = 1):
function ydot = fct(t,y) ydot = sin(y)/(1 + t^2) endfunction times=[0:.1:10]; y = ode(1, 0, times, fct) clf; plot(times, y)
Example - damped harmonic oscillation (x'' + r x' + x = 0, x(0) = 1, x'(0) = 0):
function v = fct(t,u) v(1) = u(2) v(2) = -.2*u(2) - u(1) endfunction u0 = [1; 0]; times = [0:.1:20]; u = ode(u0, 0, times, fct); clf; plot(times, u(1,:))
Graphics - Matlab Style
Clear graphics
Plot commands are cumulative by default. To start a new graph, use
clf()
2D plots
Both functions and parametric curves are drawn as polygons, based on two (equal size) vectors of coordinates. In this way, curves and/or sets of points are plotted with the same command:
plot(x, y) plot(x, y, 'spec') spec is a string, combining symbols for colors: r g b c m y k w line styles: - -- : -. points: + o * . x s d ^ v > <
Examples:
x = [-3:.3:3]; y = x.^3 - 3*x; clf plot(x, y) plot(x, y, 'go') phi = [0:.1:10]; clf; plot(cos(phi), sin(1.1*phi), 'r-d')
Add error bars:
errbar(x, y, em, ep) add vertical bar from (y-em) to (y+ep) x = rand(1,5); y = rand(x); dy = .2*y; clf; plot(x, y, 'ro') errbar(x, y, dy, dy)
Multiple plots
subplot(m, n, p)
breaks the graphics window into an (m x n) matrix of sub-windows and selects the pth for plotting (counting row-wise).
3D plots
Plot a function over a 2D rectangular grid, defined by coordinate vectors x and y. The corresponding function values are stored in a matrix Z(k,l) = function(x(k), y(l)).
x = [-2:.1:2]; y = [-3:.1:3]; Z = (8*x.^2 - x.^4)' * (8*y.^2 - y.^4); clf; contour(x, y, Z, 5) contour plot clf; mesh(x, y, Z') mesh plot clf; surf(x, y, Z') colored surface plot clf; surf(x, y, Z', 'FaceColor', 'none') falls back to mesh plot clf; surf(x, y, Z', 'FaceColor', 'interp', 'EdgeColor', 'none') colored surface only
Note the transposition of Z in mesh(..) and surf(..) (Matlab style!).
Title and labels
Add or change title and axis labels with
title("text") xlabel("text") etc.
Isometric plot
isometric = same scale on the axes = preserve proportions
isoview(xmin, xmax, ymin, ymax) preserves coordinate frame square(xmin, ymin, xmax, ymax) changes frame to square square() automatic ranges
or in graphics window:
->Editor ->Figure properties ->Axes(1) ->Aspect Isoview: [x] on
Example - draw an ellipse with correct proportions:
phi = [0:.02:2]*%pi; clf; plot(cos(phi), 2*sin(phi)) square
Export graphics
EPS export, using the menus of the graphics window:
->File ->Export [x] Postscript [x] portrait
From the command line, Scilab Graphic(0) is exported with
xs2eps(0, 'filename.eps')
If the exported EPS fails to preserve the proportions of the plot, the following may be necessary to inforce a correct scaling:
fh = scf(0) set_posfig_dim(fh.figure_size(1),fh.figure_size(2)) xs2eps(0, 'filename.eps')
Scripts
Statements are written to a script file as typed in the command window. They are terminated by a newline, a comma or a semicolon (quiet mode).
Return from script (without closing the session):
abort
Trailing comments:
// comment
Run a script file:
exec('filename') exec('filename', 0) suppress echoing
Load (and compile) a function:
getf('filename')
Load all functions *.sci from a directory:
getd('directory')
Check function definition:
exists('function')
Run a script from the command line:
unix> scilab -f scriptfile
Run a script in batch mode:
unix> scilab -nwni -f scriptfile -e quit
Control Structures
if construct, simplest form:
if condition then statement(s), end
With (optional) elseif and else clauses:
if condition then statement(s) elseif condition then statement(s) ... else statement(s) end
for loop with a control variable, taking values in a list like n1:n2 or n1:step:n2 :
for var=list do statement(s), end for var=list do statement(s) end
while loop:
while condition then statement(s) end while condition do statement(s) end
There may be an optional else branch with statements to be performed on exit.
The keywords then and do
- have to be on the same line as their corresponding if, elseif, for, while ;
- may be replaced by a comma or a newline;
- are not supported by Matlab.
I/O
z = input('prompt') prompt for interactive input disp(var) simple numerical output disp(str) simple text output disp('result = '+string(%pi)) example with string handling printf('fmt', var1, ..) output with C-style formatting write('filename', A) write Matrix A into file A = read('filename', m, n) read file into (mxn)-Matrix A (m = -1 => automatic mode) fprintfMat('filename', A) write matrix A into file A = fscanfMat('filename') read numerical data into a matrix - ignore leading text lines - last line must be terminated
Directories
pwd chdir('newdir') don't use $HOME, ~ etc cd newdir same; don't use $HOME; ~ works dir ls
Appendix
Startup scripts
Upon startup, Scilab processes startup scripts as follows:
- system-wide startup file scilab.star in Scilab's installation directory, see Scilab variable SCI;
- per-user startup file .scilab or scilab.ini (if any) within the user's HOME directory, see SCIHOME;
- initialisation file .scilab or scilab.ini (if any) in the current directory where Scilab is started (if different from $HOME, see Scilab variables PWD and home).
Stacksize
Stacksizes are given in double precision words.
stacksize() current stack (total and used) for local variables gstacksize() same for global variables stacksize(n) set new stacksize limit for local variables gstacksize(n) same for global variables
Local stacksize is 5 MiWords by default (see system startup file scilab.star) and may be increased up to 2^27 = 1.342 x 10^8 MiWords = 1 GB (depending on system resources?).
Global stacksize is 11000 Words initially and will be increased automatically, as far as system resources allow.
Matlab vs. Scilab
-------------------------------------------------------------------- Matlab Scilab -------------------------------------------------------------------- Basics i %i 3 + 4i 3 + 4*%i format long format('v', 16) Matrices [1:5].^2 [1:5]^2 (dot isn't required) 1./[1:5] 1 ./[1:5] (space is required!) length(A) = max(size(A)) length(A) = prod(size(A)) sum(A) sum(A,'m') (first non-sing. dim.) eig(..) spec(..) Functions cot cotg mod(..) modulo(..) quad(..) etc intg(..), integrate(..) fzero(fct, x0) fsolve(x0, fct) ode45(..) etc ode(..) Graphics errorbar(..) errbar(..) axis equal square Scripts % // I/O disp(sprintf('pi = %f', pi)); printf('pi = %f\n', %pi) load(..) read(..) save ... write(..) --------------------------------------------------------------------
Graphics - Traditional Scilab Style
Clear xdel() window and data xbasc() graph and data xclear() graph only Set graphics style: xset() interactive mode xset("default") reset to defaults xset("use color",0) black+white xset("dashes",i) line type i=1..6 (i.le.1 => solid line) xset("use color",1) color mode (default) xset("dashes",i) color i=1..34 (i.le.1 => black) xset("mark",i,size) mark i=0..9, size=0..5 (i=0 => point) xset("thickness",i) line width i=0..19 (i=0 or 1 => one pixel) xset("font",i,size) font i=0..5, size=0..5 (i=1 => greek) 2D plot: plot(x,y) simple plot2d(x,y,style) with line style(s): dashes: 1..6 colors: 1..34 marks: 0..(-9) see xset() plot2d(x,y,style,"021") same plot2d(x,y,style,"041") same with equal units plot2d(x,y,style,"061") same with smart axes leg="text" legend(s), separated by `@' plot2d(x,y,style,"121",leg) with legend(s) for style(s) rect=[xmin ymin xmax ymax] plot2d(x,y,style,"011"," ",rect) with fixed boundaries plot2d(x,y,style,"031"," ",rect) same with equal units plot2d(x,y,style,"051"," ",rect) same with smart axes plot2d(x,y,style,"000") add to previous plot plot2d(x,y,strf="000") same xtitle("title","xax","yax") add title and x/y legends square() square frame (lost in PS?) xclip("clipgrf") clip at frame (needed?) xsetech(...) specify sub-window 2D vector plot ("quiver"): champ(x,y,fx,fy) (no need to transpose qx,qy!) champ(x,y,fx,fy,strf="041") same with equal units 3D meshplot of z(x,y): plot3d(x,y,z) x,y : vectors of length nx,ny z : matrix of size (nx,ny) plot3d(x,y,z,35,45," ",[34 2 4]) same with white facets ^^ (.ge.17 for greyscale, 8 or .ge.34 for color) plot3d(x,y,z,35,45,"xtxt@ytxt@ztxt") same with legends ebox=[xmin xmax ymin ymax zmin zmax] same with fixed plot3d(x,y,z,35,45," ",[34 1 4],ebox) boundaries ^ ^^^^ theta=180./%pi * atan(Lx/Lz) correction for a box plot3d(x,y,z,35,theta," ",[34 2 4]) of size (Lx,Lx,Lz) phi=180/%pi * atan(.7*Ly/Lx) theta=180/%pi * atan(.7*sqrt(Lx^2+Ly^2)/Lz) correction for plot3d(x,y,z,phi,theta," ",[34 2 4]) box (Lx,Ly,Lz) Add text: xtitle("title", "xtext", "ytext", "ztext") Add a polygon: better use plot2d... xpoly(x,y,"lines") polygon line xpoly(x,y,"marks") point(s)
TO DO
...
Burkhard Bunk, 08.03.2015