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
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.
+ - * /
^ ** (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, ..
letters (case sensitive)
digits (digit not as 1st character)
special characters % _ # ! $ ? (percent as 1st character only)
%pi %i %e
%eps %inf %nan
%t %T %f %F
%s ???
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
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
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.
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.
'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.
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
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
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)
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
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
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)
fsolve(x0, fct)
Examples:
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)
...
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,:))
clf()
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)
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).
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("text")
xlabel("text") etc.
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
->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')
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
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
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
pwd
chdir('newdir') don't use $HOME, ~ etc
cd newdir same; don't use $HOME; ~ works
dir
ls
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?).
--------------------------------------------------------------------
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(..)
--------------------------------------------------------------------
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)
...