2012-09-03

Scilab

Find out all about Scilab at the Scilab website. This is just for me for starters. Scilab is a free environment for numerical computations that is very similar to the commercial MATLAB, although there are some differences.

Useful Functions

For the full monty, look at the online doc!
Interactive: disp who whos help apropos disp
I/O: exec mopen mclose mgetl fscanf fprintf error warning
Cave:getl cuts lines after 4096 chars.
Libraries: genlib
Graphics: xinit xend xset xgrid xtitle/titlepage xstring/xstringl xclear/xbasc hotcolormap plot2d contour2d grayplot plot3d plot3d1 geom3d matplot locate driver
Strings: length xegrep strcat strindex stripblanks strsubst tokens part evstr execstr
Statistics: correl/covar geomean ftest mean/median center regress variance functions size typeof union intersect isdef exists contr
Elementary math: log cos sin diag max/min prod round/int/floor/ceil sign sqrt sum rand fft
Sorting: gsort sort empty eye matrix ones zeros expm trianfml
Linear algebra: inv bdiag spec schur syslin xdscr ss2tf
Polynomials: coeff freq horner poly roots
Spline: interp interpln
ODE Solvers: dassl odedc
Optimisation: optim quapro linpro lmitool

Environment

scilab.star contains the general init file for loading default libs etc
.sclilab in your home dir can contain further initialisation code

Interactive

^-C               // pause
...               // line continues on next
;                 // separate commands in line ...
                  // and supress output if at end
[return]          // eval and print 
who               // list vars
whos()            // more detailed
help              // online help
help('fname')     // ... about function fname
apropos('name')   // help on anything named like name
resume            // resume after pause
pause             // new env inheriting vars; return vars with return
unix_s('cmds')    // execute cmds in unix shell
unix_w('cmds')    // execute cmds in unix shell, write output to window
write('name', x)  // write object x to file
clear             // clear env
clear('name')     // clear var name
lib               // load lib
disp(name)        // show functions in lib, call syntax for func
link('file.o', 'name', 'C') // link in external C code
call()            // call linked code

xset()            // panel to mod display settings

save('name')      // save vars/env to binary file
load('name')      // save vars/env from binary file
write('fname', o) // write o to file fname 
read('fname',2,3) // read part of matrux stored in fname
mopen('fname','w')// open handle to filr fname for write
mfprintf(fd, 'format', o) // printf to filehandle fh
x=mfscanf(fd, 'format')   // scanf from filehandle fh
mclose(fd)        // close file handle

deff('[x]=fact(n)', 'if n==0 then x=1, else x=n*fact(n-1), end') //function def

Scope

All variables not defined in a function are considered global. Functions are objects that can be given as args to other functions.

Literals

Scalars are constants, booleans, polynomials and their quotients and strings.
They can be used as elements in matrices.

'Hi' or "World"    // String
%t                 // true
%f                 // false
%pi                // Pi
%e                 // Euler's
%i                 // sqrt(-1) 
%s                 // poly(0,'s'), polynomial p(s) w/ var s, roots(s) = 0
%eps               // biggest number on machine           
%inf               // infinity
%nan               // Not a Number
[]                 // empty matrix, zero rows, cols
%io(2)             // scilab window output file handle
SCI                // path to scilab main directory

Syntax

Operators:
// comment
a = 7              // Assignment/Initialisation
[1,2,3]            // row vector
[1;2;3]            // col vector
M'                 // transpose (or complex conjugate) row <=> col 
0:0.1:1            // vector from 0 to 1 (inclusive) in 0.1 steps
-(1:4)             // vector from -1 to -4 in 1.0 steps

*                  // scalar product
+                  // element-wise addition, string concatenation
-                  // element-wise substraction
/                  // right division
\                  // left division
^                  // exponent
.*                 // element-wise multiplication
./                 // element-wise division
.^                 // element-wise exponent
.*.                // kronecker product
==                 // equals
<>                 // not equal
< > <= >=          // smaller, greater, smaller or equal, greater or equal
~                  // not
&                  // and
|                  // or

Lists: elements can be mixed, lists, even matrices can be elements
l = list('this',3,m,-(1:3))   // list. elems may be scalars, matrices, lists
tl = tlist(['mylist','color',value], 'red', 3) //typed list aka hash
l(3)(2)            // dereferencing a subentry in list
tl('color')        // dereferencing a hash

Matrices: all elements should have same type
M = [a+1 2 3
       0 0 atan(1)
       5 9 -1]     // constant matrix
M = [p,1-z;
     1,z*p]        // polynomal matrix
M = ['Hi','World';
     'Whats','Up?']// string matrix
M2 = matrix(M,2,3) // create matrix x with elements of M and given dims
M(2,3)             // element in row 2 column 3
M(1,:)             // extracting the first row
M(:,$)             // extracting the last column
I=(1:3);M(I,:)     // extracting the first three rows

Hypermatrices: more than 2 dimensions
M = hypermat([2,3,2],1:12) // filled 3-dimensional matrix
M(2,2,2)           // corner of hyper matrix
M.dims             // dimensions of hyper matrix
M.entries          // entries of hyper matrix


Functions:
exec('filename',-1)   // load functions from file, -1 makes that it isnt echoed
y = poly(0,'z')    // function call vor variable z
function [r1,...,rn]=name(p1,...,pn) //has to be 1st line in file
   ...
endfunction
argn      // return number of input/output arguments
error     // print error and exit function
warning
pause
return   // return to calling env
resume   // ...and pass on local vars

Control structures:
for elem=vector/matrix/list, body, end
while condition, body, end
break // exits from innermost loop
if condition then, if-body, else, else-body, end
select var, case cond, case-body, case cond2, case-body2,...[,else, catchall-body],end