Index

Documentation de Scilab
Programmation
Librairie graphique
Fonctions élémentaires
Entrées-sorties
Manipulation des fonctions et des librairies
Manipulations de chaînes de caractères
IHM et Dialogues
Utilitaires
Algèbre linéaire
Calculs sur les polynômes
Contrôle et théorie des systèmes
Contrôle robuste
Optimisation et simulation
Traitement du signal
Modélisation et simulation ARMA
Metanet : graphes et réseaux
Manipulation de fichiers sons
Génération de code, traduction de données
TdCs
Statistiques
Fonctions de distributions statistiques
Identification
Aide à la conversion Matlab vers Scilab
Solveurs creux
Calcul parallèle avec PVM
Interface TCL/Tk
Interface Java


Programmation
abort - interruption d'une évaluation
ans - réponse (answer)
backslash (\) - division matricielle à gauche
bool2s - convertit une matrice booléenne en une matrice 0-1
boolean - Objets Scilab, variables booléennes et opérateurs & | ~
brackets ([,]) - crochets à droite et à gauche
break - interruption d'une boucle
call - Fortran or C user routines call
case - mot-clé utilisé dans une structure select ... case
clear - suppression de variables
clearglobal - supprime des variables globales
colon (:) - opérateur "deux points"
comma (,) - virgule, séparateur d'instructions ou d'arguments
comments - commentaires
comparison - comparison, relational operators
continue - keyword to pass control to the next iteration of a loop
date - date courante sous forme d'une chaîne de caractères
debug - niveau de déboggage
definedfields - return index of list's defined fields
do - language keyword for loops
dot (.) - point
else - mot clé dans une structure if-then-else
elseif - mot clé dans une structure if-then-else
empty ([]) - matrice vide
end - mot-clé end
equal - (=) affectation, comparison equal sign
errcatch - interception d'erreur
errclear - "effacement" d'une erreur
error - envoi de message d'erreur
error_table - table of error messages
etime - Temps écoulé
evstr - évaluation d'une expression
exec - exécution d'un script (fichier de commandes)
execstr - exécution d'instructions Scilab contenues dans des chaînes de caractères
exists - teste l'existence d'une variable
exit - termine la session Scilab courante
external - Objet Scilab, fonction externe ou routine
extraction - extraction à partir d'une matrice ou d'une liste
feval - évaluation multiple d'une fonction
find - find indices of boolean vector or matrix true elements
for - mot clé pour les structures de boucles
format - number printing and display format
fort - Fortran or C user routines call
funptr - coding of primitives ( wizard stuff )
getdate - renvoie la date et l'heure
getenv - renvoie la valeur d'une variable d'environnement
getfield - extraction d'un champ d'une liste
getpid - renvoie le numéro de processus de Scilab
getversion - get Scilab version name
global - définition de variables globales
gstacksize - obtenir ou changer la taille de la pile des variables globales
hat (^) - élévation à la puissance
host - exécution d'une commande Unix ou DOS
hypermat - initialisation d'une matrice à N dimensions
hypermatrices - Objet Scilab, matrices à N dimensions
iconvert - conversion au codage entier à 1,2 ou 4 octets
ieee - détermine le mode d'exception IEEE pour les calculs
if then else - exécution conditionnelle
affectation - affectation partielle d'une variable
insertion - insertion/modification dans une variable
intppty - set interface argument passing properties
inttype - type des entiers utilisés dans les types entiers de données.
inv_coeff - construction d'une matrice polynomiale à partir des coefficients
iserror - test d'occurrence d'une erreur
isglobal - vérifie si une variable est globale
lasterror - get last recorded error message
left ([) - crochet gauche
great - (<) greater than comparison
less - (<) lower than comparison
list - Objet Scilab, Définition d'une liste
lsslist - Définition d'un système dynamique linéaire
lstcat - concaténation de listes
matrices - Objet Scilab, matrices
matrix - remise en forme d'une matrice
mlist - Objet Scilab, définition d'une liste typée
mode - choisit le mode d'exécution des scripts et des fonctions
mtlb_mode - choisit le mode de compatibilité Matlab
names - syntaxe des noms de variables dans Scilab
null - suppression d'un terme d'une liste
overloading - display, functions and operators overloading capabilities
parents ( ) - parenthèses droite et gauche
pause - mode de pause, attente clavier
percent (%) - caractère spécial
plus (+) - opérateur d'addition
poly - définition d'un polynôme
power - élévation à la puissance (^,.^)
predef - protection de variables
getcwd - renvoie le répertoire courant de Scilab
pwd - affiche le répertoire courant de Scilab
quit - décrémente le niveau de pause ou quitte Scilab
quote (') - opérateur de transposition, délimiteur de chaîne de caractères
rational - Objet Scilab, fraction rationnelle
resume - sortie d'une fonction ou reprise d'exécution, avec récupération de variables locales
return - sortie d'une fonction ou reprise d'exécution, avec récupération de variables locales
rlist - définition d'une fraction rationnelle
sciargs - arguments sur la ligne de commande Scilab
select - mot-clé utilisé dans une structure select ... case
semi (;) - séparateur de lignes ou d'instructions Scilab
semicolon (;) - séparateur de lignes ou d'instructions Scilab
setenv - fixe la valeur d'une variable d'environnement
setfield - insertion dans un champ d'une liste
slash (/) - division à droite et feedback
stacksize - change la taille de la pile Scilab
star (*) - opérateur de multiplication
symbols - noms des opérateurs dans l'aide de Scilab
testmatrix - génération de matrices remarquables
then - mot-clé dans une structure if-then-else
tic - Démarre le chronomètre
tilda (~) - négation logique
tlist - Objet Scilab. Définition d'une liste typée
toc - Lit le chronomètre
catch - mot clé de début du block catch dans une instruction de contrôle try-catch
try - mot clé de début du block try dans une instruction de contrôle try-catch
type - type d'une variable
typename - associe un nom à un type de variable
user - interfaçage d'une routine Fortran ou C
varn - indéterminée d'un polynôme
what - liste des primitives Scilab
where - donne l'arborescence d'appel courante
whereami - donne l'arborescence d'appel de l'instruction courante
whereis - nom de la librairie contenant une fonction
while - mot-clé utilisé dans une structure while ... end
who - liste des variables
who_user - listing of user's variables
whos - liste des variables courantes dans un format détaillé


abort

Scilab Function
Last update : 16/06/2004

abort - interruption d'une évaluation

Description

abort interrompt l'évaluation courante et affiche l'invite de commande. Dans un niveau de pause , la commande abort renvoie à l'invite de commande de niveau 0.

See Also

quit , pause , break ,


ans

Scilab Function
Last update : 16/06/2004

ans - réponse (answer)

Description

ans signifie réponse (answer). La variable ans est créée automatiquement quand des expressions ne sont pas affectées à une variable. ans contient la dernière expression non affectée.


backslash (\)

Scilab Function
Last update : 29/12/2005

backslash (\) - division matricielle à gauche

Calling Sequence

x=A\b

Description

L'anti-slash représente la division matricielle à gauche. x=A\b est une solution de A*x=b .

Si A est carrée et régulière x=A\b (unique) est équivalent mathématiquement à x=inv(A)*b (dont le calcul est par contre beaucoup plus coûteux).

Si A n'est pas carrée, x est une solution au sens des moindres carrés, c'est à dire que norm(A*x-b) est minimale (norme euclidienne). Si A est de rang maximal (colonnes linéairement indépendantes), la solution au sens des moindres carrés, x=A\b , est unique (le vecteur x minimisant norm(A*x-b) est unique). Si A n'est pas de rang maximal, cette solution n'est pas unique, et x=A\b , en général, n'est pas la solution de norme minimale (la solution de norme minimale est x=pinv(A)*b ).

A.\B est la matrice dont le terme (i,j) est égal à A(i,j)\B(i,j) . Si A (ou B ) est un scalaire A.\B est équivalent à A*ones(B).\B (or A.\(B*ones(A))

A\.B est un opérateur dont la signification n'est pas prédéfinie. il peut être utilisé pour définir de nouveaux opérateurs (voir "overloading") avec la même priorité que * ou /.

Examples

A=rand(3,2);b=[1;1;1]; x=A\b; y=pinv(A)*b;  x-y
A=rand(2,3);b=[1;1]; x=A\b; y=pinv(A)*b; x-y, A*x-b, A*y-b
A=rand(3,1)*rand(1,2); b=[1;1;1]; x=A\b; y=pinv(A)*b; A*x-b, A*y-b
A=rand(2,1)*rand(1,3); b=[1;1]; x=A\b; y=pinv(A)*b; A*x-b, A*y-b

See Also

slash , inv , pinv , percent , ieee ,


bool2s

Scilab Function
Last update : 16/06/2004

bool2s - convertit une matrice booléenne en une matrice 0-1

Calling Sequence

bool2s(x)

Parameters

  • x : matrice réelle, complexe ou booléenne

Description

Si x est une matrice booléenne, bool2s(x) renvoie une matrice où les valeurs %T (true=vrai) sont remplacées par des 1 et les %F (faux) par des 0.

Si x n'est pas une matrice booléenne, bool2s(x) renvoie une matrice où les valeurs non-nulles sont remplacées par des 1.

Examples

bool2s([%t %t %f %t])
bool2s([2.3 0 10 -1])

See Also

boolean , find ,


boolean

Scilab Objects
Last update : 16/06/2004

boolean - Objets Scilab, variables booléennes et opérateurs & | ~

Description

Une variable booléenne est %T (pour "vrai"="true") ou %F (pour "faux"). Ces variables permettent de définir des matrices de booléens avec la syntaxe habituelle. Ces matrices booléennes peuvent être manipulées comme des matrices ordinaires pour les opérations d'extraction/insertion et de concaténation. Notez que les autres opérations usuelles ( +, *, -, ^, etc.) ne sont pas définies pour les matrices booléennes. Les seuls opérateurs valides sont les suivants :

~b : est la négation logique élément par élément de la matrice booléenne b .
b1&b2 : est la conjonction (et) logique élément par élément de b1 et b2 (matrices).
b1|b2 : est la disjonction (ou) logique élément par élément de b1 et b2 (matrices).
Les variables booléennes peuvent être utilisées comme indice pour les matrices et les vecteurs. Par exemple a([%T,%F,%T],:) renvoie la sous-matrice composée des lignes 1 et 3 de a . Les matrices booléennes peuvent être creuses.

Examples

[1,2]==[1,3]
[1,2]==1
a=1:5; a(a>2)

See Also

matrices , or , and , not ,


brackets ([,])

Scilab Function
Last update : 16/06/2004

brackets ([,]) - crochets à droite et à gauche

Calling Sequence

[a11,a12,...;a21,a22,...;...]
[s1,s2,...]=func(...)

Parameters

  • a11,a12,... : toute matrice (réelle, complexe, polynomiale, rationnelle, liste de type syslin ...) de dimensions adéquates
  • s1,s2,... : noms de variables

Description

Les crochets droit et gauche sont utilisés pour effectuer une concaténation de matrices. Ces symboles sont aussi utilisés quand on effectue un appel à une fonction renvoyant plusieurs arguments.

A l'intérieur d'une paire de crochets spécifiant une concaténation, un espace ou une virgule signifient une concaténation de colonnes, alors qu'un point-virgule ou un passage à la ligne signifient une concaténation de lignes.

Note : pour éviter les confusions il est plus sûr d'utiliser des virgules pour concaténer des colonnes.

Pour des crochets entourant une liste d'arguments de sortie d'une fonction, les noms de variables doivent être séparés par des virgules.

Examples

[6.9,9.64; sqrt(-1) 0]
[1 +%i  2 -%i  3]
[]
['ceci est';'un vecteur';'de chaines de caracteres']
s=poly(0,'s');[1/s,2/s]
[tf2ss(1/s),tf2ss(2/s)]

[u,s]=schur(rand(3,3))

See Also

comma , semicolon ,


break

Scilab Function
Last update : 16/06/2004

break - interruption d'une boucle

Description

A l'intérieur d'une boucle for ou while , la commande break force la boucle à se terminer.

Examples

k=0; while 1==1, k=k+1; if k > 100 then  break,end; end

See Also

while , if , for , abort , return ,


call

Scilab Function
Last update : 25/05/2005

call - Fortran or C user routines call

Calling Sequence

// long form 'out' is present
[y1,...,yk]=call("ident",x1,px1,"tx1",...,xn,pxn,"txn",
"out",[ny1,my1],py1,"ty1",...,[nyl,myl],pyl,"tyl")
// short form : no 'out' parameter
[y1,....,yk]=call("ident",x1,...,xn)

Parameters

  • "ident" : string.
  • xi : real matrix or string
  • pxi, pyi : integers
  • txi, tyi : character string "d" , "r" , "i" or "c" .

Description

Interactive call of Fortran (or C) user program from Scilab. The routine must be previously linked with Scilab. This link may be done:

-with Scilab " link " command (incremental "soft" linking) during the Scilab session.(see link )
-by "hard" re-linking. Writing the routine call within Scilab routine default/Ex-fort.f , adding the entry point in the file default/Flist and then re_linking Scilab with the command make bin/scilex in main Scilab directory.

There are two forms of calling syntax, a short one and a long one. The short one will give faster code and an easier calling syntax but one has to write a small (C or Fortran) interface in order to make the short form possible. The long one make it possible to call a Fortran routine (or a C one) whitout modification of the code but the syntax is more complex and the interpreted code slower.

The meaning of each parameter is described now:

"ident"is the name of the called subroutine.
x1,...,xnare input variables (real matrices or strings) sent to the routine,
px1,...,pxnare the respective positions of these variables in the calling sequence of the routine "ident" and
tx1,...,txnare their types ( "r" , "i" , "d" and "c" for real (float) , integer, double precision and strings)
"out"is a keyword used to separate input variables from output variables. when this key word is present it is assumes that the long form will be used and when it is not prsent, the short form is used.
[ny1, my1]are the size ( # of rows and columns. For 'c' arguments, m1*n1 is the number of charaters ) of output variables and
py1, ...are the positions of output variables (possibly equal to pxi ) in the calling sequence of the routine. The pyi 's integers must be in increasing order.
"ty1", ...are the Fortran types of output variables. The k first output variables are put in y1,..., yk .

If an output variable coincides with an input variable (i.e. pyi=pxj ) one can pass only its position pyi . The size and type of yi are then the same as those of xi . If an output variable coincides with an input variable and one specify the dimensions of the output variable [myl,nyl] must follow the compatibility condition mxk*nxk >= myl*nyl .

In the case of short syntax , [y1,....,yk]=call("ident",x1,...,xn) , the input parameters xi 's and the name "ident" are sent to the interface routine Ex-fort . This interface routine is then very similar to an interface (see the source code in the directory SCIDIR/default/Ex-fort.f ).

Examples

    //Example 1 with  a simple C code
    f1=['#include <math.h>'
        'void fooc(c,a,b,m,n)'
         'double a[],*b,c[];'
         'int *m,*n;'
         '{'
         '   int i;'
         '   for ( i =0 ; i < (*m)*(*n) ; i++) '
         '     c[i] = sin(a[i]) + *b; '
         '}'];

    mputl(f1,'fooc.c')

    //creating the shared library (a gateway, a Makefile and a loader are
    //generated.

    ilib_for_link('fooc','fooc.o',[],"c")

    // load the shared library

    exec loader.sce

    //using the new primitive
    a=[1,2,3;4,5,6];b= %pi;
    [m,n]=size(a);

    // Inputs:
    // a is in position 2 and double
    // b                3     double
    // n                4     integer
    // m                5     integer
    // Outputs:
    // c is in position 1 and double with size [m,n]
    c=call("fooc",a,2,"d",b,3,"d",m,4,"i",n,5,"i","out",[m,n],1,"d");

    //Example 2 with  a simple Fortran code
    f1=['      subroutine foof(c,a,b,n,m)'
        '      integer n,m'
        '      double precision a(*),b,c(*)'
        '      do 10 i=1,m*n '
        '        c(i) = sin(a(i))+b'
        '   10 continue'
        '      end'];
    mputl(f1,'foof.f')

    //creating the shared library (a gateway, a Makefile and a loader are
    //generated.

    ilib_for_link('foof','foof.o',[],"f")

    // load the shared library

    exec loader.sce

    //using the new primitive
    a=[1,2,3;4,5,6];b= %pi;
    [m,n]=size(a);
    c=call("foof",a,2,"d",b,3,"d",m,4,"i",n,5,"i","out",[m,n],1,"d");

See Also

link , c_link , intersci , addinter ,


case

Scilab Function
Last update : 16/06/2004

case - mot-clé utilisé dans une structure select ... case

Description

Mot-clé utilisé dans une structure select ... case , à utiliser de la façon suivante :

select expr0,
 case expr1 then instructions1,
 case expr2 then instructions2,
 ...
 case exprn then instructions,
 [else instructions],
end

See Also

select , while , end , for ,


clearglobal

Scilab Function
Last update : 16/06/2004

clearglobal - supprime des variables globales

Calling Sequence

clearglobal()
clearglobal nam1 .. namn
clearglobal('nam1', ..,'namn')

Parameters

  • nam1,..., namn : noms valides de variables

Description

clearglobal() supprime toutes les variables globales.

clearglobal nam1 .. namn supprime les variables globales dont les noms sont spécifiés.

Notez que clearglobal() détruit seulement les variables globales, les copies locales de ces variables sont conservées.

Examples

global a b c
a=1;b=2;c=3;
who('global')
clearglobal b
who('global')

See Also

global , who ,


clear

Scilab Function
Last update : 16/06/2004

clear - suppression de variables

Calling Sequence

clear a

Description

Cette commande supprime des variables non-protégées. Elle supprime de l'environnement les variables dont les noms sont spécifiés. Sans argument clear supprime toutes les variables sauf celles qui ont été protégées par predef . La succession des commandes predef(0) et clear supprime toutes les variables.

Habituellement, les variables protégées sont les librairies standard et les variables dont le nom commence par le caractère "%".

Notez la syntaxe particulière : clear a et non clear(a) . Notez aussi que a=[] ne supprime pas a mais affecte à a une matrice vide.

See Also

predef , who ,


colon (:)

Scilab Function
Last update : 17/06/2004

colon (:) - opérateur "deux points"

Description

Le symbole : peut être utilisé pour former des vecteurs (voir aussi linspace , logspace ).

j:k est le vecteur [j, j+1,...,k] (ou la matrice vide si j>k ).
j:d:k est le vecteur [j, j+d, ..., j+m*d]
Cet opérateur peut aussi être utilisé pour sélectionner des lignes ou des colonnes d'une matrice, ou bien des sous-matrices (voir aussi extraction , insertion ).
A(:) est le vecteur de tous les éléments de la matrice A , considérée comme un vecteur colonne (les colonnes sont mises bout à bout).
A(:,j) est la j -ème colonne de A
A(j:k) est égal à [A(j),A(j+1),...,A(k)]
A(:,j:k) est égal à [A(:,j),A(:,j+1),...,A(:,k)]
A(:)=w remplit la matrice A avec les composantes de w (prises colonne par colonne si w est une matrice).

See Also

matrix ,


comma (,)

Scilab Function
Last update : 16/06/2004

comma (,) - virgule, séparateur d'instructions ou d'arguments

Description

Les virgules sont utilisées pour séparer les arguments dans les appels de fonctions, pour séparer les termes des vecteurs lignes ou pour spécifier une concaténation de colonnes.

Pour les vecteurs lignes et pour la concaténation de colonnes les espaces peuvent remplacer les virgules, mais il est préférable d'utiliser des virgules.

Les virgules peuvent aussi être utilisées pour séparer des instructions Scilab. (on utilise ; pour que le résultat des expressions ne soit pas affiché).

Examples

a=[1,2,3;4,5,6];
a=1,b=1;c=2

See Also

semi , brackets ,


comments

Scilab Function
Last update : 04/10/2005

comments - commentaires

Description

Les lignes de commandes commençant par // ne sont pas interprétées par Scilab.


comparison

Scilab operator
Last update : 13/06/2006

comparison - comparison, relational operators

Calling Sequence

a==b
a~=b or a<>b
a<b
a<=b
a>b
a>=b

Parameters

  • a : any type of variable for a==b , a~=b a<>b equality comparisons and restricted to real floating point and integer array for order related comparisons a<b , a<=b , a>b , a>=b .
  • b : any type of variable for a==b , a~=b a< > b equality comparisons and restricted to real floating point and integer arrays for order related comparisons a<b , a<=b , a>b , a>=b .

Description

Two classes of operators have to be distinguished:

The equality and inequality comparisons: a==b , a~=b (or equivalently a<>b ). These operators apply to any type of operands.
The order related comparisons: a<b , a<=b , a>b , a>=b . These operators apply only to real floating point and integer arrays.

The semantics of the comparison operators also depend on the operands types:

With array variables like floating point and integer arrays, logical arrays, string arrays, polynomial and rationnal arrays, handle arrays, lists... the following rules apply:
If a and b evaluates as arrays with same types and identical dimensions, the comparison is performed element by element and the result is an array of booleans of the same.
If a and b evaluates as arrays with same types, but a or b is a 1 by 1 array the scalar is compared with each element of the other array. The result is an array of booleans of the size of the non scalar operand.
In the others cases the result is the boolean %f
If the operand data types are differents but "compatible" like floating points and integers a type conversion is performed before the comparison.
With other type of operands like function , libraries , the result is %t if the objects are identical and %f in the other cases.

Equality comparison between operands of incompatible data types returns %f .

Examples

    //element wise comparisons
    (1:5)==3
    (1:5)<=4
    (1:5)<=[1 4 2 3 0]
    1<[]
    list(1,2,3)~=list(1,3,3)

    //object wise comparisons
    (1:10)==[4,3]
    'foo'==3
    1==[]
    list(1,2,3)==1

    isequal(list(1,2,3),1)
    isequal(1:10,1)

    //comparison with type conversion
    int32(1)==1
    int32(1)<1.5
    int32(1:5)<int8(3)
    p=poly(0,'s','c')
    p==0
    p/poly(1,'s','c')==0

See Also

less , boolean , isequal ,


continue

Scilab Function
Last update : 12/01/2004

continue - keyword to pass control to the next iteration of a loop

Description

Inside a for or while loop, the command continue passes control to the next iteration of the loop in which it appears, skipping any remaining statements between this instruction and the loop's end instruction.

Examples

  for k=1:10,K=k;if k>2&k<=8 then continue,disp('hello'),end,k,end

  for j=1:2
    x=[];
    for k=1:10,if k>j+1&k<=8 then continue,end,x=[x,k];end
    x
  end

See Also

while , for , break , return ,

Author

Serge Steer, INRIA


date

Scilab Function
Last update : 02/04/2006

date - date courante sous forme d'une chaîne de caractères

Calling Sequence

dt=date()

Parameters

  • dt : chaîne de caractères

Description

dt=date() renvoie une chaîne de caractères contenant la date au format jj-mmm-aaaaa.

Examples

date()

See Also

getdate , timer ,


debug

Scilab Function
Last update : 16/06/2004

debug - niveau de déboggage

Calling Sequence

debug(level-int)
level-int=debug()

Parameters

  • level-int : entier (entre 0 et 4)

Description

Pour les valeurs 0,1,2,3,4 de level-int , debug définit différents niveaux de déboggage (pour les experts de Scilab !).


definedfields

Scilab Function
Last update : 12/01/2004

definedfields - return index of list's defined fields

Calling Sequence

k=definedfields(l)

Parameters

  • l : a list , tlist or mlist variable.
  • k : a vector of index.

Description

If l is a list tlist mlist k=definedfields(l) returns in k the indices of the defined list fields. This function is useful because indexing undefined fields produces an error.

Examples

l=list(1);l(3)=5
k=definedfields(l)

t=tlist('x');t(5)=4
definedfields(t)

m=mlist(['m','a','b']);m.b='sdfgfgd'
definedfields(m)

See Also

list , tlist , mlist , insertion , extraction ,


dot (.)

Scilab Symbol
Last update : 16/06/2004

dot (.) - point

Calling Sequence

123.33
a.*b
[123,..
456]

Description

. Le point est utilisé dans la notation décimale : 3.25 et 0.001
.<op> Il est aussi utilisé en conjonction avec d'autres opérateurs (* / \ ^ ') pour en former de nouveaux. Les opérations multiplicatives "élément par élément" sont obtenues avec .* , .^ , ./ , .\ ou .'. Par exemple, C = A ./ B est la matrice dont les éléments sont c(i,j) = a(i,j)/b(i,j). Le produit de Kronecker est noté .*. . Notez que lorsqu'un point suit un nombre entier il est considéré comme en faisant partie. Ainsi 2.*x est évalué comme 2.0*x et 2 .*x est évalué comme (2).*x
.. A suivre. Deux points ou plus à la fin d'une ligne font en sorte que la ligne suivante est considérée comme en étant la suite (le passage à la ligne n'est pas pris en compte).

Examples

1.345
x=[1 2 3];x.^2 .*x // il faut absolument mettre un espace entre le 2 et le point
[123,..
 456]

See Also

star , hat , slash , backslash ,


do

Scilab Keyword
Last update : 14/12/2005

do - language keyword for loops

Description

Le mot clé M do peut être utilisé dans une instruction for ou while pour séparer la définition de la variable de boucle de l'ensemble des instructions.

See Also

for , while ,


elseif

Scilab Function
Last update : 16/06/2004

elseif - mot clé dans une structure if-then-else

Description

Voir if,then,else .


else

Scilab Function
Last update : 16/06/2004

else - mot clé dans une structure if-then-else

Description

Utilisé avec if .

See Also

if ,


empty ([])

Scilab Function
Last update : 16/06/2004

empty ([]) - matrice vide

Description

[] désigne une matrice vide. Elle est définie de façon unique et possède 0 lignes et 0 colonnes, soit size([]) =[0,0] . Les convention suivantes sont adoptées :

[] * A = A * [] = []

[] + A = A + [] = A

[ [], A] = [A, []] = A inv([]) =[]

det([])=cond([])=rcond([])=1, rank([])=0

Les fonctions matricielles renvoient [] ou un message d'erreur quand il n'y pas de réponse évidente. Les systèmes dynamiques linéaires (listes de type syslin ) peuvent avoir plusieurs lignes ou colonnes.

Examples

s=poly(0,'s'); A = [s, s+1];
A+[], A*[]
A=rand(2,2); AA=A([],1), size(AA)
svd([])
w=ssrand(2,2,2); wr=[]*w; size(wr), w1=ss2tf(wr), size(w1)

See Also

matrices , poly , string , boolean , rational , syslin ,


end

Scilab Function
Last update : 16/06/2004

end - mot-clé end

Description

Utilisé à la fin des boucles ou des structures conditionnelles. Les structures for, while, if, select doivent être terminées par end .

See Also

for , while , if , select ,


equal

Scilab Function
Last update : 12/01/2004

equal - (=) affectation, comparison equal sign

Description

-Equal sign is used to denote a value affectation to a variable.
- a == b denotes equality comparison between expressions a and b :
Withmatrix objects,
If a and b are matrices with same types and identical dimensions, the comparison is performed element by element and the result is a matrix of booleans.
If a and b are matrices with same types, but a or b is a 1 by 1 matrix the scalar is compared with each element of the matrix. The result is a matrix of booleans.
InThe others cases the result is the boolean %f
Withlist objects,
If a and b are lists with identical sizes, the comparison is performed element by element and and recursively. The result is a row vector of booleans.
If a and b are lists with non equal sizes the result is the boolean %f .
Withtlist and mlist object. If no overloading function is defined the list comparison method is used.
Withother data types (functions, libraries,...) , the result is %t if the objects are identical and %f in the other case.

Comparison between different data types returns %f .

Examples

a=sin(3.2)
[u,s]=schur(rand(3,3))
[1:10]==4
1~=2

See Also

less , boolean , isequal ,


errcatch

Scilab Function
Last update : 30/08/2005

errcatch - interception d'erreur

Calling Sequence

errcatch(n [,'action'] [,'option'])
errcatch()

Parameters

  • n : entier
  • action, option : chaînes de caractères

Description

errcatch définit une action à effectuer quand une erreur de numéro n est rencontrée. n a la signification suivante:

si n>0 , n est le numéro de l'erreur à intercepter

si n<0 , toutes les erreurs sont à intercepter

action est une des chaînes de caractères suivantes :

"pause" : l'interception de l'erreur conduit à une pause. Cette option est utile en phase de mise au point. On peut utiliser whereami() pour obtenir des informations sur le contexte courant.
"continue" : l'exécution de la fonction ou du script continue, l'instruction courante est tout simplement ignorée. Il est possible de vérifier si une erreur s'est produite avec la fonction iserror . Ne pas oublier d'effacer l'erreur avec la fonction errclear le plus tôt possible. Cette option est utile pour remédier aux erreurs. Dans la plupart des cas, l'usage de errcatch(n,"continue",..) peut être remplacé par l'usage de la fonction execstr .
"kill" : mode par défaut, tous les niveaux intermédiaires sont abandonnés, et Scilab revient à l'invite de commande de niveau 0.
"stop" : interrompt la session Scilab courante (très utile quand Scilab est exécuté à partir d'un programme externe).

option est la chaîne de caractères 'nomessage' pour supprimer les messages d'erreurs.

Pour revenir au mode par défaut, taper errcatch(-1,"kill") ou bien errcatch(-1) .

Lorsque errcatch est appelée à l'intérieur d'une fonction, le mode d'interception d'erreur est automatiquement réinitialisé au mode par défaut lorsque l'on sort de la fonction.

errcatch() est un equivalent obsolete de errcatch(-1) .

REMARQUES

errcatch est obsolete. Il est préférable d'utiliser try ou execstr(...,'errcatch') à la place de errcatch lorsque c'est possible.

See Also

errclear , iserror , whereami , execstr ,


errclear

Scilab Function
Last update : 16/06/2004

errclear - "effacement" d'une erreur

Calling Sequence

errclear([n])

Description

Supprime l'action (voir errcatch) associée à l'interception de l'erreur de type n .

Si n est positif, il s'agit du numéro de l'erreur à "effacer"; sinon toutes les erreurs sont "effacées".

See Also

errcatch , iserror , lasterror ,


error_table

table
Last update : 24/05/2006

error_table - table of error messages

Description

This page gives the table of the predefined error messages, and their associated error number. Some of these error messages are used by Scilab itself for parser errors or specific builtin errors. Some others are of a more general use and can be used in Scilab functions. The starred one are those for which the syntax error(n,pos) is handled.

1 "incorrect assignment"

2 "invalid factor"

3 "waiting for right parenthesis"

4 "undefined variable : %s"

5 "inconsistent column/row dimensions"

6 "inconsistent row/column dimensions"

7 "dot cannot be used as modifier for this operator"

8 "inconsistent addition"

9 "inconsistent subtraction"

10 "inconsistent multiplication"

11 "inconsistent right division "

12 "inconsistent left division"

13 "redefining permanent variable"

14 "eye variable undefined in this context"

15 "submatrix incorrectly defined"

16 "incorrect command!"

17 "stack size exceeded! (Use stacksize function to increase it)"

18 "too many variables!"

19 "Problem is singular"

* 20 "%dth argument must be square matrix"

21 "invalid index"

22 "recursion problems. Sorry...."

23 "Matrix norms available are 1, 2, inf, and fro"

24 "convergence problem..."

25 "bad call to primitive :%s"

26 "too complex recursion! (recursion tables are full)"

27 "division by zero..."

28 "empty function..."

29 "matrix is not positive definite"

30 "invalid exponent"

31 "incorrect string"

32 "singularity of log or tan function"

33 "too many "":"""

34 "incorrect control intruction syntax"

35 "Syntax error in an if,a while or a select instruction"

* 36 "%dth argument is incorrect here"

* 37 "incorrect function at line %d"

38 "file name incorrect"

39 "incorrect number of arguments"

40 "waiting for end of command"

41 "incompatible LHS"

42 "incompatible RHS"

43 "not implemented in scilab...."

* 44 "%dth argument is incorrect"

* 45 "null matrix (argument # %d)"

46 "incorrect syntax"

47 "end or else is missing..."

* 48 "input line longer than buffer size %d"

49 "incorrect file or format"

50 "subroutine not found : %s"

* 52 "%dth argument must be a real matrix"

* 53 "%dth input is invalid (waiting for real or complex matrix) "

* 54 "%dth argument type must be polynomial"

* 55 "%dth argument type must be character string"

* 56 "%dth argument must be a list"

57 "problem with comparison symbol..."

58 "incorrect number of arguments in function call..."

59 "incorrect # of outputs in the function"

60 "argument with incompatible dimensions"

61 "direct acces file : give format"

* 62 "end of file at line %d"

* 63 "%d graphic terminal?"

64 "integration fails"

* 65 "%d: logical unit already used"

66 "no more logical units available!"

67 "unknown file format "

69 "floating point exception"

70 "too many arguments in fort (max 30)"

71 "this variable is not valid in fort"

72 "%s is not valid in this context"

73 "error while linking"

74 "Leading coefficient is zero"

75 "Too high degree (max 100)"

* 76 "for x=val with type(val)="%d is not implemented in Scilab"

77 "%s : wrong number of rhs arguments"

78 "%s : wrong number of lhs arguments"

80 "incorrect function (argument n:%s)"

81 "Argument "%d of %s: wrong type argument, expecting a real or complex matrix"

82 "Argument %d of %s: wrong type argument, expecting a real matrix"

83 "Argument %d of %s: wrong type argument, expecting a real vector"

84 "Argument %d of %s: wrong type argument, expecting a scalar"

85 "host does not answer..."

86 "uncontrollable system"

87 "unobservable system"

88 "sfact : singular or assymetric problem"

* 89 "%dth argument has incorrect dimensions"

* 90 "%dth argument must be a transfer matrix"

* 91 "%dth argument must be in state space form"

* 92 "%dth argument must be a rational matrix"

* 93 "%dth argument must be in continuous time"

* 94 "%dth argument must be in discrete time"

* 95 "%dth argument must "be SISO"

* 96 "time domain of %dth argument is not defined"

* 97 "%dth argument must be a system in state space or transfer matrix form"

98 "variable returned by scilab argument function is incorrect"

* 99 "elements of %dth argument must be in increasing order!"

* 100 "the elements of %dth argument are not in (strictly) decreasing order"

* 101 "last element of %dth argument is not equal to the first"

102 "variable or function %s is not in file %s"

103 "variable %s is not a valid rational function "

104 "variable %s is not a valid state space representation"

105 "undefined fonction"

106 "function name already used"

* 107 "too many functions are defined (maximum #:%d)"

108 "too complex for scilab, may be a too long control instruction"

109 "too large, can""t be displayed"

110 "%s was a function when compiled but is now a primitive!"

111 "trying to re-define function %s "

112 "Cannot allocate more memory"

113 "too large string"

114 "too many linked entry points"

115 "Stack problem detected within a loop"

* 116 "%dth argument has incorrect value"

* 117 "list element number %d is Undefined"

* 118 "%dth argument must be a named variable not an expression"

119 "indices for non-zero elements must be given by a 2 column matrix"

121 "incompatible indices for non-zero elements "

* 122 "logical unit number should be larger than %d"

123 "fonction not bounded from below"

124 "problem may be unbounded :too high distance between two consecutive iterations"

126 "Inconsistent constraints"

127 "no feasible solution"

128 "degenerate starting point"

129 "no feasible point has been found"

130 "optimization fails: back to initial point"

131 "optim: stop requested by simulator (ind=0)"

132 "optim: incorrect input parameters"

133 "too small memory"

134 "optim: problem with initial constants in simul "

135 "optim : bounds and initial guess are incompatible"

136 "optim : this method is NOT implemented "

137 "NO hot restart available in this method"

138 "optim : incorrect stopping parameters"

139 "optim : incorrect bounds"

* 141 "incorrect function (argument n:%d)"

* 142 "hot restart : dimension of working table (argument n:%d)"

143 "optim : df0 must be positive !"

144 "Undefined operation for the given operands check or define function %s for overloading"

201 "Argument %d of %s: wrong type argument, expecting a real or complex matrix"

202 "Argument %d of %s: wrong type argument, expecting a real matrix"

203 "Argument %d of %s : wrong type argument, expecting a real vector"

* 204 "Argument %d, wrong type argument: expecting a scalar"

205 "Argument %d of %s: wrong matrix size (%d) expected "

206 "Argument %d of %s: wrong vector size (%d) expected "

207 "Argument %d of %s: wrong type argument, expecting a matrix of strings"

208 "Argument %d of %s: wrong type argument, expecting a booleen matrix"

209 "Argument %d of %s: wrong type argument, expecting a matrix"

210 "Argument %d of %s: wrong type argument, expecting a list"

211 "Argument %d of %s: wrong type argument, expecting a function or string (external function)"

212 "Argument %d of %s: wrong type argument, expecting a polynomial matrix"

213 "Argument %d of %s: wrong type argument, expecting a working integer matrix"

214 "Argument %d of %s: wrong type argument, expecting a vector"

* 215 "%dth argument type must be boolean"

* 216 "%dth argument type must be boolean or scalar"

* 217 "%dth argument must be a sparse matrix of scalars"

* 218 "%dth argument must be a handle to sparse lu factors"

* 219 "%dth argument must be a sparse or full scalar matrix"

220 "null variable cannot be used here"

221 "A sparse matrix entry is defined with two differents values"

222 "lusolve not yet implemented for full RHS"

223 "It is not possible to redefine the %s primitive this way (see clearfun)."

224 "Type data base is full"

225 "This data type is already defined"

226 "Inequality comparison with empty matrix"

227 "Missing index"

228 "reference to the cleared global variable %s"

230 "semidef fails"

231 "First argument must be a single string"

232 "Entry name not found"

233 "Maximum number of dynamic interfaces reached"

234 "link: expecting more than one argument"

235 "link: problem with one of the entry point"

236 "link: the shared archive was not loaded"

237 "link: Only one entry point allowed On this operating system"

238 "link: First argument cannot be a number"

239 "You cannot link more functions, maxentry reached"

240 "File %s already exists or directory write access denied "

241 "File %s does not exist or read access denied "

242 "binary direct acces files must be opened by ""file"""

243 "C file logical unit not allowed here"

244 "Fortran file logical unit not allowed here"

* 245 "No input file associated to logical unit %d"

246 "function not defined for given argument type(s)"

* 248 "%dth argument is not a valid variable name"

* 249 "%dth argument must not be an empty string"

250 "Recursive extraction is not valid in this context"

251 "bvode: ipar dimensioned at least 11"

252 "bvode: ltol must be of size ipar(4)"

253 "bvode: fixpnt must be of size ipar(11)"

254 "bvode: ncomp must be less than 20"

255 "bvode: m must be of size ncomp"

256 "bvode: sum(m) must be less than 40"

257 "bvode: sum(m) must be less than 40"

258 "bvode: input data error"

259 "bvode: no. of subintervals exceeds storage"

260 "bvode: Th colocation matrix is singular"

261 "Interface property table is full"

* 262 "too many global variables!,max number is %d"

263 "Error while writing in file,(disk full or deleted file)"

* 264 "%dth argument must not contain NaN or Inf"

265 "A and B must have equal number of rows"

266 "A and B must have equal number of columns"

267 "A and B must have equal dimensions"

* 268 "invalid return value for function passed in argument %d"

* 269 "%dth argument eigenvalues must have negative real parts"

* 270 "%dth argument eigenvalues modulus must be less than one"

* 271 "Size varying argument aeye(), (arg %d) not allowed here"

272 "endfunction is missing"

273 "Instruction left hand side: waiting for a dot or a left parenthesis"

274 "Instruction left hand side: waiting for a name"

275 "varargout keyword cannot be used here"

276 "Missing operator, comma, or semicolon"

277 "Too many commands defined"

See Also

warning , errcatch , execstr , lasterror ,


error

Scilab Function
Last update : 13/06/2005

error - envoi de message d'erreur

Calling Sequence

error(message [,n])
error(n)
error(n,pos)

Parameters

  • message : une chaîne de caractères. Le message à visualiser.
  • n : Un entier, le nombre associé à l'erreur.
  • pos : Un entier, paramétrant le message (voir error_table )

Description

La fonction error permet d'envoyer à l'utilisateur un message d'erreur et de gérer cette erreur. Par défaut error termine l'éxecution courante et revient au niveau du prompt. Ce défaut peut être changé en utilisant les fonctions errcatch et execstr(...,'errcatch') .

error(message) envoie à l'utilisateur le message d'erreur donné par la chaîne de caractères message . Le nombre associé à l'erreur est assigné à 10000.

error(message,n) envoie à l'utilisateur le message d'erreur donné par la chaîne de caractères message . Le nombre associé à l'erreur est donné par n .

Certains messages d'erreur prédéfinis requièrent un paramètre entier, (position de l'argument dans la liste d'appel de la fonction,...) (voir error_table ). Dans ce cas l'argument pos doit contenir ce nombre entier : error(n,pos) . Dans les autres cas l'argument pos est ignoré.

Voir la table des erreurs dans error_table .

Examples

error('Mon message')
error(43)
error(52,3)

See Also

warning , errcatch , execstr , lasterror ,


etime

Fonction Scilab
Last update : 16/12/2004

etime - Temps écoulé

Calling Sequence

e = etime(t2,t1)

Parameters

  • t2 : un vecteur de 6 ou 10 valeurs.
  • t1 : un vecteur de 6 ou 10 valeurs.
  • e : nombre de secondes entre t2 et t1 .

Description

t1 et t2 contenant 10 valeurs : t2 et t1 doivent avoir le format retourné par getdate . Dans ce cas, leurs troisièmes, quatrièmes et cinquièmes valeurs sont ignorées.
t1 et t2 contenant 6 valeurs : t2 et t1 doivent avoir le format : T = [Year Month Day Hour Minute Second] avec Second un nombre de secondes et de millisecondes (e.g: 12.345).

t2 et t1 doivent être de même taille.

t2 et t1 peuvent être des matrices dont chaque ligne contient un format précisé ci-dessus (toutes les lignes du même format).

Examples

t1=[2004 06 10 17 00 12.345]
t2=[2004 06 10 17 01 13.965]
E1=etime(t2,t1)
t1=[2004 06 24 162 5 10 17 00 12 345]
t2=[2004 06 24 162 5 10 17 01 13 965]
E2=etime(t2,t1)

See Also

tic , toc , getdate , etime ,

Authors

V.C.


evstr

Scilab Function
Last update : 17/06/2004

evstr - évaluation d'une expression

Calling Sequence

H=evstr(Z)
[H,ierr]=evstr(Z)

Parameters

  • Z : matrice de chaînes de caractères M ou list(M,Subexp)
    • M : matrice de chaînes de caractères
    • Subexp : vecteur de chaînes de caractères
  • H : matrice
  • ierr : entier, 0 ou numéro de l'erreur

Description

Renvoie le résultat de l'évaluation de la matrice de chaînes de caractères M . Chaque élément de la matrice doit être une expression Scilab valide.

Si l'évaluation d'un terme de M conduit à une erreur, la syntaxe habituelle H=evstr(M) , déclenche le message d'erreur. Dans la syntaxe [H,ierr]=evstr(M) aucun message d'erreur n'est produit, mais le numéro de l'erreur est renvoyé dans ierr .

Si Z est une liste, Subexp est un vecteur de chaînes de caractères qui définit des sous-expressions qui sont évaluées avant M . Ces sous-expressions doivent être référencées par l'expression %(k) dans M , où k est la position de la sous-expression dans la liste Subexp .

evstr('a=1') n'est pas valide (utiliser pour cela execstr ).

Examples

    a=1; b=2; Z=['a','b'] ; evstr(Z)

    a=1; b=2; Z=list(['%(1)','%(1)-%(2)'],['a+1','b+1']);
    evstr(Z)

See Also

execstr ,


execstr

Scilab Function
Last update : 12/09/2006

execstr - exécution d'instructions Scilab contenues dans des chaînes de caractères

Calling Sequence

execstr(instr)
ierr=execstr(instr,'errcatch' [,msg])

Parameters

  • instr : vecteur de chaînes de caractères
  • ierr : entier, 0 ou numéro de l'erreur
  • msg : chaîne de caractères ( 'm' ou 'n' ). La valeur par défaut est 'n' .

Description

Exécute les instructions Scilab données dans l'argument instr .

Note : les instructions ne doivent pas comporter de marques de suite (..).

Si 'errcatch' n'est pas présent dans les arguments, les erreurs sont contrôlées comme d'habitude.

Si 'errcatch' est présent dans les arguments, et qu'une erreur est rencontrée lors de l'évaluation d'un élément de instr , execstr ne produit aucun message d'erreur, mais stoppe l'exécution des instructions stockées dans instr (au point où l'erreur s'est produite), et renvoie dans ierr le numéro de l'erreur. Dans ce cas l'affichage du message d'erreur est contrôlé par l'option msg :

"m": le message d'erreur est affiché et enregistré
"n": le message d'erreur n'est pas affiché mais il est enregistré (voir lasterror ). Il s'agit du comportement par défaut.

ierr=execstr(instr,'errcatch') peut gérer les erreurs de syntaxes. Ceci peut être utile pour évaluer les instructions obtenues par une requète à l'utilisateur (interface homme-machine).

Examples

execstr('a=1') // affecte a=1.

execstr('1+1') // ne fait rien de particulier (alors que evstr('1+1') renvoie 2)

execstr(['if %t then';
         '  a=1';
         '  b=a+1';
         'else'
         ' b=0'
         'end'])

// récupération des erreurs d'exécution
execstr('a=zzzzzzz','errcatch')
execstr('a=zzzzzzz','errcatch','m')

// récupération des erreurs de syntaxe
execstr('a=1?02','errcatch')
lasterror(%t)

execstr('a=[1 2 3)','errcatch')
lasterror(%t)

See Also

try , errclear , iserror , whereami , execstr ,


exec

Scilab Function
Last update : 13/07/2005

exec - exécution d'un script (fichier de commandes)

Calling Sequence

exec(path [,mode])
exec(fun [,mode])
ierr=exec(path,'errcatch' [,mode])
ierr=exec(fun,'errcatch' [,mode])

Parameters

  • path : chaîne de caractères, le chemin du script à exécuter
  • mode : entier, précisant le mode d'exécution (voir plus bas)
  • fun : identificateur d'une fonction scilab
  • ierr : entier, 0 ou numéro d'erreur

Description

exec(path [,mode]) exécute séquentiellement les instructions Scilab contenues dans le fichier spécifié par path avec le mode d'exécution optionnel mode .

Les différentes valeurs de mode sont :

0: valeur par défaut
-1: rien n'est affiché
1: chaque ligne de commande est affichée
2: l'invite de commande --> est affiché
3: lignes de commandes + invite de commande
4: pause dans l'exécution au début de chaque ligne. L'exécution reprend après un appui sur la touche entrée/return.
7: pause + invite + affichage : ce mode est utile pour les démonstrations.

exec(fun [,mode]) exécute la fonction fun comme un script : aucun argument n'est utilisé en entrée ou en sortie, et l'exécution se fait dans l'environnement courant (les variables créées dans la fonction sont conservées après l'exécution). Cette forme est plus efficace, car ainsi les instructions du script peuvent être pré-compilées (voir getf, comp). Cette méthode d'exécution des scripts permet aussi de stocker des scripts comme des fonctions dans des librairies.

Si une erreur se produit pendant l'exécution, si la chaîne de caractères 'errcatch' est présente, exec ne produit pas de message d'erreur, mais stoppe l'exécution du script et renvoie une valeur de ierr égale au numéro de l'erreur. Si la chaîne 'errcatch' n'est pas présente, la gestion habituelle des erreurs est utilisée.

REMARQUE

Examples

    // création d'un script
    mputl('a=1;b=2',TMPDIR+'/myscript')
    // on l'exécute
    exec(TMPDIR+'/myscript')
    whos -name "a "

    // création d'une function
    function y=foo(x),a=x+1;y=a^2,endfunction
    clear a b
    // appel à la fonction
    foo(1)
    // a est une variable créée dans l'environnement de la fonction foo
    // elle est détruite à la sortie de la fonction.
    whos -name "a "

    x=1 // on crée la variable x pour qu'elle soit connue à l'exécution de foo
    exec(foo)
    // a et y ont été créées dans l'environnement courant
    whos -name "a "

See Also

getf , execstr , evstr , comp , mode , chdir , getcwd ,


exists

Scilab Function
Last update : 16/06/2004

exists - teste l'existence d'une variable

Calling Sequence

exists(name [,where])

Parameters

  • name : chaîne de caractères
  • where : une chaîne de caractères optionnelle valant par défaut 'all'

Description

exists(name) renvoie 1 si la variable nommée name existe et 0 sinon.

Mise en garde : une fonction utilisant exists peut renvoyer un résultat dépendant de l'environnement courant !

exists(name,'local') renvoie 1 si la variable nommée name existe dans l'environnement de la fonction courante et 0 sinon.

Examples

deff('foo(x)',..
['disp([exists(''a12''),exists(''a12'',''local'')])'
 'disp([exists(''x''),exists(''x'',''local'')])'])
foo(1)
a12=[];foo(1)

See Also

isdef , whereis , type , typeof , macrovar ,


exit

Scilab Command
Last update : 16/06/2004

exit - termine la session Scilab courante

Description

termine la session Scilab courante.

See Also

quit , abort , break , return , resume ,


external

Scilab Function
Last update : 16/06/2004

external - Objet Scilab, fonction externe ou routine

Description

Fonction ou routine externe nécessitée par des commandes particulières.

Un "external" est une fonction ou une routine qui est utilisée comme argument d'une "primitive de haut niveau", telle que ode , optim , schur ...

La séquence d'appel de la fonction ou de la routine est en général imposée par la primitive de haut niveau qui impose en particulier les arguments d'entrée.

Par exemple la fonction externe costfunc est un argument de la primitive optim . Sa séquence d'appel doit être de la forme : [f,g,ind]=costfunc(x,ind) et optim (primitive permettant de résoudre des problèmes d'optimisation) est invoquée ainsi :

optim(costfunc,...)

Ici costfunc (la fonction coût à minimiser avec optim ) calcule f=f(x) et g= le gradient de f en x ( ind est un entier dont l'usage est précisé dans l'aide de optim ).

Si d'autres variables sont nécessaires à la fonction externe, ces variables peuvent être définies dans son environnement. Elles peuvent aussi être stockées dans une liste : par exemple

[f,g,ind]=costfunc(x,ind,a,b,c)

est valide pour optim si costfunc est remplacé par list(costfunc,a,b,c) . La séquence d'appel à optim est donc maintenant :

optim(list(costfunc,a1,b1,c1),....

Un "external" peut aussi être une routine Fortran ou C : cela peut permettre d'accélérer les calculs.

Le nom de la routine est donné comme argument à la primitive de haut niveau sous forme d'une chaîne de caractères. La séquence d'appel est aussi imposée. Des exemples sont donnés dans le répertoire routines/default (voir le fichier README ).

Les routines externes Fortran ou C peuvent aussi être liées dynamiquement (voir link ).

See Also

ode , optim , impl , dassl , intg , schur , gschur ,


extraction

Scilab Function
Last update : 17/06/2004

extraction - extraction à partir d'une matrice ou d'une liste

Calling Sequence

x(i,j)
x(i)
[...]=l(i)
[...]=l(k1)...(kn)(i) ou [...]=l(list(k1,...,kn,i))
l(k1)...(kn)(i,j) ou l(list(k1,...,kn,list(i,j))

Parameters

  • x : matrice de tout type
  • l : liste
  • i,j : indices
  • k1,...kn : indices à valeurs entières

Description

CAS DES MATRICES i et j peuvent être :
des scalaires,vecteurs ou matrices à éléments positifs.
r=x(i,j) construit la matrice r telle que:

r(l,k)=x(int(i(l)),int(j(k)))

pour l variant de 1 à size(i,'*')

et k variant de 1 à size(j,'*') .

La valeur maximale de i (resp. j ) doit être inférieure ou égale à size(x,1) (resp. size(x,2) ).

r=x(i) où x est une matrice 1 x 1, construit la matrice r telle que r(l,k)=x(int(i(l)),int(i(k))) pour l variant de 1 à size(i,1) et k variant de 1 à size(i,2) . Noter que dans ce cas l'indice i est valable si toutes ses composantes sont égales à 1.
r=x(i) avec x un vecteur ligne, construit le vecteur ligne r tel que r(l)=x(int(i(l))) pour l entre 1 et size(i,'*') La valeur maximale de i doit être inférieure ou égale à size(x,'*') .
r=x(i) avec x une matrice à une ou plusieurs colonnes, construit la matrice r telle que r(l) ( l variant de 1 à size(i,'*') ) contient le terme numéro int(i(l)) du vecteur colonne issu de la concaténation des colonnes de x . La valeur maximale de i doit être inférieure ou égale à size(x,'*') .
Le symbole : signifiant "tous les éléments".
r=x(i,:) construit la matrice r telle que r(l,k)=x(int(i(l)),k)) pour l variant de 1 à size(i,'*') et k variant de 1 à size(x,2)
r=x(:,j) construit la matrice r telle que r(l,k)=x(l,int(j(k))) pour l variant de 1 à size(r,1) et k variant de 1 à size(j,'*') .
r=x(:) construit le vecteur colonne r obtenu par concaténation des colonnes de x . Cette commande est équivalente à r=matrix(x,size(x,'*'),1) .
vecteur de booléens Si un indice ( i ou j ) est un vecteur de booléen il est interprété comme find(i) ou find(j) , respectivement.
un polynôme Si un indice ( i ou j ) est un vecteur de polynômes ou de polynômes implicites il est interprété comme horner(i,m) ou horner(j,n) , respectivement, où m et n sont les dimensions de x associées. Même si cette fonctionnalité marche pour tous les polynômes, il est recommandé d'utiliser des polynômes dans $ par souci de lisibilité.
CAS DES LISTES

(types LIST et TLIST) S'ils sont présents, les ki donnent le chemin vers un terme d'une sous-liste de la liste l . Ils permettent de faire une extraction récursive directe sans utiliser de variable intermédiaire. Les instructions:

[...]=l(k1)...(kn)(i)

et

[...]=l(list(k1,...,kn,i))

sont interprétées comme :

lk1 = l(k1) , .. = .. , lkn = lkn-1(kn) , [...] = lkn(i)

De même, les instructions

l(k1)...(kn)(i,j)

et

l(list(k1,...,kn,list(i,j))

sont interprétées comme :

lk1 = l(k1) , .. = .. , lkn = lkn-1(kn) , lkn(i,j)

i et j , peuvent valoir :

scalaire vecteur ou matrice à termes positifs [r1,...rn]=l(i) extrait les termes i(k) de la liste l et les stocke dans les variables rk pour k variant de 1 à size(i,'*')
le symbole : ("tous les éléments")
vecteur de booléens Si i est un vecteur de booléens, il est interprété comme find(i) .
un polynôme Si i est un vecteur de polynômes ou de polynômes implicites il est interprété comme horner(i,m) où m=size(l) . Même si cette fonctionnalité marche pour tous les polynômes, il est recommandé d'utiliser des polynômes dans $ par souci de lisibilité.
k1,..kn peuvent être :
un nombre réel positif
un polynôme un polynôme, interprété comme horner(ki,m) ou m est la taille de la sous-liste correspondante.
une chaîne de caractères associée à un nom d'entrée de sous-liste'

Quand le chemin désigne plusieurs termes d'une liste l'instruction doit avoir autant de termes dans la liste des arguments du membre de gauche que le nombre de termes sélectionnés. Mais si la syntaxe d'extraction est utilisée dans les arguments d'entrée d'une fonction, chaque terme renvoyé est ajouté aux arguments d'entrée.

Notez que l(list()) est identique à l .

REMARQUES

Pour les matrices rationnelles et les systèmes dynamiques linéaires stockés sous forme de représentation d'état, la syntaxe x(i) ne doit pas être utilisée pour l'extraction des éléments d'un vecteur, à cause de la confusion possible avec l'extraction des éléments de liste. La syntaxe x(1,j) où x(i,1) doit être utilisée dans ce cas.

Examples

    // CAS DES MATRICES
    a=[1 2 3;4 5 6]
    a(1,2)
    a([1 1],2)
    a(:,1)
    a(:,3:-1:1)
    a(1)
    a(6)
    a(:)
    a([%t %f %f %t])
    a([%t %f],[2 3])
    a(1:2,$-1)
    a($:-1:1,2)
    a($)
    //
    x='test'
    x([1 1;1 1;1 1])
    //
    b=[1/%s,(%s+1)/(%s-1)]
    b(1,1)
    b(1,$)
    b(2) // le numérateur
    // CAS des LISTES (types LIST et TLIST)
    l=list(1,'qwerw',%s)
    l(1)
    [a,b]=l([3 2])
    l($)
    x=tlist(l(2:3)) // construction d'une TLIST avec les deux derniers termes de l
    //
    dts=list(1,tlist(['x';'a';'b'],10,[2 3]));
    dts(2)('a')
    dts(2)('b')(1,2)
    [a,b]=dts(2)(['a','b'])

See Also

find , horner , parents ,


feval

Scilab Function
Last update : 16/06/2004

feval - évaluation multiple d'une fonction

Calling Sequence

[z]=feval(x,y,f)
[z]=feval(x,f)

Parameters

  • x,y : deux vecteurs
  • f : fonction, ou chaîne de caractères pour les appels Fortran ou C

Description

Evaluation multiple d'une fonction pour un ou deux arguments de type vecteur.

z=feval(x,f) renvoie le vecteur z défini par z(i)=f(x(i)
z=feval(x,y,f) renvoie la matrice z telle que z(i,j)=f(x(i),y(j))

f est un "external" (fonction ou routine Fortran ou C) acceptant un ou deux arguments d'entrée supposés réels. Le résultat renvoyé par f peut par contre être réel ou complexe. Dans le cas d'un appel Fortran ou C, la fonction 'f' doit être définie dans la fonction ffevalf (voir dans le dossier SCIDIR/routines/default )

Examples

deff('[z]=f(x,y)','z=x^2+y^2');
feval(1:10,1:5,f)
deff('[z]=f(x,y)','z=x+%i*y');
feval(1:10,1:5,f)
feval(1:10,1:5,'parab')   // voir le fichier ffeval.f
feval(1:10,'parab')
// Pour le lien dynamique (voir l'exemple ftest dans ffeval.f)
// on peut utiliser la commande "link"

See Also

evstr , horner , execstr , external , link ,


find

Scilab Function
Last update : 12/01/2004

find - find indices of boolean vector or matrix true elements

Calling Sequence

[ii]=find(x [,nmax])
[i1,i2,..]=find(x [,nmax])

Parameters

  • x : may be a boolean vector, a boolean matrix, a boolean hypermatrix, a "standard" matrix or hypermatrix
  • nmax : an integer giving the maximum number of indices to return. The default value is -1 which stands for "all". This option can be used for efficiency, to avoid searching all indices.
  • ii, i1, i2, .. : integer vectors of indices or empty matrices

Description

If x is a boolean matrix,

ii=find(x) returns the vector of indices i for which x(i) is "true". If no true element found find returns an empty matrix.

[i1,i2,..]=find(x) returns vectors of indices i1 (for rows) and i2 (for columns),.. such that x(i1(n),i2(n),..) is "true". If no true element found find returns empty matrices in i1 , i2 , ...

if x is a standard matrix or hypermatrix find(x) is interpreted as find(x<>0)

find([]) returns []

Examples

A=rand(1,20);
w=find(A<0.4)
A(w)
w=find(A>100)

B=rand(1,20);
w=find(B<0.4,2) //at most 2 returned values

H=rand(4,3,5); //an hypermatrix
[i,j,k]=find(H>0.9)

H(i(1),j(1),k(1))

See Also

boolean , extraction , insertion , vectorfind ,


format

Scilab Function
Last update : 12/01/2004

format - number printing and display format

Calling Sequence

format([type],[long])
format()

Parameters

  • type : character string
  • long : integer ( max number of digits (default 10))

Description

Sets the current printing format with the parameter type ; it is one of the following :

"v": for a variable format (default)
"e": for the e-format.

long defines the max number of digits (default 10). format() returns a vector for the current format: first component is the type of format (0 if v ; 1 if e ); second component is the number of digits.

In "variable format" mode, vectors entries which are less than %eps times the maximum absolute value of the entries were displayed as "0" in the previous Scilab versions. It is no more the case, the clean function can be used to set neglitible entries to zeros.

Examples

x=rand(1,5);
format('v',10);x
format(20);x
format('e',10);x
format(20);x

x=[100 %eps];
format('e',10);x
format('v',10);x

format("v")

See Also

write , disp , print ,


fort

Scilab Function
Last update : 12/01/2004

fort - Fortran or C user routines call

Calling Sequence

// long form 'out' is present
[y1,...,yk]=fort("ident",x1,px1,"tx1",...,xn,pxn,"txn",
"out",[ny1,my1],py1,"ty1",...,[nyl,myl],pyl,"tyl")
// short form : no 'out' parameter
[y1,....,yk]=fort("ident",x1,...,xn)

Parameters

  • "ident" : string.
  • xi : real matrix or string
  • pxi, pyi : integers
  • txi, tyi : character string "d" , "r" , "i" or "c" .

Description

Interactive call of Fortran (or C) user program from Scilab. The routine must be previously linked with Scilab. This link may be done:

-with Scilab " link " command (incremental "soft" linking) during the Scilab session.(see link )
-by "hard" re-linking. Writing the routine call within Scilab routine default/Ex-fort.f , adding the entry point in the file default/Flist and then re_linking Scilab with the command make bin/scilex in main Scilab directory.

There are two forms of calling syntax, a short one and a long one. The short one will give faster code and an easier calling syntax but one has to write a small (C or Fortran) interface in order to make the short form possible. The long one make it possible to call a Fortran routine (or a C one) whitout modification of the code but the syntax is more complex and the interpreted code slower.

The meaning of each parameter is described now:

"ident"is the name of the called subroutine.
x1,...,xnare input variables (real matrices or strings) sent to the routine,
px1,...,pxnare the respective positions of these variables in the calling sequence of the routine "ident" and
tx1,...,txnare their types ( "r" , "i" , "d" and "c" for real (float) , integer, double precision and strings)
"out"is a keyword used to separate input variables from output variables. when this key word is present it is assumes that the long form will be used and when it is not prsent, the short form is used.
[ny1, my1]are the size (# of rows and columns. For 'c' arguments, m1*n1 is the number of charaters ) of output variables and
py1, ...are the positions of output variables (possibly equal to pxi ) in the calling sequence of the routine. The pyi 's integers must be in increasing order.
"ty1", ...are the Fortran types of output variables. The k first output variables are put in y1,..., yk .

If an output variable coincides with an input variable (i.e. pyi=pxj ) one can pass only its position pyi . The size and type of yi are then the same as those of xi . If an output variable coincides with an input variable and one specify the dimensions of the output variable [myl,nyl] must follow the compatibility condition mxk*nxk >= myl*nyl .

In the case of short syntax , [y1,....,yk]=fort("ident",x1,...,xn) , the input parameters xi 's and the name "ident" are sent to the interface routine Ex-fort . This interface routine is then very similar to an interface (see the source code in the directory SCIDIR/default/Ex-fort.f ).

For example the following program:

 subroutine foof(c,a,b,n,m)
 integer n,m
 double precision a(*),b,c(*)
 do 10 i=1,m*n
   c(i) = sin(a(i))+b
 10 continue
 end

link("foof.o","foof")
a=[1,2,3;4,5,6];b= %pi;
[m,n]=size(a);
// Inputs:
// a is in position 2 and double
// b                3     double
// n                4     integer
// m                5     integer
// Outputs:
// c is in position 1 and double with size [m,n]
c=fort("foof",a,2,"d",b,3,"d",n,4,"i",m,5,"i","out",[m,n],1,"d");

returns the matrix c=2*a+b .

If your machine is a DEC Alpha, SUN Solaris or SGI you may have to change the previous command line link("foo.o","foo") by one of the followings:

link('foof.o -lfor -lm -lc','foof').
link('foof.o -lftn -lm -lc','foof').
link('foof.o -L/opt/SUNWspro/SC3.0/lib/lib77 -lm -lc','foof').

The same example coded in C:

  void fooc(c,a,b,m,n)
 double a[],*b,c[];
 int *m,*n;
      { double sin();
 int i;
 for ( i =0 ; i < (*m)*(*n) ; i++)
        c[i] = sin(a[i]) + *b;
 }

link("fooc.o","fooc","C") // note the third argument
a=[1,2,3;4,5,6];b= %pi;
[m,n]=size(a);
c=fort("fooc",a,2,"d",b,3,"d",m,4,"i",n,5,"i","out",[m,n],1,"d");

See Also

link , c_link , intersci , addinter ,


for

Scilab Keyword
Last update : 04/10/2004

for - mot clé pour les structures de boucles

Description

Utilisé pour spécifier une boucle. La syntaxe est la suivante :

for variable=expression ,instruction, ,instruction,end

for variable=expression do instruction, ,instruction,end

Si expression est une matrice ou un vecteur ligne, variable prend successivement les valeurs de chaque colonne de la matrice.

Un exemple utile : for variable=n1:pas:n2, ...,end

Si expression est une liste, variable prend comme valeurs successives les termes de la liste.

Attention : le nombre de caractères constituant le corps d'une instruction conditionnelle (if while for ou select/case) est limité à 16k.

Examples

n=5;
for i = 1:n, for j = 1:n, a(i,j) = 1/(i+j-1);end;end
for j = 2:n-1, a(j,j) = j; end; a
for  e=eye(3,3),e,end
for v=a, write(6,v),end
for j=1:n,v=a(:,j), write(6,v),end
for l=list(1,2,'example'); l,end

See Also

while , end , do ,


funptr

Scilab Function
Last update : 12/01/2004

funptr - coding of primitives ( wizard stuff )

Calling Sequence

[numptr] = funptr(name)

Parameters

  • name : a string, the name of a primitive
  • numptr : the internal routine number of the primitive

Description

Utility function (for experts only) to get the internal routine number numptr of the primitive 'name' . numptr is formed from the interface number fun and the routine number fin of the primitive in its interface by numptr = 100*fun + fin (fin < 100). From numptr you can get the interface number fun = floor(numptr/100) which may be useful to link a dynamical interface with arguments passed by reference (see example section).

Examples

// Suppose you want to load some codes via the dynamic
// loading facilities offers by addinter. By default
// arguments are passed by values but if you want to
// pass them by reference you can do the following
// (name being the scilab name of one of the interfaced
// routines) :
//
// addinter(files,spnames,fcts)  // args passed by values
// num_interface = floor(funptr(name)/100)
// intppty(num_interface)  // args now passed by reference
//
// Note that if you enter the following
//
// intppty()
//
// you will see all the interfaces working by reference

See Also

clearfun , newfun , intppty , addinter ,


getdate

Fonction Scilab
Last update : 09/06/2004

getdate - renvoie la date et l'heure

Calling Sequence

dt=getdate()
x=getdate("s")
dt=getdate(x)

Parameters

  • dt : un vecteur entier à 10 composantes (voir plus bas)
  • x : un entier contenant la date en secondes écoulées depuis le 1er Janvier 1970

Description

dt=getdate() renvoie la date courante au format expliqué ci-dessous :
dt(1) : l'année (entier compris entre 0000 et 9999).
dt(2) : le mois (entier compris entre 01 et 12).
dt(3) : le numéro de semaine à la norme ISO 8601 (entier compris entre 01 et 53).
dt(4) : le jour du calendrier Julien (entier compris entre 000 et 366).
dt(5) : le jour de la semaine (entier compris entre 1 (dimanche) et 7).
dt(6) : le jour dans le mois (entier compris entre 01 et 31).
dt(7) : l'heure du jour (entier compris entre 00 et 23).
dt(8) : les minutes (entier compris entre 00 et 59).
dt(9) : les secondes (entier compris entre 00 et 59).
dt(10) : les millisecondes (entier compris entre 000 et 999).
x = getdate("s") renvoie un entier contenant le nombre de secondes écoulées depuis le 1er Janvier 1970, 00:00 UTC (Unix Time Convention).
dt = getdate(x) renvoie dt au format ci-dessus, à partir de x (nombre de secondes depuis le 1er Janvier 1970). Dans ce cas, dt(10) est toujours égal à 0.

Examples

w=getdate()
mprintf("Annee:%d,mois:%d,jour:%d",w(1),w(2),w(6));

x=getdate("s")
getdate(x)

See Also

date , timer ,

Authors

V.C.


getenv

Scilab Function
Last update : 16/06/2004

getenv - renvoie la valeur d'une variable d'environnement

Calling Sequence

env=getenv(str [, rep] )

Parameters

  • str : chaîne de caractères contenant le nom de la variable d'environnement rep : chaîne de caractères optionnelle. Quand elle est utilisée, getenv renvoie la valeur rep quand la variable d'environnement str n'existe pas.
  • env : chaîne de caractères contenant la valeur de la variable d'environnement

Description

Renvoie la la valeur d'une variable d'environnement, quand celle-ci existe.

Examples

 getenv('SCI')
 getenv('FOO','foo')


getfield

Scilab Function
Last update : 16/06/2004

getfield - extraction d'un champ d'une liste

Calling Sequence

[x,...]=getfield(i,l)

Parameters

  • x : matrice de tout type
  • l : variable de type list, tlist ou mlist
  • i : indice du champ, voir extraction pour plus de détails

Description

Cette fonction est un équivalent de la syntaxe [x,...]=l(i) pour l'extraction de champs avec la seule différence qu'elle s'applique aussi aux objets de type mlist .

Examples

l=list(1,'qwerw',%s)
[a,b]=getfield([3 2],l)

a=hypermat([2,2,2],rand(1:2^3));// les hypermatrices sont stockées dans des mlist
a(1) // le terme a(1,1,1)
getfield(1,a) // le premier champ de la mlist

See Also

extraction ,


getpid

Scilab Function
Last update : 16/06/2004

getpid - renvoie le numéro de processus de Scilab

Calling Sequence

id=getpid()

Description

Renvoie le numéro de processus de Scilab sous forme d'un entier.

Examples

d='SD_'+string(getpid())+'_'


getversion

Scilab Function
Last update : 23/03/2004

getversion - get Scilab version name

Calling Sequence

version=getversion()
[version,opts]=getversion()

Parameters

  • version : a string
  • opts : a vector of string with four entries : [compiler,pvm,tk,ocaml]

Description

return in version the Scilab version name and in opts build options which can be used to determine if scilab has been build with pvm, tk or ocaml.

Examples

getversion()
[version,opts]=getversion()


global

Scilab Function
Last update : 16/06/2004

global - définition de variables globales

Calling Sequence

global('nam1',...,'namn')
global nam1 ... namn

Parameters

  • nam1,..., namn : noms valides de variables

Description

Habituellement, chaque fonction Scilab a ses propres variables locales et peut accéder "en lecture uniquement" à toutes les variables de l'environnement principal et des fonctions appelantes. Le mot-clé global permet de partager certaines variables en lecture/écriture entre des fonctions. Toute affectation à ces variables est propagée à toutes les autres fonctions ayant déclaré cette variable globale (avec le mot-clé global ).

Si la variable n'existe pas au moment où elle est déclarée globale avec le mot-clé global , elle est initialisée avec une matrice vide [].

Examples

// 1 : l'environnement appelant et une fonction partagent une variable
global a
a=1
deff('y=f1(x)','global a,a=x^2,y=a^2')
f1(2)
a
// 2 : trois fonctions partagent des variables
deff('initdata()','global A C ;A=10,C=30')
deff('letsgo()','global A C ;disp(A) ;C=70')
deff('letsgo1()','global C ;disp(C)')
initdata()
letsgo()
letsgo1()

See Also

who , isglobal , clearglobal , gstacksize , resume ,


gstacksize

Scilab Function
Last update : 16/06/2004

gstacksize - obtenir ou changer la taille de la pile des variables globales

Calling Sequence

gstacksize(n)
sz=gstacksize()

Parameters

  • n : entier, la taille de pile désirée, en nombre de mots double-précision
  • sz : vecteur à deux composantes [taille_totale taille_utilisée]

Description

Scilab stocke les variables globales dans une pile.

gstacksize(n) permet d'augmenter ou de diminuer la taille de cette pile. La taille maximum dépend de la mémoire (physique ou virtuelle) restante. Notez que Scilab peut augmenter automatiquement la taille de la pile globale si cela s'avère nécessaire.

sz=gstacksize() renvoie un vecteur à deux composantes contenant la taille totale de la pile et la taille actuellement utilisée. SH VOIR AUSSI who, stacksize


hat (^)

Scilab Function
Last update : 16/06/2004

hat (^) - élévation à la puissance

Calling Sequence

A^b

Description

Élévation à la puissance de matrices ou vecteurs.

Si A est un vecteur ou une matrice non-carrée l'élévation à la puissance est faite élément par élément avec la signification usuelle.

Pour une matrice carrée A l'élévation est faite au sens matriciel.

Pour les matrices booléennes, rationnelles ou polynomiales, l'exposant doit être entier.

Notez que 123.^b est interprété comme (123).^b . Dans un tel cas le point fait partie de l'opérateur et non pas du nombre.

Examples

2^4
[1 2;2 4]^(1+%i)
s=poly(0,"s");
[1 2 s]^4
[s 1;1  s]^(-1)

See Also

exp , inv ,


host

Scilab Function
Last update : 08/04/2005

host - exécution d'une commande Unix ou DOS

Calling Sequence

stat=host(command-name)

Parameters

  • command-name : chaîne de caractères contenant les commandes à exécuter
  • stat : un entier

Description

Envoie la chaîne command-name à l'interpréteur de commande (sh sous Unix, ou command.com sous DOS). La sortie standard et les erreurs sont reportées dans l'interpréteur de commande.

stat vaut -1 en sortie si la fonction ne peut pas être appelée (pas assez de mémoire par exemple) ou alors le code de sortie de l'interpréteur de commande.

Examples

    //creation d'un fontion pour recuperer la path courant
    function wd=getdir()
      if MSDOS then
        host('cd>'+TMPDIR+'\path');
      else
        host('pwd>'+TMPDIR+'/path');
      end
      wd=read(TMPDIR+'/path',1,1,'(a)')
    endfunction
    //appel de la fonction
    wd=getdir()

See Also

edit , manedit , unix_g , unix_s , unix_w , unix_x ,


hypermatrices

Scilab data type
Last update : 25/09/2006

hypermatrices - Objet Scilab, matrices à N dimensions

Description

Le type Hypermatrice permet de manipuler des tableaux multidimensionnels. Ce type d'objet peut être défini par extension des matrices 2D comme ceci :

a=[1 2;3 4];a(:,:,2)=rand(2,2)

ou directement en utilisant la fonction hypermat .

Les termes peuvent être réels, complexes, polynômiaux, rationnels, booléens ou de type chaîne de caractères.

Les Hypermatrices sont des mlists : mlist(['hm','dims','entries'],sz,v) où sz est le vecteur ligne des dimensions et v le vecteur colonne des termes (rangés tel que l'indice le plus à gauche varie en premier).

NOTES: le nombre de dimensions des hypermatrices dont les dimensions les plus à droite sont egales à 1 est automatiquement réduit. Une hypermatrice n'ayant que 2 dimensions est automatiquement transformée en une matrice standard (de type 1).

Examples

a(1,1,1,1:2)=[1 2]
a=[1 2;3 4];a(:,:,2)=rand(2,2)
a(1,1,:)

size(a)

a(:,:,1) //dimensionnality reduction
type(a(:,:,1))

[a a]

See Also

hypermat ,


hypermat

Scilab Function
Last update : 16/06/2004

hypermat - initialisation d'une matrice à N dimensions

Calling Sequence

M=hypermat(dims [,v])

Parameters

  • dims : vecteur des dimensions de l'hypermatrice
  • v : vecteur des termes de l'hypermatrice (valeur par défaut zeros(prod(dims),1) )

Description

Initialisation d'une matrice à N dimensions dont les dimensions sont données dans le vecteur dims et dont les termes sont éventuellement donnés dans un vecteur optionnel v .

La structure de données M contient un champ M('dims') contenant les dimensions de l'hypermatrice et un champ contenant le vecteur des termes M('entries') , rangés tel que l'indice le plus à gauche varie en premier : [M(1,1,..);..;M(n1,1,..);...;M(1,n2,..);..;M(n1,n2,..);...]

Examples

M=hypermat([2 3 2 2],1:24)


iconvert

Scilab Function
Last update : 29/06/2005

iconvert - conversion au codage entier à 1,2 ou 4 octets

Calling Sequence

y=iconvert(X,itype)

Parameters

  • X : matrice de flottants ou d'entiers
  • y : matrice d'entiers codés sur 1,2 ou 4 octets.

Description

Convertit et stocke sous forme d'entiers à 1,2 ou 4 octets.

itype=0 : renvoie des nombres à virgule flottante
itype=1 : renvoie et stocke dans y des entiers int8 dans l'intervalle [-128,127]
itype=11 : renvoie et stocke dans y des entiers uint8 dans l'intervalle [0,255]
itype=2 : renvoie et stocke dans y des entiers int16 dans l'intervalle [-32768,32767]
itype=12 : renvoie et stocke dans y des entiers uint16 dans l'intervalle [0, 65535]
itype=4 : renvoie et stocke dans y des entiers int32 dans l'intervalle[-2147483648,2147483647]
itype=14 : renvoie et stocke dans y des entiers uint32 dans l'intervalle [0, 4294967295]

Examples

b=int32([1 -120 127 312])
y=iconvert(b,1)

See Also

double , inttype ,


ieee

Scilab Function
Last update : 17/06/2004

ieee - détermine le mode d'exception IEEE pour les calculs

Calling Sequence

mod=ieee()
ieee(mod)

Parameters

  • mod : un entier valant 0,1 ou 2

Description

ieee() renvoie le mode d'exception IEEE courant pour les calculs en virgule flottante.

0 : les exceptions produisent une erreur
1 : les exceptions produisent un warning
2 : les exceptions produisent Inf ou Nan

ieee(mod) choisit le mode d'exception ieee courant pour les calculs en virgule flottante.

La valeur initiale au lancement de Scilab est 0.

REMARQUES

Examples

    ieee(1);1/0
    ieee(2);1/0,log(0)

See Also

errcatch ,


if then else

Scilab Function
Last update : 30/08/2005

if then else - exécution conditionnelle

Calling Sequence

if expr1 then instructions
elseif expri then instructions
....
else instructions
end

Description

Le mot-clé if évalue une expression logique et exécute un groupe d'instructions si l'expression est vraie.

Les expri sont des expressions à valeurs numériques ou booléennes. Si expri est à valeur matricielle la condition est vraie si tous les termes de la matrice sont vrais ou différents de zéro.

Les mot-clés optionnels elseif et else permettent d'exécuter en alternative des groupes d'instructions. Le mot clé end , correspondant au if , termine le groupe courant d'instructions. La structure des lignes ci-dessus n'est pas significative et la seule contrainte est que chaque mot-clé then doit être sur la même ligne que le if ou elseif correspondant .

Le mot-clé then peut être remplacé par un passage à la ligne ou une virgule.

Attention : le nombre de caractères constituant le corps d'une instruction conditionnelle (if while for ou select/case) est limité à 16k.

Examples

   i=2
   for j = 1:3,
      if i == j then
        a(i,j) = 2;
      elseif abs(i-j) == 1 then
        a(i,j) = -1;
      else a(i,j) = 0;
      end,
   end

See Also

try , while , select , boolean , end , then , else ,


insertionaffectation

Scilab Function
Last update : 17/06/2004

insertion - insertion/modification dans une variable

affectation - affectation partielle d'une variable

Calling Sequence

x(i,j)=a
x(i)=a
l(i)=a
l(k1)...(kn)(i)=a ou l(list(k1,...,kn,i))=a
l(k1)...(kn)(i,j)=a ou l(list(k1,...,kn,list(i,j))=a

Parameters

  • x : matrice de tout type
  • l : liste
  • i,j : indices
  • k1,...kn : indices à valeurs entières
  • a : nouvelles valeurs des termes

Description

CAS DES MATRICES

Si x est un tableau i et j peuvent être :
Des scalaires, vecteurs ou matricesDans ce cas les parties entieres des valeurs données en indices doivent être strictement positives. Seule la prtie entière est prise e, compte.
Si a est une matrice de dimensions (size(i,'*'),size(j,'*')) x(i,j)=a renvoie une nouvelle matrice x telle que x(int(i(l)),int(j(k)))=a(l,k) pour l variant de 1 à size(i,'*') et k variant de 1 à size(j,'*') , les autres composantes initiales de x sont inchangées.
Si a est un scalaire x(i,j)=a renvoie une nouvelle matrice x telle que x(int(i(l)),int(j(k)))=a pour l variant de 1 à size(i,'*') et k variant de 1 à size(j,'*') , les autres composantes initiales de x sont inchangées.
Si la valeur maximum de i ou j dépasse la dimension correspondante de x , alors x est au préalable agrandie aux dimensions adéquates en stockant des zéros pour les matrices standard, des chaînes vides pour les matrices de chaînes de caractères ou la valeur %F pour les matrices booléennes.
x(i,j)=[] détruit les lignes spécifiées par i si j désigne toutes les colonnes de x ou détruit les colonnes spécifiées par j si i désigne toutes les lignes de x . Dans tous les autres cas x(i,j)=[] produit une erreur.
x(i)=a où a est un vecteur renvoie une nouvelle matrice x telle que x(int(i(l)))=a(l) pour l variant de 1 à size(i,'*') , les autres composantes initiales de x sont inchangées.
x(i)=a où a est un scalaire, renvoie une nouvelle matrice x telle que x(int(i(l)))=a pour l variant de 1 à size(i,'*') , les autres composantes initiales de x sont inchangées.

Si la valeur maximum de i dépasse size(x,1) , x est au préalable agrandie aux dimensions adéquates en stockant des zéros pour les matrices standard, des chaînes vides pour les matrices de chaînes de caractères ou la valeur %F pour les matrices booléennes.

Si x est une matrice 1 x 1 a peut être un vecteur ligne (resp. colonne) de dimension size(i,'*') . La matrice x obtenue est un vecteur ligne (resp. colonne)
Si x est un vecteur ligne (resp. colonne) a doit être un vecteur ligne (resp. colonne) de dimension size(i,'*')
Si x est une matrice en général a doit être un vecteur ligne ou colonne de dimension size(i,'*') et la valeur maximum de i ne peut dépasser size(x,'*') ,
x(i)=[] supprime les termes spécifiés par i .
Le : symbole Le symbole : signifiant "tous les éléments".
x(i,:)=a est interprété comme x(i,1:size(x,2))=a
x(:,j)=a est interprété comme x(1:size(x,1),j)=a
x(:)=a renvoie dans x la matrice a remise en forme en accord avec les dimensions de x. size(x,'*') doit être égal à size(a,'*')
Vecteurs de booléens Si un indice ( i ou j ) est un vecteur de booléens, il est interprété comme find(i) ou find(j) , respectivement.
PolynomesSi un indice ( i ou j ) est un vecteur de polynômes ou de polynômes implicites, il est interprété comme horner(i,m) ou horner(j,n) , respectivement, où m et n sont les dimensions de x associées. Même si cette fonctionnalité marche pour tous les polynômes, il est recommandé d'utiliser des polynômes dans $ par souci de lisibilité.
CAS DES LISTES
S'ils sont présents les ki donnent le chemin vers un terme d'une sous-liste de la liste l . Ils permettent de faire une insertion récursive directe sans utiliser de variable intermédiaire. Les instructions l(k1)...(kn)(i)=a et l(list(k1,...,kn,i)=a) sont interprétées comme :

lk1 = l(k1) .. = ..

lkn = lkn-1(kn)

lkn(i) = a lkn-1(kn) =lkn .. = ..

les instructions l(k1)...(kn)(i,j)=a et l(list(k1,...,kn,list(i,j))=a sont interprétées comme:

lk1 = l(k1) .. = ..

lkn =lkn-1(kn) lkn(i,j) = a

lkn-1(kn) = lkn .. = ..

l(k1) = lk1

i peut être :
un scalaire réel positif l(0)=a ajoute un terme "à gauche" de la liste l(i)=a affecte a au terme i de la liste l . Si i>size(l) , l est préalablement agrandie et les termes créés sont de type non-défini. l(i)=null() supprime le terme i th de la liste.
un polynôme. Si i est un vecteur de polynômes ou de polynômes implicites il est interprété comme horner(i,m) où m=size(l) . Même si cette fonctionnalité marche pour tous les polynômes, il est recommandé d'utiliser des polynômes dans $ par souci de lisibilité.
k1,..kn peuvent être :
un polynôme, interprété comme horner(ki,m) ou m est la taille de la sous-liste correspondante.
une chaîne de caractères associée à un nom d'entrée de sous-liste.

Remarque

Pour les matrices rationnelles et les systèmes dynamiques linéaires stockés sous forme de représentation d'état, la syntaxe x(i) ne doit pas être utilisée pour l'insertion des éléments d'un vecteur, à cause de la confusion possible avec l'insertion des éléments de liste. La syntaxe x(1,j) où x(i,1) doit être utilisée dans ce cas.

Examples

    // CAS DES MATRICES
    a=[1 2 3;4 5 6]
    a(1,2)=10
    a([1 1],2)=[-1;-2]
    a(:,1)=[8;5]
    a(1,3:-1:1)=[77 44 99]
    a(1)=%s
    a(6)=%s+1
    a(:)=1:6
    a([%t %f],1)=33
    a(1:2,$-1)=[2;4]
    a($:-1:1,1)=[8;7]
    a($)=123
    //
    x='test'
    x([4 5])=['4','5']
    //
    b=[1/%s,(%s+1)/(%s-1)]
    b(1,1)=0
    b(1,$)=b(1,$)+1
    b(2)=[1 2] // le numérateur
    // CAS des LISTES (types LIST et TLIST)
    l=list(1,'qwerw',%s)
    l(1)='Changed'
    l(0)='Added'
    l(6)=['one more';'added']
    //
    //
    dts=list(1,tlist(['x';'a';'b'],10,[2 3]));
    dts(2)('a')=33
    dts(2)('b')(1,2)=-100

See Also

find , horner , parents , extraction ,


intppty

Scilab Function
Last update : 12/01/2004

intppty - set interface argument passing properties

Calling Sequence

funs=intppty()
intppty(fun)

Parameters

  • fun : integer an interface number (see funptr)
  • funs : integer vector, vector of interface number (see funptr)

Description

The interface programs may be written in 2 different ways for the mode of function argument passing.

In the first and default way, the arguments are passed by value. With the following syntax:

foo(A,1+2)

the argument associated with A will be passed by value (a copy of A is made before foo is called, and the argument associated with 1+2 will be passed by value.

In the second way arguments may be passed be reference if there are "named arguments" (no copy of the variable value is done). intppty(fun) with fun>0 tells Scilab that the interface with number fun can handle arguments passed by reference. With the following syntax:

foo(A,1+2)

the argument associated with A will be passed by reference, and the argument associated with 1+2 will be passed by value.

Warning, declaring that the interface with number fun can handle arguments passed by reference if it is not the case should produce unpredictable results.

intppty(fun) with fun<0 suppress this property for the interface -fun .

intppty() returns the vector of interfaces which handle arguments passed by reference.

This function may be useful for dynamically loaded interface (see addinter).

See Also

funptr , addinter ,


inttype

Scilab Function
Last update : 16/06/2004

inttype - type des entiers utilisés dans les types entiers de données.

Calling Sequence

[i]=inttype(x)

Parameters

  • x : matrice d'entiers (voir int8)
  • i : un entier

Description

renvoie un entier donnant le type de données stockées dans x avec la convention suivante :

1 : codage entier à 1 octet

2 : codage entier à 2 octets

4 : codage entier à 4 octets

11 : codage entier non-signé à 1 octet

12 : codage entier non-signé à 2 octets

14 : codage entier non-signé à 4 octets

Examples

x=uint16(1:10);
inttype(x)

See Also

int8 ,


inv_coeff

Scilab Function
Last update : 16/06/2004

inv_coeff - construction d'une matrice polynomiale à partir des coefficients

Calling Sequence

[P]=inv_coeff(C,[,d,[name])

Parameters

  • C : "grosse" matrice des coefficients
  • d : degré de la matrice polynomiale (paramètre optionnel valant par défaut d=-1+size(C,'c')/size(C,'r') )
  • name : chaîne de caractères (indéterminée du polynôme, 'x' par défaut).

Description

P=inv_coeff(Mp,k) , quand k est compatible avec la taille de Mp renvoie une matrice polynomiale de degré k. C=[C0,C1,...,Ck] et P= C0 + C1*x +... +Ck*x^k .

Examples

A=int(10*rand(2,6))
// construction d'une matrice polynomiale de degré 1
P=inv_coeff(A,1)
norm(coeff(P)-A)
// utilisation de la valeur par défaut du degré
P1=inv_coeff(A)
norm(coeff(P1)-A)

See Also

poly , degree , coeff ,


iserror

Scilab Function
Last update : 16/06/2004

iserror - test d'occurrence d'une erreur

Calling Sequence

iserror([n])

Description

Vérifie si l'erreur n a eu lieu (après un appel à errcatch ). iserror renvoie 1 si l'erreur a eu lieu et 0 sinon.

n>0 est le numéro de l'erreur; toutes les erreurs sont testées si n<0 .

See Also

error , errcatch ,


isglobal

Scilab Function
Last update : 16/06/2004

isglobal - vérifie si une variable est globale

Calling Sequence

t=isglobal(x)

Parameters

  • x : une variable
  • t : un booléen

Description

isglobal(x) renvoie %T (vrai) si x a été déclarée en temps que variable globale et %F (faux) sinon.

Examples

isglobal(1)
global a
isglobal(a)

See Also

global , clearglobal , who ,


lasterror

Scilab Function
Last update : 16/11/2004

lasterror - get last recorded error message

Calling Sequence

str=lasterror( [opt] )
[str,n]=lasterror([opt])
[str,n,line,func]=lasterror([opt])

Parameters

  • str : vector of character strings or an empty matrix. The last recorded error message.
  • n : integer, 0 or the last recorded error number.
  • line : integer, 0 or the last recorded function line number.
  • func : string,the last recorded function name
  • opt : boolean, if %t recorded message is cleared. Default is %t.

Description

Each time an error occur, the Scilab error handler records it in internal tables (only the last one is retained). The lasterror function allows to get the message, the error number, the current function (if any) and the current line of the current function out of these tables.

This function is useful while using errcatch or execstr .

The recorded error message may be retained for a further call to lasterror using lasterror(%f) .

Examples

ierr=execstr('a=zzzzzzz','errcatch')
if ierr>0 then disp(lasterror()),end

See Also

errcatch , execstr , error , errclear , edit_error ,


left ([)

Scilab Function
Last update : 16/06/2004

left ([) - crochet gauche

Calling Sequence

[a11,a12,...;a21,a22,...;...]
[s1,s2,...]=func(...)

Parameters

  • a11,a12,... : toute matrice (réelle, complexe, polynomiale, rationnelle, liste de type syslin ...) de dimensions adéquate
  • s1,s2,... : noms de variables

Description

Les crochets droit et gauche sont utilisés pour effectuer une concaténation de matrices. Ces symboles sont aussi utilisés quand on effectue un appel à une fonction renvoyant plusieurs arguments.

A l'intérieur d'une paire de crochets spécifiant une concaténation, un espace ou une virgule signifient une concaténation de colonnes, alors qu'un point-virgule ou un passage à la ligne signifient une concaténation de lignes.

Note : pour éviter les confusions il est plus sûr d'utiliser des virgules pour concaténer des colonnes.

Pour des crochets entourant une liste d'arguments de sortie d'une fonction, les noms de variables doivent être séparés par des virgules.

Examples

[6.9,9.64; sqrt(-1) 0]
[1 +%i  2 -%i  3]
[]
['ceci est';'un vecteur';'de chaines de caracteres']
s=poly(0,'s');[1/s,2/s]
[tf2ss(1/s),tf2ss(2/s)]

[u,s]=schur(rand(3,3))

See Also

comma , semicolon ,


lessgreat

Scilab symbol
Last update : 30/05/2006

less - (<) lower than comparison

great - (<) greater than comparison

Description

logical comparison symbol

<>means "different" (same as ~= )
<means "lower than"
>means "larger than"
<=means lower than or equal to.
>=means larger than or equal to

See Also

if , comparison , equal ,


list

Scilab Function
Last update : 30/11/2005

list - Objet Scilab, Définition d'une liste

Calling Sequence

list(a1,....an)

Description

Crée une liste avec les éléments ai qui sont des objets Scilab arbitraires ( matrice, liste, ... ). Le numéro de type des objets liste (renvoyé par la fonction type ) est 15.

list() crée une liste vide (0 élément).

Operations sur les listes

  • extraction : [x,y,z...]=L(v) où v est un vecteur d'indices; [x,y,z]=L(:) extrait tous les éléments.
  • insertion en position i : L(i)=a . Remarque : l'opération L(i)=a avec i > 1 + size(L) ne génère pas d'erreur les entrées en position 1 + size(L), ..., i-1 étant alors indéfinies. Par contre l'extraction d'un élément indéfini en génère une.
  • ajouter un élément en queue de liste : L($+1)=e.
  • ajouter un élément en tête de liste : L(0)=e. (remarque : après cette opération e est en position 1, la position des éléments initiaux de la liste étant décalée vers la droite).
  • suppression : L(i)=null() supprime l'élément en position i de la liste L.
  • concaténation de deux listes : L3 = lstcat(L1,L2).
  • nombre d'éléments d'une liste : vous pouvez utiliser nb_elm = size(L) ou encore nb_elm = length(L).
  • itérer avec une liste : il est possible d'utiliser une liste L pour piloter une boucle for : for e=L,...,end est une boucle avec length(L) itérations, la variable e de la boucle prenant la valeur L(i) à l'itération i.

    • Remarques

    Scilab propose deux autres sortes de liste, les tlist (pour listes typées) et les mlist qui sont très utiles pour définir de nouveaux types de données avec possibilité de surcharge des opérateurs classiques (voir overloading ). Les tableaux multidimensionnels de scilab (les hypermatrices ) sont en fait codés comme des mlist.

    Les structures Matlab (struct) sont aussi utilisables.

    Examples

    l = list(1,["a" "b"])
l(0) = "foo"
l($+1) = "hello"
l(2) = "toto"
l(3) = rand(1,2)
l(3) = null()
lbis = list("gewurtz", "caipirina" ,"debug")
lter = lstcat(l,lbis)
size(lter) - size(lbis) - size(l)  // doit être nul

    See Also

    null , lstcat , tlist , insertion , extraction , size , length ,


lsslist

Scilab Function
Last update : 16/06/2004

lsslist - Définition d'un système dynamique linéaire

Calling Sequence

lsslist()
lsslist(a1,....an)

Description

lsslist(a1,....an) est équivalent à la commande tlist(['lss','A';'B';'C';'X0','dt'], a1,....an)

Crée une tlist avec ['lss','A';'B';'C';'X0','dt'] pour le premier champ et les ai pour les termes suivants, s'ils sont spécifiés. Aucune vérification de taille ou de type n'est faite sur les ai .

See Also

tlist , syslin ,


lstcat

Scilab Function
Last update : 16/06/2004

lstcat - concaténation de listes

Calling Sequence

lc=lstcat(l1,..ln)

Parameters

  • li : une liste ou une variable de type indifférent
  • lc : une liste

Description

lc=lstcat(l1,..ln) concatène les composantes des listes li sous forme d'une liste unique. Si les li sont des variables d'un autre type elles sont tout simplement ajoutées comme termes supplémentaires dans la liste.

Examples

lstcat(list(1,2,3),33,list('foo',%s))
lstcat(1,2,3)

See Also

list ,


matrices

Scilab Function
Last update : 16/06/2004

matrices - Objet Scilab, matrices

Description

Les matrices sont les objets de base dans Scilab. Elles peuvent être définies de la façon suivante :

E=[e11,e12,...,e1n;
   e21,e22,...,e2n;
        ....
   em1,em2,...,emn];

Les termes eij peuvent être des nombres complexes ou réels, des polynômes, des fraction rationnelles, des chaînes de caractères ou des booléens.

Les vecteurs sont vus comme des matrices à une ligne ou une colonne.

Examples

E=[1,2;3,4]
E=[%T,%F;1==1,1~=1]
s=poly(0,'s');E=[s,s^2;1,1+s]
E=[1/s,0;s,1/(s+1)]
E=['A11','A12';'A21','A22']

See Also

poly , string , boolean , rational , empty , hypermatrices ,


matrix

Scilab Function
Last update : 16/06/2004

matrix - remise en forme d'une matrice

Calling Sequence

y=matrix(v,n,m)
y=matrix(v,[sizes])

Parameters

  • v : un vecteur, une matrice ou une hypermatrice
  • n,m : entiers
  • sizes : vecteur d'entiers
  • y : un vecteur, une matrice ou une hypermatrice

Description

Pour un vecteur ou une matrice de taille n x m , la commande y=matrix(v,n,m) ou y=matrix(v,[n,m]) transforme le vecteur (ou la matrice) v en une matrice nxm en parcourant les éléments colonne par colonne v .

Si l'une des dimensions m ou n est égale à -1 elle est remplacée par le quotient de size(v,'*') par l'autre dimension.

Pour une hypermatrice telle que prod(size(v))==prod(sizes) , la commande y=matrix(v,sizes) (ou de façon équivalente, y=matrix(v,n1,n2,...nm) ) transforme v en une matrice ou une hypermatrice en parcourant les éléments de v (parcourus tel que le premier indice varie en premier). y=matrix(v,sizes) renvoie une matrice ou un vecteur si sizes est un scalaire ou un vecteur à deux composantes.

Examples

a=[1 2 3;4 5 6]
matrix(a,1,6)
matrix(a,1,-1)
matrix(a,3,2)

See Also

matrices , hypermatrices , ones , zeros , rand , poly , empty ,


mlist

Scilab Function
Last update : 08/06/2005

mlist - Objet Scilab, définition d'une liste typée

Calling Sequence

mlist(typ,a1,....an )

Parameters

  • typ : vecteur de chaînes de caractères
  • ai : objet Scilab ( matrice, liste, chaîne... ).

Description

Les objets de type mlist sont très similaires aux objets de type tlist . Si M est de type mlist, pour tout indice i qui n'est pas le nom d'un champ de la liste, M(i) n'est pas le i -ème champ de la liste mais est interprété comme le i -ème terme de M vu comme un vecteur. C'est la seule différence entre mlist et tlist .

Les champs des mlist doivent donc être manipulés par leur noms. Il peuvent aussi être manipulés avec les fonctions getfield et setfield .

Examples

M=mlist(['V','name','value'],['a','b','c'],[1 2 3]);
// définition de la fonction d'affichage
deff('%V_p(M)','disp(M.name+'':''+string(M.value))')
// définition de la fonction d'extraction
deff('r=%V_e(i,M)',..
'r=mlist([''V'',''name'',''value''],M.name(i),M.value(i))')
M(2) // Le deuxième terme du vecteur M
M.value

// définition de M comme une tlist
M=tlist(['V','name','value'],['a','b','c'],[1 2 3]);
M(2)

M('name')

// avec deux indices
M=mlist(['V','name','value'],['a','b';'c' 'd'],[1 2;3 4]);
deff('r=%V_e(varargin)',[
    'M=varargin($)';
    'H=[''V'',''name'',''value'']'
    'r=mlist(H,M.name(varargin(1:$-1)),M.value(varargin(1:$-1)))'])

M(:,2)
// tableau multidimensionnel
str=['a','b','c','d','e','f','g','h'];
n=hypermat([2,2,2],str);
v=hypermat([2,2,2],1:8);
M=mlist(['V','name','value'],n,v);
M(1,1:2,2)

See Also

tlist , list , overloading , getfield , setfield ,


mode

Scilab Function
Last update : 14/12/2005

mode - choisit le mode d'exécution des scripts et des fonctions

Calling Sequence

mode(k)
k=mode()

Description

Utilisé uniquement dans un script ou une fonction, mode(k) permet de choisir le mode d'affichage utilisé pendant l'exécution, suivant la valeur de k :

k=0 : les nouvelles valeurs des variables sont affichées (voir semi ou comma ).
k=-1 : l'exécution est silencieuse (rien n'est affiché : mode par défaut pour les fonctions)
k=1 ou k=3 : les nouvelles valeurs des variables sont affichées, chaque ligne de commande est affichée et précédée de l'invite de commande (mode par défaut pour les scripts lancés par "exec")
k=7: les nouvelles valeurs des variables sont affichées, chaque ligne de commande est affichée et précédée de l'invite de commande. L'exécution est interrompue après chaque ligne et reprend après un appui sur la touche entrée/return.Si la touche entrée/return et précédée du caractère "p", l'éxecution est suspendue (voir pause ).
L'affichage est supprimé dans les fonctions compilées (voir getf ou comp). Par défaut les fonctions Scilab sont éxécutées en mode silencieux ("-1").

See Also

exec , getf , semi , comma ,


mtlb_mode

Scilab Function
Last update : 17/06/2004

mtlb_mode - choisit le mode de compatibilité Matlab

Calling Sequence

mmode=mtlb_mode()
mtlb_mode(mmode)

Parameters

  • mmode : un booléen

Description

Les additions et soustractions fonctionnent différemment dans Scilab et Matlab quand un des opérandes est une matrice vide :

Scilab:

a+[] -->a
a-[] -->a
[]+a -->a
[]-a -->-a
Matlab

a+[] -->[]
a-[] -->[]
[]+a -->[]
[]-a -->[]

mtlb_mode(%t) passe au mode de compatibilité Matlab pour les additions et les soustractions. mtlb_mode(%f) retourne au mode Scilab.

mtlb_mode() renvoie la valeur du mode de compatibilité courant (%t=Matlab, %f=Scilab).

See Also

empty ,


names

Scilab Syntax
Last update : 16/06/2004

names - syntaxe des noms de variables dans Scilab

Description

Les noms de variables et de fonctions doivent commencer par une lettre de l'alphabet ou l'un des caractères "spéciaux" suivants : ' % ', ' _ ', ' # ', ' ! ', ' $ ', ' ? '.

Les caractères suivants peuvent être des lettres ou des chiffres, ou bien des caractères spéciaux tels que ' _ ', ' # ', ' ! ', ' $ ', ' ? '.

Le nombre de caractères des noms de variables n'est pas limité mais seuls les 24 premiers sont pris en compte. La différence entre minuscules et majuscules est prise en compte.

Examples

// Noms valides
%eps
A1=123
#Color=8
My_Special_Color_Table=rand(10,3)
// Noms invalides
//1A , b%, .C


null

Scilab Function
Last update : 16/06/2004

null - suppression d'un terme d'une liste

Calling Sequence

l(i)=null()

Description

Suppression d'un terme d'une liste

Examples

l=list(1,2,3);
l(2)=null() // get list(1,3)

See Also

list , clear ,


overloading

Scilab keyword
Last update : 18/02/2004

overloading - display, functions and operators overloading capabilities

Description

In scilab, variable display, functions and operators may be defined for new objects using functions (scilab coded or primitives).

Display: The display of new objects defined by tlist structure may be overloaded (the default display is similar to list 's one). The overloading function must have no output argument a single input argument. It's name is formed as follow %<tlist_type>_p where %<tlist_type> stands for the first entry of the tlist type component.
Operators: Each operator which is not defined for given operands type may be defined. The overloading function must have a single output argument and one or two inputs according to the number of operands. The function name is formed as follow:

for binary operators: %<first_operand_type>_<op_code>_<second_operand_type>

for unary operators: %<operand_type>_<op_code>

extraction and insertion operators which are n-nary operators are described below.

<operand_type> , <first_operand_type> , <second_operand_type> are sequence of characters associated with each data type as described in the following table:

data type | char code | data type | char code
constant | s | boolean | b
string | c | library | f
function pointer | fptr | handle | h
integer | i | list | l
function | m | compiled function | mc
polynomial | p | sparse | sp
boolean sparse | spb | tlist | tlist_type

<op_code> is a single character associated with each operator as described in the following table:

op | char code | op | char code
' | t | + | a
- | s | * | m
/ | r | \ | l
^ | p | .* | x
./ | d | .\ | q
.*. | k | ./. | y
.\. | z | : | b
*. | u | /. | v
\. | w | [a,b] | c
[a;b] | f | () extraction | e
() insertion | i | == | o
<> | n | | | g
& | h | .^ | j
~ | 5 | .' | 0
< | 1 | > | 2
<= | 3 | >= | 4
 |  | iext | 6

The overloading function for extraction syntax b=a(i1,...,in) has the following calling sequence: b=%<type_of_a>_e_(i1,...,in,a)

and the syntax [x1,..,xm]=a(i1,...,in) has the following calling sequence: [x1,..,xm]=%<type_of_a>_e_(i1,...,in,a)

The overloading function associated to the insertion syntax a(i1,...,in)=b has the following calling sequence: a=%<type_of_b>_i_<type_of_a>(i1,...,in,b,a) .

The 6 char code may be used for some complex insertion algorithm like x.b(2)=33 where b field is not defined in the structure x . The insertion is automatically decomposed into temp=x.b; temp(2)=33; x.b=temp . The 6 char code is used for the first step of this algorithm. The 6 overloading function is very similar to the e 's one.

Functions :Some basic primitive function

may also be overloaded for new data type. When such a function is undefined for a particular data types the function %<type_of_an_argument>_<function_name> is called. User may add in this called function the definition associated with the input data types.

Examples

//DISPLAY
deff('[]=%tab_p(l)','disp([['' '';l(3)] [l(2);string(l(4))]])')
tlist('tab',['a','b'],['x';'y'],rand(2,2))

//OPERATOR
deff('x=%c_a_s(a,b)','x=a+string(b)')
's'+1

//FUNCTION
deff('x=%c_sin(a)','x=''sin(''+a+'')''')
sin('2*x')

See Also

tlist , disp , symbols ,


parents ( )

Scilab Function
Last update : 16/06/2004

parents ( ) - parenthèses droite et gauche

Calling Sequence

(expression)
[...]=func(e1,e2,...)
[x1,x2,...]=(e1,e2,...)
x(i,j)
v(i)
[...]=l(i)

Parameters

  • x : matrice de tout type
  • v : vecteur ligne ou colonne de tout type
  • l : liste
  • func : nom de fonction
  • e1,e2,... : expression de type quelconque

Description

Les parenthèses droite et gauche sont utilisées pour :

* Spécifier l'ordre d'évaluation dans des expressions,

* Former la liste des arguments d'entrée d'une fonction. Les arguments multiples sont séparés par des virgules.

* Sélectionner des éléments dans les vecteurs, matrices et listes.

Voir extraction et insertion pour de plus amples précisions.

* [x1,x2,...]=(e1,e2,...) est équivalent aux commandes préalables %t_1 = e1, %t_2 = e2, ..., suivies de x1 = %t_1, x2 = %t_2, ..., où les variables %t_i, i = 1, 2, ... sont "invisibles" pour l'utilisateur.

Examples

3^(-1)
x=poly(0,"x");
//
(x+10)/2
i3=eye(3,3)
//
a=[1 2 3;4 5 6;7 8 9],a(1,3),a([1 3],:),a(:,3)
a(:,3)=[]
a(1,$)=33
a(2,[$ $-1])
a(:,$+1)=[10;11;12]
//
w=ssrand(2,2,2);ssprint(w)
ssprint(w(:,1))
ss2tf(w(:,1))
//
l=list(1,2,3,4)
[a,b,c,d]=l(:)
l($+1)='new'
//
v=%t([1 1 1 1 1])
//
[x,y,z]=(1,2,3)

See Also

colon , comma , brackets , list , extraction , insertion ,


pause

Scilab Function
Last update : 16/06/2004

pause - mode de pause, attente clavier

Description

Passage en mode de pause ; inséré dans le code d'une fonction, pause fait une pause dans l'exécution de la fonction : un symbole d'invite de commande est affiché à l'utilisateur indiquant le "niveau" de la pause (e.g. -1-> ). L'utilisateur se trouve dans un environnement dans lequel toutes les variables du niveau correspondant sont accessibles (en particulier les variables locales de la fonction). Pour reprendre l'exécution taper "return" .

Dans ce mode, [...]=return(...) renvoie les variables de l'argument (...) dans l'environnement appelant sous les noms précisés dans [...] . Sinon, les variables de l'environnement interrompu sont protégées et non modifiables.

L'instruction pause est très utile en phase de mise au point ou de déboggage.

Il est possible de sortir du mode de pause en mettant fin à l'exécution en tapant "abort" .

See Also

halt , return , abort , quit , whereami , where ,


percent (%)

Scilab Function
Last update : 16/06/2004

percent (%) - caractère spécial

Description

Certains noms de variables prédéfinies commencent par le caractère % , tels que %i (pour sqrt(-1) ), %inf (pour Infinity ), %pi (pour 3.14... ), %T (pour la constante booléene "true"="vrai" ),...

De plus, les fonctions dont les noms commencent par % sont spéciales : elles sont utilisées pour surcharger les primitives et opérateurs usuels (voir overloading ).

Par exemple la fonction %rmr calcule la multiplication (opérateur m ) x*y pour des matrices rationnelles x et y (type r ). Les conventions de codage sont précisées dans le fichier README du répertoire SCIDIR/macros/percent .

Examples

x1=tlist('x',1,2);
x2=tlist('x',2,3);
deff('x=%xmx(x1,x2)','x=list(''x'',x1(2)*x2(2),x2(3)*x2(3))');
x1*x2

See Also

overloading ,


plus (+)

Scilab Operator
Last update : 16/06/2004

plus (+) - opérateur d'addition

Calling Sequence

X+Y
str1+str2

Parameters

  • X,Y : matrice réelle, complexe, polynomiale, rationnelle ou liste de type syslin
  • str1,str2 : chaîne de caractères ou matrice de chaînes de caractères

Description

Addition.

Pour des opérandes numériques l'addition a la signification habituelle. Si l'un des opérandes est une matrice et l'autre un scalaire, ce dernier est ajouté à tous les termes de la matrice. Si l'un des opérandes est une matrice vide, le résultat est égal à l'autre opérande (ce comportement par défaut peut être modifié avec mtlb_mode ).

Pour les chaînes de caractères + désigne la concaténation.

L'addition peut être redéfinie pour de nouveaux types d'objets en utilisant la surcharge d'opérateurs (voir overloading ).

Examples

[1,2]+1
[]+2
s=poly(0,"s");
s+2
1/s+2
"conca"+"tener"

See Also

addf , mtlb_mode , overloading ,


poly

Scilab Function
Last update : 16/06/2004

poly - définition d'un polynôme

Calling Sequence

[p]=poly(a,"x", ["flag"])

Parameters

  • a : matrice ou nombre réel
  • x : indéterminée du polynôme
  • "flag" : chaîne de caractères ("roots", "coeff"), la valeur par défaut est "roots".

Description

Si a est une matrice, p est le polynôme caractéristique de a, c'est à dire déterminant(x*eye()-a) , x étant l'indéterminée.

Si v est un vecteur, poly(v,"x",["roots"]) est le polynôme dont les racines sont égales aux termes de v et "x" l'indéterminée. Dans ce cas roots et poly sont des fonctions inverses l'une de l'autre.

poly(v,"x","coeff") crée le polynôme d'indéterminée "x" dont les coefficients sont les termes de v (v(1) est le terme constant). Dans ce dernier cas, poly et coeff sont des fonctions inverses l'une de l'autre.

s=poly(0,"s") permet de définir des polynômes en utilisant les opérations usuelles (+,-,*,^). "s" .

Examples

s=poly(0,"s");p=1+s+2*s^2;
A=rand(2,2);poly(A,"x")

See Also

coeff , matrices , rational ,


power

Scilab Function
Last update : 16/06/2004

power - élévation à la puissance (^,.^)

Calling Sequence

t=A^b
t=A**b
t=A.^b

Parameters

  • A,t : matrice réelle, complexe, polynomiale ou rationnelle
  • b : matrice réelle, complexe, polynomiale ou rationnelle

Description

(A:matrice carrée)^(b:scalaire) : Si A est une matrice carrée et b un scalaire alors A^b est la matrice A élevée à la puissance b .
(A:matrice).^(b:scalaire) : Si b est un un scalaire et A une matrice alors A.^b est la matrice formée par les éléments de A élevés à la puissance b (puissance élément par élément). Si A est un vecteur et b un scalaire alors A^b et A.^b donnent le même résultat (puissance élément par élément).
(A:scalaire).^(b:matrice) Si A est un scalaire et b est une matrice A^b et A.^b sont deux matrices de même taille que b dont les termes sont égaux à a^(b(i,j)) .
(A:matrice).^(b:matrice) Si A et b sont des matrices de même taille A.^b est la matrice dont les termes sont égaux à A(i,j)^b(i,j) .

Notes :

- Pour les matrices carrées A^p est calculé par multiplications successives si p est un entier positif, et par diagonalisation sinon.

- Les opérateurs ** et ^ sont synonymes.

Examples

A=[1 2;3 4];
A^2.5,
A.^2.5
(1:10)^2
(1:10).^2

s=poly(0,'s')
s^(1:10)

See Also

exp ,


predef

Scilab Function
Last update : 21/11/2006

predef - protection de variables

Calling Sequence

n=predef()
oldnew=predef(n)
oldnew=predef('all')
oldnew=predef('clear')

Description

Function utilitaire permettant de déclarer comme "protégées" les variables "les plus anciennes". Les variables protégées ne peuvent pas être effacées. Elles ne sont pas non plus sauvées par la commande 'save' . Les variables "les plus anciennes" sont celles qui apparaissent avec la commande who('get') .

predef() renvoie le nombre de variables protégées.

predef('a[ll]') protège toutes les variables et renvoie l'ancien et le nouveau nombre de variables protégées.

predef('c[lear]') enlève la protection de toutes les variables sauf les 7 définies dernièrement. Renvoie l'ancien et le nouveau nombre de variables protégées.

predef(n) protège les max(n,7) variables définies dernièrement. Renvoie l'ancien et le nouveau nombre de variables protégées.

Remarques

Le nombre de variables protégées est défini dans le fichier de démarrage SCI/scilab.star . L'utilisateur a la possibilité de définir ses propres variables protégées dans les fichiers de démarrage SCIHOME/.scilab et SCIHOME/scilab.ini .

Définition de SCIHOME : Sous Windows : C:/Documents and Settings/<User>/Scilab/<Scilab-Version> Sous Linux/Unix : /home/<User>/.Scilab/<Scilab-Version>

See Also

clear , save ,


pwdgetcwd

Scilab command
Last update : 23/06/2004

pwd - affiche le répertoire courant de Scilab

getcwd - renvoie le répertoire courant de Scilab

Calling Sequence

pwd
x=pwd()
x=getcwd()

Description

pwd renvoie dans ans le répertoire courant de Scilab. x=pwd() ou x=getcwd() renvoie dans x le répertoire courant de Scilab.

Examples

    pwd
    x=pwd()

See Also

chdir , cd ,


quit

Scilab Function
Last update : 16/06/2004

quit - décrémente le niveau de pause ou quitte Scilab

Description

quit décrémente le niveau de pause ou quitte Scilab, si l'on se trouve au niveau principal.

See Also

pause , break , abort , exit ,


quote (')

Scilab Function
Last update : 16/06/2004

quote (') - opérateur de transposition, délimiteur de chaîne de caractères

Description

L'apostrophe ou "quote" ( ' ) est utilisé pour noter la transposition (conjuguée) des matrices.

Le symbole ( .' ) doit être utilisé pour une transposition non conjuguée.

L'apostrophe (') ou le guillemet (") sont aussi utilisés pour délimiter les chaînes de caractères (une chaîne de caractères est définie entre deux apostrophes ou guillemets). Une apostrophe ou un guillemet doivent être doublés s'ils font partie de la chaîne de caractères elle même.

Examples

[1+%i, 2]'
[1+%i, 2].'
x='Ceci est une chaîne de caractères'
'Et Dieu dit : ''que la lumière soit'''


rational

Scilab Objects
Last update : 16/06/2004

rational - Objet Scilab, fraction rationnelle

Description

Une fraction rationnelle r est le quotient de deux polynômes r=num/den . La représentation interne d'une fraction rationnelle est une liste : r=tlist('['r','num','den','dt'],num,den,[]) est identique à r=num/den . Une matrice de fractions rationnelles peut être définie en utilisant la syntaxe habituelle : [r11,r12;r21,r22] est une matrice 2x2 ou les rij sont des fractions rationnelles. Une matrice de fractions rationnelles peut aussi être définie comme précédemment : tlist(['r','num','den','dt'],num,den,[]) avec num et den deux matrices polynomiales.

Examples

s=poly(0,'s');
W=[1/s,1/(s+1)]
W'*W
Num=[s,s+2;1,s];Den=[s*s,s;s,s*s];
tlist(['r','num','den','dt'],Num,Den,[])
H=Num./Den
syslin('c',Num,Den)
syslin('c',H)
[Num1,Den1]=simp(Num,Den)

See Also

poly , syslin , simp ,


resume

Scilab Function
Last update : 16/06/2004

resume - sortie d'une fonction ou reprise d'exécution, avec récupération de variables locales

Calling Sequence

resume
[x1,..,xn]=resume(a1,..,an)

Parameters

  • x

Description

Dans une fonction resume termine son exécution et [..]=resume(..) renvoie les variables locales ai dans l'environnement appelant sous les noms xi .

En mode de pause , cela permet de reprendre l'exécution et [..]=resume(..) renvoie les variables locales ai dans l'environnement appelant sous les noms xi .

Utilisé dans l'argument de execstr appelé dans une fonction [..]=resume(..) termine l'exécution de la fonction et renvoie les variables locales ai dans l'environnement appelant sous les noms xi .

resume est équivalent à return .

See Also

abort , break , return ,


return

Scilab Function
Last update : 16/06/2004

return - sortie d'une fonction ou reprise d'exécution, avec récupération de variables locales

Calling Sequence

return
[x1,..,xn]=return(a1,..,an)

Parameters

  • x

Description

Dans une fonction return termine son exécution et [..]=return(..) renvoie les variables locales ai dans l'environnement appelant sous les noms xi .

En mode de pause , cela permet de reprendre l'exécution et [..]=return(..) renvoie les variables locales ai dans l'environnement appelant sous les noms xi .

Utilisé dans l'argument de execstr appelé dans une fonction, [..]=return(..) termine l'exécution de la fonction et renvoie les variables locales ai dans l'environnement appelant sous les noms xi .

return est équivalent à resume .

See Also

abort , break , resume ,


rlist

Scilab Function
Last update : 16/06/2004

rlist - définition d'une fraction rationnelle

Calling Sequence

rlist()
rlist(a1,....an)

Description

rlist(a1,....an) est équivalent à tlist(['r','num';'den','dt'], a1,....an)

Crée une tlist avec ['r','num';'den','dt'] comme premier argument et les ai comme termes suivants s'ils sont présents dans les arguments. Aucune vérification de type ou de taille n'est faite sur les ai .

See Also

tlist , syslin ,


sciargs

Scilab Function
Last update : 16/06/2004

sciargs - arguments sur la ligne de commande Scilab

Calling Sequence

args=sciargs()

Description

Cette fonction renvoie un vecteur de chaînes de caractères contenant les arguments de la commande de lancement de Scilab. Le premier terme du vecteur args contient le nom complet (avec le chemin) du fichier exécutable de Scilab.

Cette fonction correspond à la fonction getarg en langage C.

See Also

getenv ,


select

Scilab Function
Last update : 16/06/2004

select - mot-clé utilisé dans une structure select ... case

Description

Mot-clé utilisé dans une structure select ... case , à utiliser de la façon suivante :

 select expr,
   case expr1 then instructions1,
   case expr2 then instructions2,
   ...
   case exprn then instructions,
   [else instructions],
 end

Notes :

- La seule contrainte est que chaque mot-clé "then" soit sur la même ligne que le "case" correspondant.
- Le mot-clé then peut être remplacé par un passage à la ligne ou une virgule. Les instructions1 sont exécutées si expr1=expr , etc.

Attention : le nombre de caractères constituant le corps d'une instruction conditionnelle (if while for ou select/case) est limité à 16k..

Examples

while %t do
  n=round(10*rand(1,1))
  select n
  case 0 then
    disp(0)
  case 1 then
    disp(1)
  else
    break
  end
end

See Also

if , while , for ,


semicolon (;)

Scilab Function
Last update : 16/06/2004

semicolon (;) - séparateur de lignes ou d'instructions Scilab

Description

Les points-virgules sont utilisés pour séparer des lignes dans une définition de matrice.

Les points-virgules sont utilisés aussi pour marquer la fin d'une instruction. Dans ce cas le résultat n'est pas affiché. On peut utiliser à la place une virgule (,) qui permet de séparer les instructions sans supprimer l'affichage.

Examples

a=[1,2,3;4,5,6];
a=1;b=1,c=2

See Also

comma , brackets ,


semi (;)

Scilab Function
Last update : 16/06/2004

semi (;) - séparateur de lignes ou d'instructions Scilab

Description

Les points-virgules sont utilisés pour séparer des lignes dans une définition de matrice.

Les points-virgules sont utilisés aussi pour marquer la fin d'une instruction. Dans ce cas le résultat n'est pas affiché. On peut utiliser à la place une virgule (,) qui permet de séparer les instructions sans supprimer l'affichage.

Examples

a=[1,2,3;4,5,6];
a=1;b=1,c=2

See Also

comma , brackets ,


setenv

Fonction Scilab
Last update : 08/06/2005

setenv - fixe la valeur d'une variable d'environnement

Calling Sequence

rep=setenv(nom, valeur )

Parameters

  • nom : chaîne de caractères contenant le nom de la variable d'environnement
  • valeur : chaîne de caractères contenant la valeur de la variable d'environnement
  • rep : retourne %T si la variable d'environnement a ete cree ou %F dans le cas contraire

Description

Fixe la valeur d'une variable d'environnement.

Examples

 setenv('chaine','exemple')
 getenv('chaine')

See Also

getenv ,

Author

Allan CORNET


setfield

Scilab Function
Last update : 16/06/2004

setfield - insertion dans un champ d'une liste

Calling Sequence

setfield(i,x,l)

Parameters

  • x : matrice de tout type
  • l : variable de type list, tlist ou mlist
  • i : indice de champ, voir insertion pour plus de détails.

Description

Cette fonction est équivalente à la syntaxe l(i)=x pour l'extraction avec la seule différence qu'elle s'applique aussi aux objets de type mlist .

Examples

l=list(1,'qwerw',%s)
l(1)='change'
l(0)='ajoute'
l(6)=['un de plus';'ajoute']
//

a=hypermat([2,2,2],rand(1:2^3));// les hypermatrices sont des mlist
setfield(3,1:8,a);a // affectation du champ

See Also

insertion ,


slash (/)

Scilab Function
Last update : 16/06/2004

slash (/) - division à droite et feedback

Description

Division à droite. x=A / b est la solution de x*b=A .

b/a = (a' \ b')' .

a ./ b est la matrice dont les termes sont égaux à a(i,j)/ b(i,j) . Si b est un scalaire (matrice 1x1) cette opération est la même que a./b*ones(a) (même convention si a est un scalaire).

Notez que 123./b est interprété comme (123.)/b . Dans un tel cas le point fait partie du nombre et non pas de l'opérateur.

L'anti-slash ("contre-barre" ou backslash) signifie quant à lui la division à gauche (voir backslash ).

Feedback de systèmes dynamiques. S=G/.K évalue S=G*(eye()+K*G)^(-1) . Cet opérateur évite des problèmes de simplification.

Notez aussi que G/.5 est interprété comme G/(.5) . Dans un tel cas le point fait partie du nombre et non pas de l'opérateur.

La suite de symboles // met une ligne en commentaire, c'est à dire, les lignes commençant par // sont ignorées par l'interpréteur.

See Also

inv , percent , backslash , ieee ,


stacksize

Scilab Function
Last update : 16/06/2004

stacksize - change la taille de la pile Scilab

Calling Sequence

stacksize(n)
sz=stacksize()

Parameters

  • n : entier, la taille de pile désirée, en nombre de mots double-précision words
  • sz : vecteur à deux composantes [taille_totale taille_utilisée]

Description

Scilab stocke les variables usuelles dans une pile stk (pour les variables globales voir gstacksize ).

stacksize(n) permet d'augmenter ou de diminuer la taille de cette pile. La taille maximum dépend de la mémoire (physique ou virtuelle) restante.

Avec l'argument n cette fonction peut maintenant être utilisée n'importe où.

sz=stacksize() renvoie un vecteur à deux composantes contenant la taille totale de la pile et la taille actuellement utilisée. Elle peut être utilisée n'importe où.

See Also

who , gstacksize ,


star (*)

Scilab Function
Last update : 16/06/2004

star (*) - opérateur de multiplication

Description

Multiplication. Signification habituelle. Valide pour les matrices réelles, complexes, polynomiales, rationnelles et pour les listes de type syslin (dans ce dernier cas "*" désigne une connection en série).

La multiplication élément par élément est notée x.*y . Si x ou y est un scalaire (matrice 1x1) .* est équivalent à * .

Le produit de Kronecker se note x.*.y

See Also

mulf , syslin ,


symbols

Scilab Function
Last update : 16/06/2004

symbols - noms des opérateurs dans l'aide de Scilab

Description

Utilisez les noms suivants pour obtenir de l'aide sur un symbole particulier :

opérateur | nom dans l'aide de Scilab
',", .' | quote
+ | plus
- | minus
*,.* | star
/, ./, /. | slash
\, .\ ,\. | backslash
. | dot
=, == | equal
<,>,>=,<=,<> | less
~ | tilda
[ | left
] | right
() | parents
% | percent
: | colon
, | comma
; | semi
^ | hat
.^ | power
| | or
& | and
.*., ./., .\. | kron

See Also

overloading ,


testmatrix

Scilab Function
Last update : 16/06/2004

testmatrix - génération de matrices remarquables

Calling Sequence

[y]=testmatrix(name,n)

Parameters

  • name : chaîne de caractères
  • n : entier
  • y : matrice n x n

Description

Génère certaines matrices carrées particulières.

testmatrix('magi',n) : renvoie un carré magique de taille n .
testmatrix('frk',n) : renvoie la matrice de Franck :
testmatrix('hilb',n) : renvoie l'inverse de la matrice de Hilbert de taille n x n (Hij= 1/(i+j-1)) .


then

Scilab Function
Last update : 16/06/2004

then - mot-clé dans une structure if-then-else

Description

Utilisé avec if .

See Also

if ,


tic

Fonction Scilab
Last update : 10/06/2004

tic - Démarre le chronomètre

Calling Sequence

tic()

Description

La séquence de commandes tic(); opération; toc(); affiche le nombre de secondes nécessaire pour opération.

Examples

tic();
realtimeinit(1);
realtime(0);
realtime(10);
toc();

See Also

toc , timer , etime ,

Authors

V.C.
A.C.


tilda (~)

Scilab Function
Last update : 16/06/2004

tilda (~) - négation logique

Calling Sequence

~m

Parameters

  • m : matrice booléenne

Description

~m est la négation logique de m .


tlist

Scilab Function
Last update : 16/06/2004

tlist - Objet Scilab. Définition d'une liste typée

Calling Sequence

tlist(typ,a1,....an )

Parameters

  • typ : chaîne de caractères ou matrice de chaînes de caractères
  • ai : objet Scilab ( matrice, liste, chaîne... ).

Description

Crée une liste typée avec les éléments ai . L'argument typ spécifie le nom du type. L'utilisateur peut redéfinir les opérateurs et primitives de Scilab pour ces nouveaux objets à l'aide de fonctions Scilab (voir overloading ). La seule différence entre les listes typées et les listes (voir list ) est la valeur numérique du type (16 au lieu de 15).

typ(1) spécifie le nom du type (cette chaîne de caractères est utilisée dans les noms des fonctions surchargeant les opérateurs et primitives).

S'il est spécifié, typ(i) donne le nom formel de l'élément i+1 (voir plus bas dans les exemples).

Les opérations standard sur les listes fonctionnent similairement pour les listes typées (tlist).

extraction : [x,y,z...]=l(v) ou v est un vecteur d'indices; [x,y,z]=l(:) extrait tous les éléments.

insertion : l(i)=a

suppression : l(i)=null() supprime le i-ème élément de la tlist l .

affichage

De plus si les composantes typ(2:n+1) sont spécifiées, les éléments peuvent être désignés par leur noms formels.

Voici quelques exemples d'utilisation des liste typées :

Dans Scilab, les systèmes dynamiques linéaires sont définis par une liste typée : le quadruplet [A,B,C,D] est représenté par la tlist Sys=tlist(['lss';'A';'B';'C';'D';'X0';'dt'],A,B,C,D,x0,'c') et cette tlist spécifique est créée par la fonction syslin .

Sys(2), Sys('A') ou Sys.A est la matrice d'état et Sys('dt') ou Sys.dt est le domaine temporel.

Une matrice rationnelle H est représentée par la tlist H=tlist(['r';'num';'den';'dt'],Num,Den,[]) où Num et Den sont deux matrices polynomiales et un système dynamique linéaire (en temps continu) peut être créé sous la forme d'une matrice de transfert H par syslin('c',H) .

H(2), H('num') ou H.num est le numérateur de la matrice de transfert

See Also

null , percent , syslin , list ,


toc

Fonction Scilab
Last update : 10/06/2004

toc - Lit le chronomètre

Calling Sequence

toc()
t = toc()

Parameters

  • t : nombre de secondes depuis le dernier appel à tic() (Précision de l'ordre de la milliseconde).

Description

La séquence de commandes tic(); opération; toc(); affiche le nombre de secondes nécessaire pour opération.

Examples

tic();
realtimeinit(1);
realtime(0);
realtime(10);
toc();

See Also

tic , timer , etime ,

Authors

V.C.
A.C.


trycatch

Scilab keyword
Last update : 17/08/2006

try - mot clé de début du block try dans une instruction de contrôle try-catch

catch - mot clé de début du block catch dans une instruction de contrôle try-catch

Calling Sequence

try
statements
catch
statements
end

Description

L'instruction de contrôle try - catch peut être utilisée pour controler les conséquence d'une erreur d'éxécution en permettant l'éxécution de code spécifique en cas d'erreur.

Quand une instruction de contrôle try - catch est exécutée, normalement seules les instructions comprises entre les mots clés try et catch sont exécutées. Cependant, si une erreur se produit pendant l'exécution de ces instructions, l'erreur est mémorisée, les instructions restantes jusqu'au mot clé catch sont ignorées et les instructions comprises entre les mots clés catch et end sont exécutées en utilisant le mode de gestion des erreurs par défaut (voir: errcatch .

L'erreur mémorisé peut être retrouvée en utilisant la fonction lasterror .

Les intructions comprises entre les mots clés catch et end peuvent être omises ainsi que le mot clé catch si aucun code alternatif n'est fourni.

Notez que l'on peut aussi utiliser la fonction execstr avec l'argument 'errcatch' pour gérer les erreurs et tout particulièrement pour gérer les erreurs de syntaxe.

Examples

 file_path=TMPDIR+'/wrong'
 try
    u=mopen(file_path,'r')
    x=mget(10,'c',u)
  catch
    disp(['le fichier '+file_path+ 'ne peut pas être lu',
          'on utilise la valeur  par défaut de x'])
    x=1:10
  end
  [error_message,error_number]=lasterror(%t)

See Also

error , execstr , if , lasterror , errcatch ,

Author

Serge Steer, INRIA


typename

Scilab Function
Last update : 16/06/2004

typename - associe un nom à un type de variable

Calling Sequence

[types [ [,names]]=typename()
typename(name,type)

Parameters

  • types : vecteur colonne d'entiers, les codes des types de variables
  • names : vecteur colonne de chaînes de caractères, les noms associés à chaque code
  • type : entier, le code d'un nouveau type de variable
  • name : chaîne de caractères, le nom associé au nouveau type

Description

La surcharge des opérateurs et primitives utilise des noms formels associés à chaque type de variable pour former les noms des fonctions de surcharge (voir overloading ). typename peut être utilisé pour gérer ces noms pour les types natifs de variables (les noms formels pour les types tlist ou mlist sont définis autrement, pour ceci voir overloading ).

Sans argument d'entrée, typename renvoie les informations associées aux types de données déjà définis.

Avec les arguments d'entrée, typename associe un nom à un code de type de variable.

typename('',type) supprime le type de donnée défini par le code passé dans type dans la table des types de variables connus.

See Also

type , typeof , overloading , tlist , mlist ,


type

Scilab Function
Last update : 16/06/2004

type - type d'une variable

Calling Sequence

[i]=type(x)

Parameters

  • x : objet Scilab
  • i : entier

Description

type(x) renvoie un entier donnant le code numérique du type de x définit comme suit :

1 : matrice réelle ou complexe

2 : matrice polynomiale

4 : matrice booléenne

5 : matrice creuse

6 : matrice creuse booléene

8 : matrice d'entiers codés sur 1, 2 ou 4 octets

9 : matrice de "handle" sur les objets graphiques

10 : matrice de chaînes de caractères

11 : fonction non-compilée

13 : fonction compilée

14 : fonction d'une librairie

15 : liste

16 : liste typée (tlist)

17 : mlist

128 : pointeur

See Also

typeof ,


user

Scilab Function
Last update : 16/06/2004

user - interfaçage d'une routine Fortran ou C

Calling Sequence

[s_1,s_2,...,s_lhs]=user(e_1,e_2,...,e_rhs)

Description

Avec cette commande il est possible d'utiliser un programme externe comme une commande Scilab où (s_1,s_2,...,s_lhs) sont les variables de sortie et (e_1,e_2,...,e_rhs) sont les variables d'entrée. Pour utiliser cette commande dans Scilab il faut écrire quelques lignes dans la subroutine Fortran user de Scilab. Voir intersci ou la documentation de Scilab pour plus d'informations.

See Also

fort , link ,


varn

Scilab Function
Last update : 16/06/2004

varn - indéterminée d'un polynôme

Calling Sequence

[symb]=varn(p)
[pm]=varn(x,var)

Parameters

  • p : polynôme (ou matrice de polynômes)
  • symb : chaîne de caractères
  • x : polynôme (ou matrice de polynômes)
  • var : indéterminée du polynôme
  • pm : polynôme (ou matrice de polynômes)

Description

symb=varn(p) renvoie dans symb l'indéterminée du polynôme p (par exemple varn(poly(0,'x')) est égal à 'x' ).

varn(x,'s') renvoie une matrice polynomiale de même taille que x mais avec 's' comme indéterminée.

Examples

s=poly(0,'s');p=[s^2+1,s];
varn(p)
varn(p,'x')

See Also

horner , poly ,


what

Scilab Function
Last update : 06/10/2005

what - liste des primitives Scilab

Calling Sequence

what()
[primitives,commandes]=what();

Description

Liste des primitives et commandes de bas niveau.

Author

A.C


whereami

Scilab Function
Last update : 16/06/2004

whereami - donne l'arborescence d'appel de l'instruction courante

Calling Sequence

whereami()

Description

Affiche l'arborescence des appels jusqu'à l'emplacement courant, où se trouve l'appel à whereami(). Peut être utilisé suite à un appel à pause .

Examples

deff('y=test(a)',['y=sin(a)+1';
                  'y=t1(y)';
                  'y=y+1'])
deff('y=t1(y)',['y=y^2';'whereami()'])
test(1)

See Also

where , pause , errcatch ,


whereis

Scilab Function
Last update : 16/06/2004

whereis - nom de la librairie contenant une fonction

Calling Sequence

[librname]=whereis(function-name)

Description

Renvoie une chaîne de caractères contenant le nom de la librairie contenant la fonction function-name . Le chemin d'accès à la librairie peut être obtenu avec la fonction "librname" .

See Also

lib ,


where

Scilab Function
Last update : 16/06/2004

where - donne l'arborescence d'appel courante

Calling Sequence

[linenum,mac]=where()

Parameters

  • linenum : vecteur colonne d'entiers
  • mac : vecteur colonne de chaînes de caractères

Description

Renvoie linenum et mac tels que l'instruction courante a été appelée par la ligne linenum(1) de la fonction mac(1), mac(1) a été appelée par la ligne linenum(2) de la fonction mac(2) et ainsi de suite.

mac(i) est en général le nom d'une fonction mais il peut être égal à "exec" ou "execstr" si l'instruction est dans un script ou dans une chaîne argument de execstr.

See Also

whereami , pause ,


while

Scilab syntax and keyword
Last update : 17/06/2004

while - mot-clé utilisé dans une structure while ... end

Calling Sequence

while expr ,instructions,...[,else instructions], end
while expr do instructions,...[,else instructions], end
while expr then instructions,...[,else instructions], end

Description

Notes:
La seule contrainte est que chaque mot-clé then ou do soit sur la même ligne que le hile correspondant.
Les mot-clés then et do peuvent être remplacés par un passage à la ligne ou une virgule.
La construction ,else instructions permet de spécifier des instructions à exécuter si l'expression expr est fausse.

Attention : le nombre de caractères constituant le corps d'une instruction conditionnelle (if while for ou select/case) est limité à 16k..

Examples

    e=1; a=1; k=1;
    while norm(a-(a+e),1) > %eps, e=e/2; k=k+1; end
    e,k

See Also

for , select , break , return , pause ,


whos

Scilab Function
Last update : 30/11/2005

whos - liste des variables courantes dans un format détaillé

Calling Sequence

whos()
whos -type typ
whos -name nam

Parameters

  • typ : nom du type des variables sélectionnées (voir typeof )
  • nam : premiers caractères des noms des variables recherchées

Description

whos() affiche tous les noms des variables courantes, leurs types et la place mémoire occupée.

whos -type typ affiche tous les noms des variables courantes de type spécifié dans typ .

whos -name nam affiche tous les noms des variables courantes dont le nom commence par 'nam'

Remarque : si une variable est globale, le caractère * apparait devant son type.

Examples

whos()

whos -type boolean

whos -name %

See Also

who , typeof ,


who_user

Scilab Function
Last update : 12/01/2004

who_user - listing of user's variables

Calling Sequence

who_user()

Description

who_user displays user's variable names.

See Also

whos , who ,


who

Scilab Function
Last update : 16/06/2004

who - liste des variables

Calling Sequence

who
who()
names=who('local')
[names,mem]=who('local')
names=who('global')
[names,mem]=who('global')

Description

who affiche les noms des variables courantes.

who('local') ou who('get') renvoie les noms des variables courantes et l'occupation mémoire en nombre de flottants double précision.

who('global') renvoie les noms des variables globales courantes et l'occupation mémoire en nombre de flottants double précision.

See Also

whos , who_user ,


Librairie graphique
GlobalProperty - to customize the objects appearance (curves, surfaces...) in a plot or surf command.
Graphics - contenu de la librairie graphique
LineSpec - to quickly customize the lines appearance in a plot
Matplot - 2D plot of a matrix using colors
Matplot1 - 2D plot of a matrix using colors
Matplot_properties - description of the Matplot entities properties
Sfgrayplot - smooth 2D plot of a surface defined by a function using colors
Sgrayplot - smooth 2D plot of a surface using colors
addcolor - ajoute de nouvelles couleurs à la table des couleurs courante
alufunctions - description des modes de dessin des pixels.
arc_properties - description of the Arc entity properties
axes_properties - description of the axes entity properties
axis_properties - description of the axis entity properties
bar - histogramme de barres
barh - histogramme horizontal de barres
barhomogenize - homogeneise toutes les barres contenues dans les axes courrants de travail
black - Black's diagram (Nichols chart)
bode - Bode plot
champ - 2D vector field plot
champ1 - 2D vector field plot with colored arrows
champ_properties - description of the 2D vector field entity properties
chart - diagramme de Nichols
clear_pixmap - erase the pixmap buffer
clf - clear or reset the current graphic figure (window) to default values
color - returns the color id of a color
color_list - list of named colors
colorbar - draw a colorbar
colordef - Set default color values to display different color schemes
colormap - using colormaps
Compound_properties - description of the Compound entity properties
contour - level curves on a 3D surface
contour2d - level curves of a surface on a 2D plot
contour2di - calcule les courbes de niveau d'une surface
contourf - courbes de niveaux 2D remplies d'une surface 3D
copy - copy a graphics entity.
delete - delete a graphic entity and its children.
dragrect - déplace un ou plusieurs rectangles avec la souris
draw - draw an entity.
drawaxis - dessine un axe
drawlater - makes axes children invisible.
drawnow - draw hidden graphics entities.
driver - select a graphics driver
edit_curv - éditeur graphique interactif
errbar - ajoute des barres d'erreur sur un dessin 2D
eval3d - valeurs d'une fonction sur une grille
eval3dp - calcule les facettes d'une surface 3D paramétrique
evans - Evans root locus
fac3d - dessin en 3D d'une surface (obsolète)
fchamp - direction field of a 2D first order ODE
fcontour - level curves on a 3D surface defined by a function
fcontour2d - level curves of a surface defined by a function on a 2D plot
fec - dessin en pseudo-couleurs d'une surface définie sur une triangulation
fec_properties - description of the fec entities properties
fgrayplot - représentation 2D en pseudo-couleurs d'une surface définie par une fonction
figure_properties - description of the graphics figure entity properties
fplot2d - 2D plot of a curve defined by a function
fplot3d - 3D plot of a surface defined by a function
fplot3d1 - 3D gray or color level plot of a surface defined by a function
gainplot - magnitude plot
gca - Return handle of current axes.
gce - Get current entity handle.
gcf - Return handle of current graphic or GUI window.
gda - Return handle of default axes.
gdf - Return handle of default figure.
genfac3d - calcule les facettes d'une surface 3D non-paramétrique
geom3d - projection 3D vers 2D après une instruction de dessin 3D
get - Retrieve a property value from a graphics entity or an User Interface object.
getcolor - opens a dialog to show colors in the current colormap
getfont - dialog to select font
getlinestyle - dialog to select linestyle
getmark - dialog to select mark (symbol)
getsymbol - boîte de dialogue pour sélectionner un marqueur
glue - glue a set of graphics entities into an Compound.
gr_menu - petit éditeur graphique interactif
graduate - graduations simplifiées des axes 2D
figure_style - description of the graphics entities data structures
graphics_entities - description of the graphics entities data structures
nouveau graphique - description of the graphics entities data structures
old_style - description of the graphics entities data structures
graycolormap - linear gray colormap
grayplot - 2D plot of a surface using colors
grayplot_properties - description of the grayplot entities properties
graypolarplot - Polar 2D plot of a surface using colors
hist3d - représentation 3D d'un histogramme
histplot - dessine un histogramme
hotcolormap - red to yellow colormap
hsv2rgb - Converts HSV colors to RGB
hsvcolormap - Hue-saturation-value colormap
isoview - set scales for isometric plot (do not change the size of the window)
jetcolormap - blue to red colormap
label_properties - description of the Label entity properties
legend - draw graph legend
legend_properties - description of the Legend entity properties.
legends - dessine des légendes de courbes 2D
loadplots - loads and formats saved old style plots
locate - sélection avec la souris d'un ensemble de points
m_circle - M-circle plot
mesh - 3D mesh plot
milk_drop - représentation d'une goutte de lait
move - move, translate, a graphic entity and its children.
name2rgb - returns the RGB values of a named color
newaxes - Creates a new Axes entity
nf3d - conversion de facettes pour plot3d
nyquist - nyquist plot
graphic - description des capacités de l'éditeur graphique
graphique - description des capacités de l'éditeur graphique
menus - description des capacités de l'éditeur graphique
object_editor - description des capacités de l'éditeur graphique
oldplot - simple plot (old version)
param3d - 3D plot of a parametric curve
param3d1 - 3D plot of parametric curves
param3d_properties - description of the 3D curves entities properties
paramfplot2d - animation dans le plan d'une courbe définie par une fonction
pie - cercle graphique
plot - 2D plot
plot2d - 2D plot
plot2d1 - 2D plot (logarithmic axes) (obsolete)
plot2d2 - 2D plot (step function)
plot2d3 - 2D plot (vertical bars)
plot2d4 - 2D plot (arrows style)
plot2d_old_version - 2D plot reference
plot3d - 3D plot of a surface
plot3d1 - 3D gray or color level plot of a surface
plot3d2 - plot surface defined by rectangular facets
plot3d3 - mesh plot surface defined by rectangular facets
plot3d_old_version - 3D plot of a surface
plotframe - dessine un cadre avec graduations et définition de l'échelle
plzr - pole-zero plot
polarplot - Plot polar coordinates
polyline_properties - description of the Polyline entity properties
printing - impression des graphiques Scilab
rectangle_properties - description of the Rectangle entity properties
replot - redessine la fenêtre graphique courante en changeant les bornes
rgb2name - returns the name of a color
rotate - rotation d'un ensemble de points dans le plan
rubberbox - Rubberband box for rectangle selection
sca - set the current axes entity
scaling - transformation affine d'un ensemble de points
scf - set the current graphic figure (window)
sd2sci - conversion des sorties de gr_menu vers des instructions Scilab
sda - Set default axes.
sdf - Set default figure.
secto3d - conversion de surfaces 3D
segs_properties - description of the Segments entity properties
set - set a property value of a graphic entity object or of a User Interface object.
set_posfig_dim - change defaut transformation for exporting in postscript
sgrid - s-plane grid lines.
show_pixmap - send the pixmap buffer to the screen
square - échelle isométrique 2D (change la taille de la fenêtre)
stringbox - Calcule le rectangle englobant d'un texte ou d'un label.
subplot - divise une fenêtre graphique en sous-fenêtres
surf - 3D surface plot
surface_properties - description of the 3D entities properties
text_properties - description of the Text entity properties
title - display a title on a graphic window
titlepage - ajoute un titre au milieu d'une fenêtre graphique
twinkle - is used to have a graphics entity twinkle
unglue - unglue an agragation and replace it by individual children.
unzoom - unzoom graphics
winsid - renvoie la liste des fenêtre graphiques ouvertes
xarc - dessine un arc d'ellipse
xarcs - dessine des arcs d'ellipses
xarrows - dessine un ensemble de flèches
xaxis - dessine un axe
xbasc - efface une fenêtre graphique et efface les graphiques enregistrés
xbasimp - envoie des graphiques vers une imprimante ou un fichier Postscript
xbasr - redessine une fenêtre graphique
xchange - transformation de coordonnées de l'échelle courante en pixels et inversement
xclea - efface un rectangle
xclear - efface une fenêtre graphique
xclick - attend un appui sur un bouton de la souris
xclip - définit une zone de "clipping"
xdel - supprime des fenêtres graphiques
xend - termine la session graphique courante
xfarc - remplit un secteur angulaire d'ellipse
xfarcs - remplit des secteurs angulaires d'ellipses
xfpoly - remplit un polygone
xfpolys - fill a set of polygons
xfrect - remplit un rectangle
xget - récupère des valeurs du contexte graphique de la fenêtre courante
xgetech - récupération de l'échelle graphique courante
xgetmouse - get the mouse events and current position
xgraduate - graduation des axes
xgrid - ajoute une grille sur un dessin 2D
xinfo - affiche une chaîne de caractères dans la sous-fenêtre de messages
xinit - initialisation d'un pilote graphique
xlfont - load a font in the graphic context or query loaded font
xload - load a saved graphics
xname - change le nom de la fenêtre graphique courante
xnumb - dessine des nombres
xpause - interrompt Scilab pendant une durée donnée
xpoly - dessine une ligne brisée ou un polygone
xpolys - dessine un ensemble de lignes brisées ou de polygones
xrect - dessine un rectangle
xrects - dessine ou remplit un ensemble de rectangles
xrpoly - dessine un polygone régulier
xs2bmp - send graphics to a file in BMP syntax (Only for Windows)
xs2emf - send graphics to a file in EMF syntax (Only for Windows)
xs2eps - save graphics to a Postscript file.
xs2fig - send graphics to a file in Xfig syntax
xs2gif - send graphics to a file in GIF syntax
xs2ppm - send graphics to a file in PPM syntax
xs2ps - send graphics to a file in PS syntax
xsave - save graphics into a file
xsegs - dessine des segments non connectés
xselect - met la fenêtre graphique courante au premier plan
xset - change des valeurs du contexte graphique
xsetech - sélectionne la sous-fenêtre d'une fenêtre graphique pour les dessins
xsetm - boîte de dialogue pour changer des valeurs du contexte graphique
xstring - dessine des chaînes de caractères
xstringb - dessine des chaînes de caractères dans une boîte
xstringl - calcule les dimensions d'une boîte entourant des chaînes de caractères
xtape - détermine le processus d'enregistrement des graphiques
xtitle - add titles on a graphics window
zgrid - zgrid plot
zoom_rect - zoom a selection of the current graphic figure


addcolor

Scilab Function
Last update : 16/06/2004

addcolor - ajoute de nouvelles couleurs à la table des couleurs courante

Calling Sequence

new=addcolor(c)

Parameters

  • new : indices des nouvelles couleurs dans la nouvelle table des couleurs
  • c : matrice à trois colonnes. Définition des composantes RVB des nouvelles couleurs

Description

addcolor ajoute de nouvelles couleurs données dans l'argument c . c est une matrice à trois colonnes. [R V B] R est la composante rouge, V est la composante verte, B est la composante bleue. Chaque terme de c est un nombre positif inférieur ou égal à un.

Les indices des nouvelles couleurs sont renvoyés dans new .

Si une couleur dans c est déjà présente dans la table des couleurs courante, elle n'est pas ajoutée.

See Also

colormap ,


alufunctions

Scilab keyword
Last update : 16/06/2004

alufunctions - description des modes de dessin des pixels.

Description

src est la source c'est à dire la "valeur du pixel" que l'on veut dessiner. dst est la destination c'est à dire la "valeur du pixel" déjà présent à cet emplacement.

0: effacer i.e. "0"

1: ET i.e. "src ET dst"

2: ET inverse i.e. "src ET NON dst"

3: copie i.e. "src"

4: ET inverse i.e. "(NON src) ET dst"

5: rien i.e. "dst"

6: XOU (ou exclusif) i.e. "src XOU dst"

7: OU i.e. "src OU dst"

8: NOR "(NON src) ET (NON dst)"

9: équivalence i.e. "(NON src) OUX dst"

10: inversion i.e. "NON dst"

11: OU inverse i.e. "src OU (NON dst)"

12: copie inversée i.e. "NON src"

13: OU inverse i.e. "(NON src) OU dst"

14: NAND i.e. "(NON src) OU (NON dst)"

15: valeur affectée "1"


arc_properties

Scilab Data type
Last update : 16/12/2005

arc_properties - description of the Arc entity properties

Description

The Arc entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for ellipses and part of ellipses and the filled ones.

parent: This field contains the handle of the parent. The parent of the arc entity should be of the type "Axes" or "Compound" .
children: This property contains a vector with the children of the handle. However, arc handles currently do not have any children .
thickness: This field contains the line thickness property. Its value should be positive integer.
line_style: The line_style property value should be an integer in [1 6]. 1 stands for solid the other value stands for a selection of dashes.
line_mode: This property allows to display or not the line representing the arc. The value must be "on" or "off" .
fill_mode: If fill_mode property value is "on" , the arc is filled with the background color.
foreground: This field contains the default foreground property value used to draw or to fill arc. It should be a color index (relative to the current colormap).
background: This field contains the color used to fill the arc. It should be a color index (relative to the current colormap).
data: This property is to return the coordinates of the upper-left point, the width and the height of the inclosing rectangle as well as the boundary angles of the sector. It is the matrix [xleft,yup,[zup],width,height,a1,a2] where a1/64 and a2/64 are the sector boundary angles in degree.
visible: This field contains the visible property value for the entity . It should be "on" or "off" . If "on" the arc is drawn, If "off" the arc is not displayed on the screen.
clip_state: This field contains the clip_state property value for the arc. Clip_state value should be :
"off" this means that the arc is not clipped
"clipgrf" this means that the arc is clipped outside the Axes box.
"on" this means that the arc is clipped outside the arc given by property clip_box.
clip_box: This field is to determinate the clip_box property. By Default its value should be an empty matrix if clip_state is "off". Other cases the vector [x,y,w,h] (upper-left point width height) defines the portions of the arc to display, however clip_state property value will be changed.
user_data: This field can be use to store any scilab variable in the arc data structure, and to retreive it.

Examples

   set("figure_style","new") //create a figure
   a=get("current_axes");//get the handle of the newly created axes
   a.data_bounds=[-2,-2;2,2];

   xarc(-1.5,1.5,3,3,0,360*64)

   arc=get("hdl"); //get handle on current entity (here the arc entity)
   arc.fill_mode="on";
   arc.foreground=5;
   arc.data(:,[3 6])=[2 270*64];
   xfarc(-.5,1,.4,.6,0,360*64);
   arc.visible="off";

See Also

set , get , delete , xarc , xarcs , xfarc , xfarcs , graphics_entities ,

Author

Djalel ABDEMOUCHE


axes_properties

Scilab Data type
Last update : 09/03/2006

axes_properties - description of the axes entity properties

Description

The Axes entity is the second level of the graphics entities hierarchy. This entity defines the parameters allowing the change of coordinates and the axes drawing as well as the parameters' default values for the children creation.

Axes properties
parent: This field contains the handle of the parent figure.
children: FA vector containing the handles of all graphics objects children of the axes These graphics objects are of type "Compound" , "Rectangle" , "Polyline" , "Segs" , "Arc" , "Grayplot" ,.. (see Compound_properties , rectangle_properties , champ_properties , axis_properties , polyline_properties , segs_properties , grayplot_properties , surface_properties , param3d_properties , fec_properties , text_properties , legend_properties )
visible: This field contains the visible property value for axes . Its value should be "on" or "off" . By default, axes is visible "on" in case all "visible" chidren are displayed on the screen, If "off" the axes and all its chidren are not drawn.
axes_visible: A 1x3 string vector. This property specifies whether each axis is drawn or not. Its value should be "on" or "off" for a global setting.To act on a single axis, the syntax is axes_visible(N) where N is 1,2 or 3 corresponding to the x,y or z axis. The scaling data and if required the grids are drawn if the value is "on" . Note that when creating a simple axes entity using the gca() (shorcut for get"current_axes") ) or gcf() (shortcut for get(current_figure) ) commands, the axes visiblibilty is set to "off" .
axes_reverse: A 1x3 string vector corresponding to the three axes (X,Y,Z). For each axes, the property specifies the direction of the incresing values. If "off" , the default direction is used. If "on" , the direction is reverse. It is also possible to use only one string, "on" or "off" , to set simultaneously the three data.
grid: The field value is a vector [x-grid,y-grid,z-grid] where x-grid controls a grid drawning for the x-axis and y-grid, z-grid respecting to the y-axis, z-axis. The default values is -1 grids are not drawn, else the grids are drawn using the color given indexed by the grid value.
x_location: Specify the location of the x-axis. The possible values are:
"bottom" . In this case the x axis is drawn at the bottom of the axes rectangle.
"top" . In this case the x axis is drawn at the top of the axes rectangle.
"middle" . In this case the x axis is drawn at the position nearest to the 0 y coordinates.
y_location: Specify the location of the y-axis. The possible values are:
"left" . In this case the y axis is drawn at the left of the axes rectangle.
"right" . In this case the y axis is drawn at the right of the axes rectangle.
"middle" . In this case the y axis is drawn at the position nearest to the 0 x coordinates.
title: An object attached to the Axes entity and returning a graphic handle on a Label structure (see label_properties ). This field defines a title with options on this label.
x_label: An object attached to the Axes entity and returning a graphic handle on a Label structure (see label_properties ). This field defines a label on x axis with options on this label.
y_label: An object attached to the Axes entity and returning a graphic handle on a Label structure (see label_properties ). This field defines a label on y axis with options on this label.
z_label: An object attached to the Axes entity and returning a graphic handle on a Label structure (see label_properties ). This field defines a label on z axis with options on this label.
auto_ticks: A 1x3 string vector giving the auto_ticks status for each axis. This property specifies whether each axis is graduated using a computational algorithm or not (graduations are set by the user). Its value should be "on" or "off" for a global setting.To act on a single axis, the syntax is auto_ticks(N) where N is 1,2 or 3 corresponding to the x,y or z axis. Note that editing ticks (text and/or locations) via x_ticks, y_ticks or z_ticks automatically set auto_ticks to "off" for the corresponding axes.
x_ticks.locations: A real vector containing the locations for the graduations on x axis. This property can be edited specifying a new real vector (of the same size). To specify greater or lesser graduations, man can act on the x_ticks tlist defining a corresponding x_ticks.labels string vector too.
y_ticks.locations: A real vector containing the locations for the graduations on y axis. This property can be edited specifying a new real vector (of the same size). To specify greater or lesser graduations, man can act on the y_ticks tlist defining a corresponding y_ticks.labels string vector too.
z_ticks.locations: A real vector containing the locations for the graduations on z axis. This property can be edited specifying a new real vector (of the same size). To specify greater or lesser graduations, man can act on the z_ticks tlist defining a corresponding z_ticks.labels string vector too.
x_ticks.labels: A string vector containing the labels for the graduations on x axis. This property can be edited specifying a new string vector (of the same size). To specify greater or lesser graduations, man can act on the x_ticks tlist defining a corresponding x_ticks.locations real vector too.
y_ticks.labels: A string vector containing the labels for the graduations on y axis. This property can be edited specifying a new string vector (of the same size). To specify greater or lesser graduations, man can act on the y_ticks tlist defining a corresponding y_ticks.locations real vector too.
z_ticks.labels: A string vector containing the labels for the graduations on z axis. This property can be edited specifying a new string vector (of the same size). To specify greater or lesser graduations, man can act on the z_ticks tlist defining a corresponding z_ticks.locations real vector too.
box: This property specifies whether to enclose the axes in a box. Take as value "off" is to not display the box. The default is "on" .
sub_ticks: This field sets the number of tics to draw between two main tics. The field value is the vector [nx,ny] where nx is the number of sub tics for the x-axis and ny respecting to the y-axis.
font_style: Specify the font used for displaying tics labels. Seven differents fonts are available : "Courrier", "Symbol", "Times", "Times Italic", "Times Bold", "User defined". The font_style property is an index in [0 6] which is associated to the previous font names.
font_size: An integer specifying the font size used to draw the tics labels.
font_color: This property determines the color of the tics labels.
isoview: This property is used to have isometric scales on the x, y and z axes (for exemple to make the display of the curve sin(x) versus cos(x) be a circle not an ellipse). Its value should be "on" or "off" . If the value is "on" , the axes data_bounds automatically change according to the corresponding figure figure_size property values.
cube_scaling:This property is used in 3d mode to have a rescaling of the x, y and z axes. Indeed, it allows the data to fit into a 1x1x1 cube ; the goal is to better display 3d graphics in case axes scales are very different from one to another. Its value should be "on" or "off" (which is the default value). In most cases, it helps generating Matlab-like 3d view.
view: This field is related to the graphics universe. It takes "3d" as value corresponding to the three-dimensional views. In the other case its value can be "2d" for initial 2d plotting (default value). This flag also depends on the plots the user enters : a plot3d command, for example, will switch the view flag from "2d" to "3d" .
rotation_angles: This field is the vector [alpha,theta] . These two values give the spherical coordinates of the observation points (in degree).
tight_limits: If this property value is "on" axes adapt to fit exactly with the minima and maxima values of the data_bounds . If this field value is "off" , axes may enlarge boundaries such as to produce pretty tics labels.
data_bounds: This field contains the boundary values for the x,y and z coordinates. It is the matrix [xmin,ymin,zmin;xmax,ymax,zmax] or [xmin,ymin;xmax,ymax] . Note that, to stricly have the specified data bounds, tight_limits must be set to "on" value (see above).
zoom_box: This field contains the current zoom box if any coordinates are given. It is an empty matrix (no zoom) or the vector [xmin,ymin,xmax,ymax] (defines a rectangle given by two opposite corners). The z coordinates is not yet taken into account.
margins: A vector [margin_left,margin_right,margin_top,margin_bottom] specifying the margins portion for this axes. This vector is composed of numbers between [0 1] with default: [0.125 0.125 0.125 0.125] (these numbers are ratio relatives to the corresponding figure figure_size property values).
axes_bounds: A vector [x_left,y_up,width,height] specifying the portion of figure used by this axes. Where x_left , y_up , width and height are numbers in [0 1] give respectively the position of the upper-left corner and the dimension of the axes (these numbers are ratio relative to the corresponding figure figure_size property values).
user_data: This field can be use to store any scilab variable in the axes data structure, and to retreive it.
Properties for high level functions

The plot , plot2dx , grayplot and matplot functions use the following properties to decide how to merge consecutive plots if this is not stated by the frameflag calling argument. The result of the merge is decided through these two following properties:

auto_clear: If this property value is equal to "on" , a call to a high level graphic will re-ininitialize the current axes and erase all its children before preforming the drawing. If the value is "off" the drawings will be added to current axes according to "auto_scale" property.
auto_scale: A property to update the axes data boundary. If value is "on" , a new plot will adapt the current axes properties to fit with previous and current plots. If its value is "off" the new plot will be drawn in the current axes data boundary.
Children's default values:
hiddencolor: This property controls the hidden parts' color. It takes as value an index relative to the current colormap. In another case, if it is a negative value, the hidden parts take the same colors as the surface
line_mode: This field contains the default line_mode property value for Segs Rectangle Legend Axis Plot3d Fac3d and Polyline objects. Its value should be "on" (default) or "off" .
line_style: This field contains the default line_style property value for Segs, Arcs, Rectangle and Polyline objects. line_style selects the type of line to be used to draw lines . Its value should be an integer in [0 6]. 0 and 1 stand for solid, the other values stand for a selection of dashes (see getlinestyle ).
thickness: This field contains the default thickness property value for all objects using line drawing. Its value should be positive integer.
mark_mode: This field contains the default mark_mode property value for Segs Rectangle Legend Axis Plot3d Fac3d and Polyline objects. Its value should be "on" or "off" (default).
mark_style: This field contains the default mark_style property value for Segs Rectangle Legend Axis Plot3d Fac3d and Polyline objects. mark_style selects the type of mark to be displayed. Its value should be an integer in [0 9] which stands for: dot, plus, cross, star, filled diamond, diamond, triangle up, triangle down, trefle and circle.
mark_size_unit: This field contains the default mark_size_unit property value for Segs Rectangle Legend Axis Plot3d Fac3d and Polyline objects. If mark_size_unit is set to "point" , then the mark_size value is directly given in points. When mark_size_unit is set to "tabulated" , mark_size is computed relative to the font size array: therefore, its value should be an integer in [0 5] whith stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt. Note that plot2d and pure scilab functions use tabulated mode as default ; when using plot function, the point mode is automatically enabled.
mark_size: This field contains the default mark_size property value for Segs Rectangle Legend Axis Plot3d Fac3d and Polyline objects. mark_size selects the font size of mark to be displayed. Its value should be an integer in [0 5] whith stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt (see getmark ).
mark_foreground: This field contains the default mark_foreground property value for all objects created under this axes. Polyline, rectangle, legend, surface, segment and axis objects are using this property to specify a foreground (edge) color for their marks. Its value should be a color index (relative to the current color_map). Note that the default value is -1 (default black) and, even if you change the color_map , this -1 value will always point onto the default black color.
mark_background: This property controls the default mark_background property value for all objects created under this axes. Polyline, rectangle, legend, surface, segment and axis objects are using this property to specify a background (face) color for their marks. It takes as value an index relative to the current colormap.Note that the default value is -2 (default white) and, even if you change the color_map , this -2 value will always point onto the default white color.
foreground: This field contains the default foreground property value for axes and all objects created under this axes. Its value should be a color index (relative to the current color_map). Note that the default value is -1 (default black) and, even if you change the color_map , this -1 value will always point onto the default black color.
background: This property controls the default background property value for axes and all objects created under this axes. It takes as value an index relative to the current colormap.Note that the default value is -2 (default white) and, even if you change the color_map , this -2 value will always point onto the default white color.
clip_state: This field contains the default clip_state property value for all objects. Its value should be :
"off" this means that all objects created after that are not clipped (default value).
"clipgrf" this means that all objects created after that are clipped outside the Axes boundaries.
"on" this means that all objects created after that are clipped outside the rectangle given by property clip_box.
clip_box: This field contains the default clip_box property value for all objects. Its value should be an empty matrix if clip_state is "off" . Other case the clipping is given by the vector [x,y,w,h] (upper-left point width height).
Note on default values :
All these listed properties and fields inherit from default values stored in an axes model. These default values can be seen and changed. To do so, use the get("default_axes") command : it returns a graphic handle on the axes model. Note that no graphic window is created by this command. The next created axes will inherit from this model (see "Example on axes model" below).

Examples

   lines(0) // disables vertical paging
   set("figure_style","new") //create a figure
   a=get("current_axes")//get the handle of the newly created axes
   a.axes_visible="on"; // makes the axes visible
   a.font_size=3; //set the tics label font size
   a.x_location="top"; //set the x axis position
   a.data_bounds=[-100,-2,-1;100,2,1]; //set the boundary values for the x, y and z coordinates.
   a.sub_tics=[5,0];
   a.labels_font_color=5;
   a.grid=[2,2];
   a.box="off";
   // Example with 3D axes
   clf(); //clear the graphics window
   x=0.1:0.1:2*%pi;plot2d(x-.3,sin(x)*7+.2);
   a=gca(); // get the handle of the current axes
   a.grid=[1 -1 -1]; //make x-grid
   a.rotation_angles=[70 250]; //turn the axes with giving angles
   a.grid=[1 6 -1]; //make y-grid
   a.view="2d"; //return te the 2d view
   a.box="off";
   a.labels_font_color=5;
   a.children.children.thickness=4;
   a.children.children.polyline_style=3;
   a.view="3d"; //return te the 3d view
   a.children.children.thickness=1;
   a.children.children.foreground=2;
   a.grid=[1 6 3]; //make z-grid
   a.parent.background=4;
   a.background=7;
   plot2d(cos(x)+1,3*sin(x)-3);
   plot2d(cos(x)+7,3*sin(x)+3);
   a.children(2).children.polyline_style=2;
   a.children(1).children.polyline_style=4;
   a.children(1).children.foreground=5;
   a.children(2).children.foreground=14;
   a.parent.figure_size= [1200,800];
   a.box="on";
   a.labels_font_size=4;
   a.parent.background=8;
   a.parent.figure_size= [400,200];
   a.rotation_angles=[0 260];
   delete(a.children(2));
   delete(); // delete current object
   a.labels_font_size=1;
   a.auto_clear= "on";
   x=0:0.1:2.5*%pi;plot2d(10*cos(x),sin(x));
   a=gca();
   a.rotation_angles=[45 45];
   a.data_bounds=[-20,-3,-2;20 3 ,2];
   xrect([-4 0.5 8 1]);
   a.auto_clear = "off" ;
   a.isoview="on"; // isoview mode
   xrect([-2 0.25 4 0.5]);
   a.children(1).fill_mode="on";
   a.axes_visible="off";
   a.children(1).data=[-2 0.25 -1 4 0.5];
   a.children(2).data=[-4 0.5 1 8 1];
   x=2*%pi*(0:7)/8;
   xv=[.2*sin(x);.9*sin(x)];yv=[.2*cos(x);.9*cos(x)];
   xsegs(10*xv,yv,1:8)
   s=a.children(1);
   s.arrow_size=1;
   s.segs_color=5;
   a.data_bounds //the boundary values for the x,y and z coordinates
   a.view="2d";
   a.data_bounds=[-10,-1; 10,1]; // set the boundary values for the two-dimensional views
   // Example on axes model
   da=gda() // get the handle on axes model to view and edit the fields
   // title by default
   da.title.text="My Default@Title"
   da.title.foreground = 12;
   da.title.font_size = 4;
   // x labels default
   da.x_label.text="x";
   da.x_label.font_style = 8;
   da.x_label.font_size = 2;
   da.x_label.foreground = 5;
   da.x_location = "middle";
   // y labels default
   da.y_label.text="y";
   da.y_label.font_style = 3;
   da.y_label.font_size = 5;
   da.y_label.foreground = 3;
   da.y_location = "right";
   da.thickness = 2;
   da.foreground = 7;
   // the plot
   x=(0:0.1:2*%pi)';
   plot2d(x,[sin(x),sin(2*x),sin(3*x)],style=[1,2,3],rect=[0,-2,2*%pi,2]);
   sda() // back to default axes model

See Also

lines , set , get , gca , gda , gcf , sda , sdf , scf , graphics_entities ,

Author

Djalel ABDEMOUCHE


axis_properties

Scilab Data type
Last update : 09/12/2005

axis_properties - description of the axis entity properties

Description

The Axis entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for axis scaling and appearance.

Axis properties
parent: This property contains the handle of the parent. The parent of the axis entity should be of the type "Axes" or "Compound" .
visible: This field contains the visible property value for the entity . It should be "on" or "off" . By default, the axis entity is visible, the value's property is "on" . If "off" , the axis is not drawn on the screen.
tics_direction: Specify the direction of the tics drawn under the horizontal axis and the vertical axis. The possible values of this property are:

"top" . In this case, tics are drawn at the top of the horizontal axis.

"bottom" . In this case, tics are drawn at the bottom of the horizantal axis.

"left" . In this case, tics are going left on the vertical axis.

"right" . In this case, tics are going right on the vertical axis.

The defaults values are "top" for the horizontal axis and "right" for vertical axis.

xtics_coord: This field represent the x-coordinate of the axis. It is a row vector containing values increasing from left to right which give tics positions for a horizontal axis. Other case, the entity is a vertical axis, this property contain a scale which defines the x-origin of the axis.
ytics_coord: This field represent the y-coordinate of the axis. It is a row vector containing values increasing from bottom to top which give tics positions for a vertical axis. Other case, the entity is a horizantal axis, this property contain a scale which defines the y-origin of the axis.
tics_color: The value of this properties is index of the color used to draw the axis'lines and tics.
tics_segment: This field contains a flag which controls the display of the base segment of the axis. The default is "on" , else if to not display it, the property takes "off" as value.
tics_style: This property describes how the tics are given. It is a string flag which can have these possible values:

"v" . It's the default value, In this case, tics positions are given by the row factor xtics_coord for horizontal axis ( ytics_coord for the vertical one).

"r" . In this case, tics positions are given by the vector [min,max,n] where n is the number of intervals.

"i" . In this case the vector given tics positions is of size 4, [k1,k2,a,n] then values are increasing between k1*10^a and k2*10^a , n is the number of intervals.

sub_tics: This field sets the number of tics to draw between two main tics.
tics_labels: This filed is a string matrix, which contains the strings to be drawn along the axis at tics positions.
labels_font_color: This property determines the color of the tics labels.
labels_font_size: An integer specifying the font size used to draw the tics labels.
clip_state: This field contains the clip_state property value for the arc. Clip_state value should be :

"off" this means that the axis is not clipped

"clipgrf" this means that the axis is clipped outside the Axes box.

"on" this means that the axis is clipped outside the arc given by property clip_box.

clip_box: This field is to determinate the clip_box property. By Default its value should be an empty matrix if clip_state is "off". Other cases the vector [x,y,w,h] (upper-left point width height) defines the portions of the axis to display, however clip_state property value will be changed.
user_data: This field can be use to store any scilab variable in the axis data structure, and to retreive it.

Examples

  set("figure_style","new") //create a figure
   a=get("current_axes");//get the handle of the newly created axes
   a.data_bounds=[-1,-1;10,10];

  drawaxis(x=2:7,y=4,dir='u');
  a1=a.children(1)
  a1.xtics_coord=[1 4 5  8 10];
  a1.tics_color=2;
  a1.labels_font_size=3;
  a1.tics_direction="bottom";
  a1.tics_labels= [" February" "May"  "june" "August"  "October"];

  drawaxis(x=1.2:1:10,y=5,dir='u',textcolor=13);
  a2=get("hdl")
  a2.sub_tics=0;
  a2.tics_segment="off";
  a2.ytics_coord=4;

  drawaxis(x=-1,y=0:1:7,dir='r',fontsize=10,textcolor=5,ticscolor=6,sub_int=10)
  a3=get("hdl");
  a3.tics_labels= 'B'  +string(0:7);
  a3.tics_direction="left";

See Also

set , get , delete , drawaxis , graphics_entities ,

Author

Djalel ABDEMOUCHE


barhomogenize

Fonction Scilab
Last update : 30/11/2005

barhomogenize - homogeneise toutes les barres contenues dans les axes courrants de travail

Calling Sequence

barhomogenize()
barhomogenize([h[,'style'[,'width']]])

Parameters

  • h : un pointeur sur les axes, (par defaut: h=gca() ).
  • style: une chaine, 'grouped' ou 'stacked' (par defaut: 'grouped').
  • width : (optionnel), un scalaire, qui defini l'epaisseur des barres (un pourcentage de l'epaisseur maximun autorisé pour une barre) (par defaut: width=0.8, i.e 80%).

Description

S'il y a plusieurs appels à la fonction bar, la fonction barhomogenize permet d'homogeneiser l'epaisseur et le style de toutes les barres (i.e de type polyline_style 6) contenues dans les axes de travail. Ces barres doivent avoir les meme abscisses (x data).

barhomogenize( ) : prends les valeurs suivantes par defaut: h=gca(), width=0.8, style='grouped'.

barhomogenize(h,...) : definit les axes courants dans lesquels le dessin sera réalisé.

barhomogenize(...,width,...) : definit l'epaisseur des barres, en pourcentage (generallement : 0<width<=1).

barhomogenize(...,style,...) : definit la façon dont les barres sont positionnées les unes par rapport aux autres. L'option style fixée à 'grouped' permet de centrer les polylines par rapport à leurs abscisses, et l'option style fixée à 'stacked' permet de les empiler.

Examples

// Premier exemple : creation d'une barre jaune(i.e une polyline de type polyline_style=6) et de 3 barres(i.e 3 polylines de type polyline_style=6)
subplot(2,3,1)
xtitle('ex1: creation of 1 yellow bar and  3 bars')
x=1:3; y1=1:3; y2=[4 3 5;6 7 8;9 10 11];
bar(x,y1,'yellow');bar(x,y2);
// homogeneisation des 4 barres avec l'option style fixée à  'grouped' (par défaut)
subplot(2,3,2)
xtitle('grouped homogenisation')
x=1:3; y1=1:3; y2=[4 3 5;6 7 8;9 10 11];
bar(x,y1,'yellow');bar(x,y2);
barhomogenize();
// homogeneisation des 4 barres avec l'option style fixée à  'stacked'
subplot(2,3,3)
xtitle('stacked homogenisation')
x=1:3; y1=1:3; y2=[4 3 5;6 7 8;9 10 11];
bar(x,y1,'yellow');bar(x,y2);
barhomogenize('stacked',1);

// Deuxieme exemple
// creation d'une barre (i.e une polyline de type polyline_style=6, avec un appel à  la fonction bar) et deux polylines (i.e 2 polylines de type polyline_style=1, avec un appel à  la fonction plot)
subplot(2,3,4)
xtitle('ex2: creation of 1 bar and 2 polylines')
x=1:10; y=sin(x)/2;
bar(x,y,'red')
x1=1:10;y1=[sin(x);cos(x)]
plot(x1,y1)
// modification du type polyline_style à  6 de la deuxieme polyline construite par plot (cette polyline devient une barre)
subplot(2,3,5)
xtitle('transformation of the second polyline to bar')
x=1:10; y=sin(x)/2;
bar(x,y,'red')
x1=1:10;y1=[sin(x);cos(x)]
plot(x1,y1)
e=gce(); e2=e.children(2); e2.polyline_style=6;
// homogeneisation de la première barre (construite par appel à  la fonction bar) et de la deuxieme barre (issue de la modification).
subplot(2,3,6)
xtitle('grouped homogenisation')
x=1:10; y=sin(x)/2;
bar(x,y,'red')
x1=1:10;y1=[sin(x);cos(x)]
plot(x1,y1)
e=gce(); e2=e.children(2); e2.polyline_style=6;
barhomogenize();
// change the style and the width
//barhomogenize('stacked',0.5);
//barhomogenize('stacked',1);

See Also

bar , polyline_properties ,

Author

Farid Belahcene


barh

Fonction Scilab
Last update : 30/11/2005

barh - histogramme horizontal de barres

Calling Sequence

barh(y)
barh(x,y)
barh([h],x,y [,width [,color [,style]]])

Parameters

  • h : un pointeur sur les axes, (par défaut: h=gca() ).
  • y : un scalaire, un vecteur de taille N, ou une matrice de taille N*M
  • x : un scalaire ou un vecteur de taille N, (si y est un vecteur alors x doit etre de meme longeur que y. Si y est une matrice alors x doit etre un vecteur de longeur egale au nombre de lignes de y).
  • width : (optionnel), un scalaire, définit l'épaisseur des barres (un pourcentage de l'epaisseur maximum autorisé pour une barre), par défaut: 0.8=80%.
  • color : (optionnel), une chaine (par défaut: 'blue'), specifiant la couleur intérieur des barres.
  • style: (optionnel), une chaine, 'grouped' or 'stacked' (par défaut: 'grouped').

Description

barh(y,...) : si y est un vecteur alors la fonction barh dessine une polyline de type polyline_style égale à 6, dans ce cas x =1 : length(y). Si y est une matrice de taille N*M, alors la fonction bar dessine M polylines de (type 6), chaque polyline correspond à une colonne de y est au vecteur x=1:size(y,1).

barh(x,y,...) : si y est un vecteur alors la fonction barh dessine une polyline de type polyline_style égale à 6, vérifiant: longeur de x length = longeur de y .Si y est une matrice de taille N*M, alors la fonction bar dessine M polylines de (type 6), chaque polyline correspond à une colonne de y est au vecteur x vérifiant longueur de x=size(y,1) (i.e nombre de ligne de y).

barh(h,...) : definit les axes courants ou le dessin est réalisé.

barh(...,width,...) : definit l'épaisseur des barres en pourcentage (générallement: 0<width<=1).

barh(...,style,...) : dans le cas ou y est une matrice l'option style definit la façon dont les barres sont dessinées les unes par rapport aux autres. Si y est une matice N*M (donc M polylines de type 6) alors il y a 2 façons de dessiner ces M barres. l'option 'grouped' permet de centrer les M polylines par rapport aux abscisses (i.e par rapport à chaque composantes de x), et l'option 'stacked' permet de les empiler.

barh(...,color,...) : definit la couleur des barres. La fonction bar utilise la meme colormap que la fonction plot .

S'il y a plusieurs appels à la fonction barh, la fonction barhomogenize permet d'homogénéiser l'épaisseur et le style de toutes les barres (i.e les polylines de type 6) inclus dans les axes courrants.

Examples

// Premier exemple : dessine juste une barre, width=0.5, color='yellow', par défaut x=1:length(y)
scf(0);
y=[1 -3 5];
barh(y,0.5,'yellow');

// Deuxième exemple : par défaut style='grouped'
scf(1);
x=[1 2 5]; y=[1  -5 6;3 -2 7;4  -3 8];
barh(x,y);

// Troisième exemple : dessine 3 barres (nombre de colonnes de y) style='stacked'.
scf(2);
x=[1 2 5]; y=[1 4 7;2 5 8;3 6  9];
barh(x,y,'stacked');

// Quatrième exemple; width=0.2;color='green'; par défaut style='grouped'
scf(3);
x=[1 2 5]; y=[1 4 7;2 5 8;3 6 9];
barh(x,y,0.2,'green');

See Also

bar , barhomogenize , plot , polyline_properties ,

Author

Farid Belahcene


bar

Fonction Scilab
Last update : 30/11/2005

bar - histogramme de barres

Calling Sequence

bar(y)
bar(x,y)
bar([h],x,y [,width [,color [,style]]])

Parameters

  • h : un pointeur sur les axes, (par défaut: h=gca() ).
  • y : un scalaire, un vecteur de taille N, ou une matrice de taille N*M
  • x : un scalaire ou un vecteur de taille N, (si y est un vecteur alors x doit etre de meme longeur que y. Si y est une matrice alors x doit etre un vecteur de longeur egale au nombre de lignes de y).
  • width : (optionnel), un scalaire, définit l'épaisseur des barres (un pourcentage de l'epaisseur maximum autorisé pour une barre), par défaut: width=0.8, i.e 80%.
  • color : (optionnel), une chaine (par défaut: 'blue'), specifiant la couleur de l'intérieur des barres.
  • style: (optionel), une chaine, 'grouped' or 'stacked' (par défaut: 'grouped').

Description

bar(y,...) : si y est un vecteur alors la fonction bar dessine une polyline de type polyline_style égale à 6, dans ce cas x =1 : length(y). Si y est une matrice de taille N*M, alors la fonction bar dessine M polylines de (type 6), chaque polyline correspond à une colonne de y est au vecteur x=1:size(y,1).

bar(x,y,...) : si y est un vecteur alors la fonction bar dessine une polyline de type polyline_style égale à 6, vérifiant: longeur de x = longeur de y .Si y est une matrice de taille N*M, alors la fonction bar dessine M polylines de (type 6), chaque polyline correspond à une colonne de y est au vecteur x vérifiant longueur de x=size(y,1) (i.e longueur de x = nombre de ligne de y).

bar(h,...) : definit les axes courants ou le dessin est réalisé.

bar(...,width,...) : definit l'épaisseur des barres en pourcentage (générallement: 0<width<=1).

bar(...,style,...) : dans le cas ou y est une matrice l'option style definit la façon dont les barres sont positionnées les unes par rapport aux autres. Si y est une matice N*M (donc M polylines de type 6) alors il y a 2 façons de dessiner ces M barres. l'option style fixée à grouped' permet de centrer les M polylines par rapport aux abscisses (i.e par rapport à chaque composantes de x), et l'option style fixée à 'stacked' permet de les empiler.

bar(...,color,...) : definit la couleur des barres. La fonction bar utilise la meme colormap que la fonction plot .

S'il y a plusieurs appels à la fonction bar, la fonction barhomogenize permet d'homogénéiser l'épaisseur et le style de toutes les barres (i.e les polylines de type 6) inclus dans les axes courrants.

Examples

// Premier exemple : dessine juste une barre, width=0.5, color='yellow', par défaut x=1:length(y)
scf(0);
y=[1 -3 5];
bar(y,0.5,'yellow');

// Deuxième exemple : par défaut style='grouped'
scf(1);
x=[1 2 5]; y=[1  -5 6;3 -2 7;4  -3 8];
bar(x,y);

// Troisième exemple : dessine 3 bars (nombre de colonnes de y) style='stacked'.
scf(2);
x=[1 2 5]; y=[1 4 7;2 5 8;3 6  9];
bar(x,y,'stacked');

// Quatrième exemple; width=0.2;color='green'; par défaut style='grouped'
scf(3);
x=[1 2 5]; y=[1 4 7;2 5 8;3 6 9];
bar(x,y,0.2,'green');

See Also

barh , barhomogenize , plot , polyline_properties ,

Author

Farid Belahcene


black

Scilab Function
Last update : 08/06/2005

black - Black's diagram (Nichols chart)

Calling Sequence

black( sl,[fmin,fmax] [,step] [,comments] )
black( sl,frq [,comments] )
black(frq,db,phi [,comments])
black(frq,repf [,comments])

Parameters

  • sl : list ( linear system syslin )
  • fmin,fmax : real scalars (frequency bounds)
  • frq : row vector or matrix (frequencies)
  • db,phi : row vectors or matrices (modulus, phase)
  • repf : row vectors or matrices (complex frequency response)
  • step : real
  • comments : string

Description

Black's diagram (Nichols'chart) for a linear system sl . sl can be a continuous-time or discrete-time SIMO system (see syslin ). In case of multi-output the outputs are plotted with different symbols.

The frequencies are given by the bounds fmin,fmax (in Hz) or by a row-vector (or a matrix for multi-output) frq .

step is the ( logarithmic ) discretization step. (see calfrq for the choice of default value).

comments is a vector of character strings (captions).

db,phi are the matrices of modulus (in Db) and phases (in degrees). (One row for each response).

repf matrix of complex numbers. One row for each response.

To plot the grid of iso-gain and iso-phase of y/(1+y) use chart() .

Default values for fmin and fmax are 1.d-3 , 1.d+3 if sl is continuous-time or 1.d-3 , 0.5 if sl is discrete-time.

Examples

s=poly(0,'s')
h=syslin('c',(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01))
chart();
sstr='(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01)';
black(h,0.01,100,sstr);
h1=h*syslin('c',(s^2+2*0.1*15.1*s+228.01)/(s^2+2*0.9*15*s+225))
clf()
black([h1;h],0.01,100,['h1';'h'])

See Also

bode , nyquist , chart , freq , repfreq , calfrq , phasemag ,


bode

Scilab Function
Last update : 08/06/2005

bode - Bode plot

Calling Sequence

bode(sl,[fmin,fmax] [,step] [,comments] )
bode(sl,frq [,comments] )
bode(frq,db,phi [,comments])
bode(frq, repf [,comments])

Parameters

  • sl : syslin list (SISO or SIMO linear system) in continuous or discrete time.
  • fmin,fmax : real (frequency bounds (in Hz))
  • step : real (logarithmic step.)
  • comments : vector of character strings (captions).
  • frq : row vector or matrix (frequencies (in Hz) ) (one row for each SISO subsystem).
  • db : row vector or matrix ( magnitudes (in Db)). (one row for each SISO subsystem).
  • phi : row vector or matrix ( phases (in degree)) (one row for each SISO subsystem).
  • repf : row vector or matrix of complex numbers (complex frequency response).

Description

Bode plot, i.e magnitude and phase of the frequency response of sl .

sl can be a continuous-time or discrete-time SIMO system (see syslin ). In case of multi-output the outputs are plotted with different symbols.

The frequencies are given by the bounds fmin,fmax (in Hz) or by a row-vector (or a matrix for multi-output) frq .

step is the ( logarithmic ) discretization step. (see calfrq for the choice of default value).

comments is a vector of character strings (captions).

db,phi are the matrices of modulus (in Db) and phases (in degrees). (One row for each response).

repf matrix of complex numbers. One row for each response.

Default values for fmin and fmax are 1.d-3 , 1.d+3 if sl is continuous-time or 1.d-3 , 0.5 if sl is discrete-time. Automatic discretization of frequencies is made by calfrq .

Examples

s=poly(0,'s')
h=syslin('c',(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01))
title='(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01)';
bode(h,0.01,100,title);
h1=h*syslin('c',(s^2+2*0.1*15.1*s+228.01)/(s^2+2*0.9*15*s+225))
clf()
bode([h1;h],0.01,100,['h1';'h'])

See Also

black , nyquist , gainplot , repfreq , g_margin , p_margin , calfrq , phasemag ,


champ1

Scilab Function
Last update : 08/06/2005

champ1 - 2D vector field plot with colored arrows

Calling Sequence

champ1(x,y,fx,fy,[arfact,rect,strf])

Parameters

  • x,y : two vectors which define the grid.
  • fx : a matrix which describes the x component of the vector field. fx(i,j) is the x component of the vector field at point (x(i),y(j)) .
  • fy : a matrix which describes the y component of the vector field. fy(i,j) is the y component of the vector field at point (x(i),y(j)) .
  • arfact : an optional argument of type real which gives a scale factor for the display of the arrow heads on the plot (default value is 1.0).
  • rect : a vector rect=[xmin,ymin,xmax,ymax] which gives the boundaries of the graphics frame to use.
  • frameflag : controls the computation of the actual coordinate ranges from the minimal requested values. The associated value should be an integer ranging from 0 to 8.
  • axesflag : specifies how the axes are drawn. The associated value should be an integer ranging from 0 to 5.
  • strf : a string of length 3 "xyz" which has the same meaning as the strf parameter of plot2d . The first character x has no effect with champ1 .

Description

champ1 draws a 2D vector field with colored arrows. The color of the arrows depends on the intensity of the field.

If you want arrows proportional to the intensity of the field, use champ .

Enter the command champ1() to see a demo.

Examples

champ1(-5:5,-5:5,rand(11,11),rand(11,11),rect=[-10,-10,10,10],arfact=2)

See Also

champ , fchamp , plot2d ,

Author

J.Ph.C.


champ_properties

Scilab Data type
Last update : 09/12/2005

champ_properties - description of the 2D vector field entity properties

Description

The Champ entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for a 2D vector field.

parent: This property contains the handle of the parent. The parent of the 2D vector field entity should be of the type "Axes" or "Compound" .
children: This property contains a vector with the children of the handle. However, champ handles currently do not have any children .
visible: This properties contains the visible property value for the entity . It should be "on" or "off" . If "on" the vector field is drawn, If "off" the vector field is not displayed on the screen.
data: This field defines a tlist data structure of type "champdata" composed of a row and column indices of each element : the x and y grid coordinates are contained respectively in data.x and data.y . The complementary fields named data.fx and data.fy are matrices which describe respectively the x and y component of the vector field at point (x(i),y(j)) .
line_style: The line_style property value should be an integer in [0 9]. 0 stands for solid the other value stands for a selection of dashes. This property applies to all lines used to draw the vector field.
thickness: This property contains the thickness property for all lines used to draw the vector field. Its value should be a non negative integer..
colored: If this this property value is "on" , fields vectors are drawn using a color proportional to the intensity of the field.
arrow_size: This positive defined the size of the triangle drawn at the end of the arrows. If the value is 0, no triangle is drawn.
clip_state: This field contains the clip_state property value for the champ. It should be :

"off" this means that the vector field is not clipped

"clipgrf" this means that the vector field is clipped outside the Axes box.

"on" this means that the vector field is clipped outside the rectangle given by property clip_box.

clip_box: This property contains the clip_box property. Its value should be an empty matrix if clip_state is "off" .Other cases the vector [x,y,w,h] (upper-left point width height) defines the portions of the vector field to display, however clip_state property value will be changed.
user_data: This field can be use to store any scilab variable in the champ data structure, and to retreive it.

Examples

  set("figure_style","new") //create a figure
   a=get("current_axes");//get the handle of the newly created axes
   a.data_bounds=[-10,-10;10,10];
   champ(-5:5,-5:5,rand(11,11),rand(11,11))

   c=a.children

   c.colored="on";
   c.thickness=2;
   c.data // display the tlist of type "scichampdata"
   a.data_bounds=[-5,-5;5,5];

See Also

set , get , delete , champ , champ1 , graphics_entities ,

Author

Djalel ABDEMOUCHE


champ

Scilab Function
Last update : 08/06/2005

champ - 2D vector field plot

Calling Sequence

champ(x,y,fx,fy,[arfact,rect,strf])
champ(x,y,fx,fy,<opt_args>)

Parameters

  • x,y : two vectors which define the grid.
  • fx : a matrix which describes the x component of the vector field. fx(i,j) is the x component of the vector field at point (x(i),y(j)) .
  • fy : a matrix which describes the y component of the vector field. fy(i,j) is the y component of the vector field at point (x(i),y(j)) .
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following: arfact, rect, strf (see below).
  • arfact : an optional argument of type real which gives a scale factor for the display of the arrow heads on the plot (default value is 1.0).
  • rect : a vector rect=[xmin,ymin,xmax,ymax] which gives the boundaries of the graphics frame to use.
  • strf : a string of length 3 "xyz" which has the same meaning as the strf parameter of plot2d . The first character x has no effect with champ .

Description

champ draws a 2D vector field. The length of the arrows is proportional to the intensity of the field.

If you want colored arrows with the color of the arrows depending on the intensity of the field, use champ1 .

Enter the command champ() to see a demo.

Examples

// using rect as plot boundaries
champ(-5:5,-5:5,rand(11,11),rand(11,11),rect=[-10,-10,10,10],arfact=2)
// using (x,y) to get boundaries
clf()
champ(-5:5,-5:5,rand(11,11),rand(11,11),2,[-10,-10,10,10],"021")

See Also

champ1 , fchamp , plot2d ,

Author

J.Ph.C.


chart

Scilab Function
Last update : 16/06/2004

chart - diagramme de Nichols

Calling Sequence

chart([flags])
chart(gain [,flags])
chart(gain,phase [,flags])

Parameters

  • gain : valeurs réelles ( gains (en DB))
  • phase : valeurs réelles (phases (en degrés))
  • flags : une liste de 4 termes list(sup [,leg [,cm [,cphi]]])
    • sup : 1 -> superposition sur le dessin précédent 0 -> pas de superposition
    • leg : 1 indique que les légendes sont dessinées, 0 : pas de légendes
    • cm : numéro de couleur (voir plot2d) pour les courbes de gain
    • cphi : numéro de couleur (voir plot2d) pour les courbes de phase

Description

Dessine un diagramme de Nichols

Les valeurs par défaut pour gain et phase sont respectivement :

[-12 -8 -6 -5 -4 -3 -2 -1.4 -1 -.5 0.25 0.5 0.7 1 1.4 2 2.3 3 4 5 6 8 12]

[-(1:10) , -(20:10:160)]

Examples

s=poly(0,'s')
h=syslin('c',(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01))
black(h,0.01,100,'(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01)')
chart(list(1,0,2,3));

// Un autre exemple :

xbasc()
h1=h*syslin('c',(s^2+2*0.1*15.1*s+228.01)/(s^2+2*0.9*15*s+225))
black([h1;h],0.01,100,['h1';'h'])
chart([-8 -6 -4],[80 120],list(1,0));


clear_pixmap

Scilab Function
Last update : 08/06/2005

clear_pixmap - erase the pixmap buffer

Calling Sequence

clear_pixmap()

Description

If a graphic window pixmap property is "on" the drawings are send to a pixmap memory instead of the screen display.

The clear_pixmap() instruction erase the pixmap, but not the screen.

The pixmap mode can be used to obtain smooth animations.

See Also

figure_properties , show_pixmap ,

Author

Serge Steer INRIA


clf

Scilab Function
Last update : 08/06/2005

clf - clear or reset the current graphic figure (window) to default values

Calling Sequence

clf(<opt_job_arg>)
clf(h,<opt_job_arg>)
clf(num,<opt_job_arg>)

Parameters

  • h : a handle, the figure handle
  • num : a number, the figure_id
  • <opt_job_arg> : a string ( 'clear' or 'reset' ) specifying the job for clf .

Description

The clf command is used to reset a figure to its default values and/or to delete all its children.

If opt_job_arg string value is 'clear' then all children of the specified figure are deleted.

If opt_job_arg string value is 'reset' then not only all children of the specified figure are deleted but the figure properties are reset to their default values using the default figure model (see gdf ).

clf(num) clear or reset and clear the figure with figure_id==num . Try not to specify an inexistant figure.

clf(h) clear or reset and clear the figure pointed to by the handle h . Try not to specify an inexistant figure.

clf() clear or reset and clear the current existing figure.

Examples

   f4=scf(4);  //creates figure with id==4 and make it the current one
   f4.color_map = jetcolormap(64);
   f4.figure_size = [400, 200];
   plot2d()
   clf(f4,'reset')
   f0=scf(0); //creates figure with id==0 and make it the current one
   f0.color_map=hotcolormap(128);
   plot3d1();
   clf() // equivalent to clf(gcf(),'clear')
   plot3d1();  // color_map unchanged
   clf(gcf(),'reset')
   plot3d1();  // color_map changed (back to the default one with 32 colors)

See Also

set , get , gcf , gdf , scf , graphics_entities ,

Author

S. Steer & F.Leray INRIA


colorbar

Scilab Function
Last update : 15/04/2005

colorbar - draw a colorbar

Calling Sequence

colorbar(umin, umax [, colminmax])

Parameters

  • umin : real scalar, the minimum value associated with the plot
  • umax : real scalar, the maximum value associated with the plot
  • colminmax : (optional) a vector with 2 integer components

Description

Draw a colorbar for a plot3d, fec, Sgrayplot, etc... The function may be called BEFORE the plot3d, fec, Sgrayplot,... because its sets and changes the frame for the plot. This way the colorbar is not part of the associated plot and so is not modified by a zoom or a rotation.

The optional argument colminmax may be used to precise the first color (associated with umin) and the the last color (associated with umax) of the current colormap. By default colminmax=[1 nb_colors] where nb_colors is the number of colors of the current colormap.

Examples

// example 1
x = linspace(0,1,81);
z = cos(2*%pi*x)'*sin(2*%pi*x);
zm = min(z); zM = max(z);
xbasc()
xset("colormap",jetcolormap(64))
colorbar(zm,zM)
Sgrayplot(x,x,z)
xtitle("The function cos(2 pi x)sin(2 pi y)")

// example 2
x = linspace(0,1,81);
z = cos(2*%pi*x)'*sin(2*%pi*x);
zm = min(z); zM = max(z);
zz = abs(0.5*cos(2*%pi*x)'*cos(2*%pi*x));
zzm = min(zz); zzM = max(zz);
xbasc();
xset("colormap",jetcolormap(64))
new_styl = get("figure_style") == "new";
if new_styl then, drawlater(), end
subplot(2,2,1)
   colorbar(zm,zM)
   Sgrayplot(x,x,z, strf="031", rect=[0 0 1 1])
   xtitle("a Sgrayplot with a colorbar")
subplot(2,2,2)
   colorbar(zm,zM)
   plot3d1(x,x,z)
   xtitle("a plot3d1 with a colorbar")
subplot(2,2,3)
   colorbar(zzm,zzM)
   plot3d1(x,x,zz)
   xtitle("a plot3d1 with a colorbar")
subplot(2,2,4)
   colorbar(zzm,zzM)
   Sgrayplot(x,x,zz, strf="031", rect=[0 0 1 1])
   xtitle("a Sgrayplot with a colorbar")
if new_styl then, drawnow(), end

// example 3
x = linspace(0,1,81);
zz = abs(0.5*cos(2*%pi*x)'*cos(2*%pi*x));
zzm = min(zz); zzM = max(zz);
[xf,yf,zf]=genfac3d(x,x,zz);
nb_col = 64;
xbasc()
xset("colormap",hotcolormap(nb_col))
new_styl = get("figure_style") == "new";
if new_styl then, drawlater(), end
colorbar(zzm,zzM)
nbcol = xget("lastpattern")
zcol = dsearch(zf, linspace(zzm, zzM, nb_col+1));
plot3d(xf, yf, list(zf, zcol), flag = [-2 6 4])
xtitle("a plot3d with shaded interpolated colors")
if new_styl then, drawnow(), end
xselect()

See Also

colormap ,

Author

B. Pincon


colordef

Scilab Function
Last update : 14/06/2005

colordef - Set default color values to display different color schemes

Calling Sequence

colordef(color_scheme)
colordef(f,color_scheme)
colordef('new',color_scheme)

Parameters

  • color_scheme : a character string with possible value: 'white', 'black','none'
  • f : a handle on a graphic figure

Description

colordef('white') sets the default figure (see gdf ) colormap to jetcolormap(64) , the default figure background color to light gray and the default axes (see gda ) background color to white, the axes lines foreground and font color to black.
colordef('black') sets the default figure (see gdf ) colormap to jetcolormap(64) , the default figure background color to dark gray and the default axes (see gda ) background color to black, the axes lines foreground and font color to white.
colordef('none') sets the default figure (see gdf ) colormap to hsvcolormap(64) , the default figure background color to dark gray and the default axes (see gda ) background color to black, the axes lines foreground and font color to white.
colordef(f,color_scheme) sets the color properties of figure given by the handle f as well as the color properties of its current axes.
colordef('new',color_scheme) creates a new graphic window and its color properties as well as the properties of its axes.

Examples

   // Add here scilab instructions and comments

See Also

gdf , gda , figure_properties , axes_properties ,

Authors

S. Steer INRIA


colormap

Scilab Function
Last update : 07/07/2004

colormap - using colormaps

Description

A colormap cmap is defined by a m x 3 matrix. m is the number of colors. Color number i is given as a 3-uple cmap(i,1) , cmap(i,2) cmap(i,3) corresponding respectively to red, green and blue intensity between 0 and 1.

At the beginning, 32 colors are defined in the colormap. You can change the colormap of a figure by using set(f,"color_map",cmap) where f is the handle of the figure.

Each color in the colormap has an id you have to use to specify color in most plot functions. To see the ids, use function getcolor .

The functions hotcolormap , jetcolormap and graycolormap provide colormaps with continuous variation of the colors.

You can get the default colormap by cmap=get(sdf(),"color_map") .

Examples

n=64;
r=linspace(0,1,n)';
g=linspace(1,0,n)';
b=ones(r);
cmap=[r g b];
f=gcf(); f.color_map=cmap;
plot3d1()
f.color_map=get(sdf(),"color_map");

See Also

hotcolormap , graycolormap , jetcolormap , color , getcolor ,


color_list

Scilab Function
Last update : 08/07/2004

color_list - list of named colors

Description

You will find below the names of the colors known by Scilab. The RGB values are given after the name. Note that sometimes colors have more than 1 name.

scilab blue4 | 0 | 0 | 144
scilabblue4 | 0 | 0 | 144
scilab blue3 | 0 | 0 | 176
scilabblue3 | 0 | 0 | 176
scilab blue2 | 0 | 0 | 208
scilabblue2 | 0 | 0 | 208
scilab green4 | 0 | 144 | 0
scilabgreen4 | 0 | 144 | 0
scilab green3 | 0 | 176 | 0
scilabgreen3 | 0 | 176 | 0
scilab green2 | 0 | 208 | 0
scilabgreen2 | 0 | 208 | 0
scilab cyan4 | 0 | 144 | 144
scilabcyan4 | 0 | 144 | 144
scilab cyan3 | 0 | 176 | 176
scilabcyan3 | 0 | 176 | 176
scilab cyan2 | 0 | 208 | 208
scilabcyan2 | 0 | 208 | 208
scilab red4 | 144 | 0 | 0
scilabred4 | 144 | 0 | 0
scilab red3 | 176 | 0 | 0
scilabred3 | 176 | 0 | 0
scilab red2 | 208 | 0 | 0
scilabred2 | 208 | 0 | 0
scilab magenta4 | 144 | 0 | 144
scilabmagenta4 | 144 | 0 | 144
scilab magenta3 | 176 | 0 | 176
scilabmagenta3 | 176 | 0 | 176
scilab magenta2 | 208 | 0 | 208
scilabmagenta2 | 208 | 0 | 208
scilab brown4 | 128 | 48 | 0
scilabbrown4 | 128 | 48 | 0
scilab brown3 | 160 | 64 | 0
scilabbrown3 | 160 | 64 | 0
scilab brown2 | 192 | 96 | 0
scilabbrown2 | 192 | 96 | 0
scilab pink4 | 255 | 128 | 128
scilabpink4 | 255 | 128 | 128
scilab pink3 | 255 | 160 | 160
scilabpink3 | 255 | 160 | 160
scilab pink2 | 255 | 192 | 192
scilabpink2 | 255 | 192 | 192
scilab pink | 255 | 224 | 224
scilabpink | 255 | 224 | 224
snow | 255 | 250 | 250
ghost white | 248 | 248 | 255
ghostwhite | 248 | 248 | 255
white smoke | 245 | 245 | 245
whitesmoke | 245 | 245 | 245
gainsboro | 220 | 220 | 220
floral white | 255 | 250 | 240
floralwhite | 255 | 250 | 240
old lace | 253 | 245 | 230
oldlace | 253 | 245 | 230
linen | 250 | 240 | 230
antique white | 250 | 235 | 215
antiquewhite | 250 | 235 | 215
papaya whip | 255 | 239 | 213
papayawhip | 255 | 239 | 213
blanched almond | 255 | 235 | 205
blanchedalmond | 255 | 235 | 205
bisque | 255 | 228 | 196
peach puff | 255 | 218 | 185
peachpuff | 255 | 218 | 185
navajo white | 255 | 222 | 173
navajowhite | 255 | 222 | 173
moccasin | 255 | 228 | 181
cornsilk | 255 | 248 | 220
ivory | 255 | 255 | 240
lemon chiffon | 255 | 250 | 205
lemonchiffon | 255 | 250 | 205
seashell | 255 | 245 | 238
honeydew | 240 | 255 | 240
mint cream | 245 | 255 | 250
mintcream | 245 | 255 | 250
azure | 240 | 255 | 255
alice blue | 240 | 248 | 255
aliceblue | 240 | 248 | 255
lavender | 230 | 230 | 250
lavender blush | 255 | 240 | 245
lavenderblush | 255 | 240 | 245
misty rose | 255 | 228 | 225
mistyrose | 255 | 228 | 225
white | 255 | 255 | 255
black | 0 | 0 | 0
dark slate gray | 47 | 79 | 79
darkslategray | 47 | 79 | 79
dark slate grey | 47 | 79 | 79
darkslategrey | 47 | 79 | 79
dim gray | 105 | 105 | 105
dimgray | 105 | 105 | 105
dim grey | 105 | 105 | 105
dimgrey | 105 | 105 | 105
slate gray | 112 | 128 | 144
slategray | 112 | 128 | 144
slate grey | 112 | 128 | 144
slategrey | 112 | 128 | 144
light slate gray | 119 | 136 | 153
lightslategray | 119 | 136 | 153
light slate grey | 119 | 136 | 153
lightslategrey | 119 | 136 | 153
gray | 190 | 190 | 190
grey | 190 | 190 | 190
light grey | 211 | 211 | 211
lightgrey | 211 | 211 | 211
light gray | 211 | 211 | 211
lightgray | 211 | 211 | 211
midnight blue | 25 | 25 | 112
midnightblue | 25 | 25 | 112
navy | 0 | 0 | 128
navy blue | 0 | 0 | 128
navyblue | 0 | 0 | 128
cornflower blue | 100 | 149 | 237
cornflowerblue | 100 | 149 | 237
dark slate blue | 72 | 61 | 139
darkslateblue | 72 | 61 | 139
slate blue | 106 | 90 | 205
slateblue | 106 | 90 | 205
medium slate blue | 123 | 104 | 238
mediumslateblue | 123 | 104 | 238
light slate blue | 132 | 112 | 255
lightslateblue | 132 | 112 | 255
medium blue | 0 | 0 | 205
mediumblue | 0 | 0 | 205
royal blue | 65 | 105 | 225
royalblue | 65 | 105 | 225
blue | 0 | 0 | 255
dodger blue | 30 | 144 | 255
dodgerblue | 30 | 144 | 255
deep sky blue | 0 | 191 | 255
deepskyblue | 0 | 191 | 255
sky blue | 135 | 206 | 235
skyblue | 135 | 206 | 235
light sky blue | 135 | 206 | 250
lightskyblue | 135 | 206 | 250
steel blue | 70 | 130 | 180
steelblue | 70 | 130 | 180
light steel blue | 176 | 196 | 222
lightsteelblue | 176 | 196 | 222
light blue | 173 | 216 | 230
lightblue | 173 | 216 | 230
powder blue | 176 | 224 | 230
powderblue | 176 | 224 | 230
pale turquoise | 175 | 238 | 238
paleturquoise | 175 | 238 | 238
dark turquoise | 0 | 206 | 209
darkturquoise | 0 | 206 | 209
medium turquoise | 72 | 209 | 204
mediumturquoise | 72 | 209 | 204
turquoise | 64 | 224 | 208
cyan | 0 | 255 | 255
light cyan | 224 | 255 | 255
lightcyan | 224 | 255 | 255
cadet blue | 95 | 158 | 160
cadetblue | 95 | 158 | 160
medium aquamarine | 102 | 205 | 170
mediumaquamarine | 102 | 205 | 170
aquamarine | 127 | 255 | 212
dark green | 0 | 100 | 0
darkgreen | 0 | 100 | 0
dark olive green | 85 | 107 | 47
darkolivegreen | 85 | 107 | 47
dark sea green | 143 | 188 | 143
darkseagreen | 143 | 188 | 143
sea green | 46 | 139 | 87
seagreen | 46 | 139 | 87
medium sea green | 60 | 179 | 113
mediumseagreen | 60 | 179 | 113
light sea green | 32 | 178 | 170
lightseagreen | 32 | 178 | 170
pale green | 152 | 251 | 152
palegreen | 152 | 251 | 152
spring green | 0 | 255 | 127
springgreen | 0 | 255 | 127
lawn green | 124 | 252 | 0
lawngreen | 124 | 252 | 0
green | 0 | 255 | 0
chartreuse | 127 | 255 | 0
medium spring green | 0 | 250 | 154
mediumspringgreen | 0 | 250 | 154
green yellow | 173 | 255 | 47
greenyellow | 173 | 255 | 47
lime green | 50 | 205 | 50
limegreen | 50 | 205 | 50
yellow green | 154 | 205 | 50
yellowgreen | 154 | 205 | 50
forest green | 34 | 139 | 34
forestgreen | 34 | 139 | 34
olive drab | 107 | 142 | 35
olivedrab | 107 | 142 | 35
dark khaki | 189 | 183 | 107
darkkhaki | 189 | 183 | 107
khaki | 240 | 230 | 140
pale goldenrod | 238 | 232 | 170
palegoldenrod | 238 | 232 | 170
light goldenrod yellow | 250 | 250 | 210
lightgoldenrodyellow | 250 | 250 | 210
light yellow | 255 | 255 | 224
lightyellow | 255 | 255 | 224
yellow | 255 | 255 | 0
gold | 255 | 215 | 0
light goldenrod | 238 | 221 | 130
lightgoldenrod | 238 | 221 | 130
goldenrod | 218 | 165 | 32
dark goldenrod | 184 | 134 | 11
darkgoldenrod | 184 | 134 | 11
rosy brown | 188 | 143 | 143
rosybrown | 188 | 143 | 143
indian red | 205 | 92 | 92
indianred | 205 | 92 | 92
saddle brown | 139 | 69 | 19
saddlebrown | 139 | 69 | 19
sienna | 160 | 82 | 45
peru | 205 | 133 | 63
burlywood | 222 | 184 | 135
beige | 245 | 245 | 220
wheat | 245 | 222 | 179
sandy brown | 244 | 164 | 96
sandybrown | 244 | 164 | 96
tan | 210 | 180 | 140
chocolate | 210 | 105 | 30
firebrick | 178 | 34 | 34
brown | 165 | 42 | 42
dark salmon | 233 | 150 | 122
darksalmon | 233 | 150 | 122
salmon | 250 | 128 | 114
light salmon | 255 | 160 | 122
lightsalmon | 255 | 160 | 122
orange | 255 | 165 | 0
dark orange | 255 | 140 | 0
darkorange | 255 | 140 | 0
coral | 255 | 127 | 80
light coral | 240 | 128 | 128
lightcoral | 240 | 128 | 128
tomato | 255 | 99 | 71
orange red | 255 | 69 | 0
orangered | 255 | 69 | 0
red | 255 | 0 | 0
hot pink | 255 | 105 | 180
hotpink | 255 | 105 | 180
deep pink | 255 | 20 | 147
deeppink | 255 | 20 | 147
pink | 255 | 192 | 203
light pink | 255 | 182 | 193
lightpink | 255 | 182 | 193
pale violet red | 219 | 112 | 147
palevioletred | 219 | 112 | 147
maroon | 176 | 48 | 96
medium violet red | 199 | 21 | 133
mediumvioletred | 199 | 21 | 133
violet red | 208 | 32 | 144
violetred | 208 | 32 | 144
magenta | 255 | 0 | 255
violet | 238 | 130 | 238
plum | 221 | 160 | 221
orchid | 218 | 112 | 214
medium orchid | 186 | 85 | 211
mediumorchid | 186 | 85 | 211
dark orchid | 153 | 50 | 204
darkorchid | 153 | 50 | 204
dark violet | 148 | 0 | 211
darkviolet | 148 | 0 | 211
blue violet | 138 | 43 | 226
blueviolet | 138 | 43 | 226
purple | 160 | 32 | 240
medium purple | 147 | 112 | 219
mediumpurple | 147 | 112 | 219
thistle | 216 | 191 | 216
snow1 | 255 | 250 | 250
snow2 | 238 | 233 | 233
snow3 | 205 | 201 | 201
snow4 | 139 | 137 | 137
seashell1 | 255 | 245 | 238
seashell2 | 238 | 229 | 222
seashell3 | 205 | 197 | 191
seashell4 | 139 | 134 | 130
antiquewhite1 | 255 | 239 | 219
antiquewhite2 | 238 | 223 | 204
antiquewhite3 | 205 | 192 | 176
antiquewhite4 | 139 | 131 | 120
bisque1 | 255 | 228 | 196
bisque2 | 238 | 213 | 183
bisque3 | 205 | 183 | 158
bisque4 | 139 | 125 | 107
peachpuff1 | 255 | 218 | 185
peachpuff2 | 238 | 203 | 173
peachpuff3 | 205 | 175 | 149
peachpuff4 | 139 | 119 | 101
navajowhite1 | 255 | 222 | 173
navajowhite2 | 238 | 207 | 161
navajowhite3 | 205 | 179 | 139
navajowhite4 | 139 | 121 | 94
lemonchiffon1 | 255 | 250 | 205
lemonchiffon2 | 238 | 233 | 191
lemonchiffon3 | 205 | 201 | 165
lemonchiffon4 | 139 | 137 | 112
cornsilk1 | 255 | 248 | 220
cornsilk2 | 238 | 232 | 205
cornsilk3 | 205 | 200 | 177
cornsilk4 | 139 | 136 | 120
ivory1 | 255 | 255 | 240
ivory2 | 238 | 238 | 224
ivory3 | 205 | 205 | 193
ivory4 | 139 | 139 | 131
honeydew1 | 240 | 255 | 240
honeydew2 | 224 | 238 | 224
honeydew3 | 193 | 205 | 193
honeydew4 | 131 | 139 | 131
lavenderblush1 | 255 | 240 | 245
lavenderblush2 | 238 | 224 | 229
lavenderblush3 | 205 | 193 | 197
lavenderblush4 | 139 | 131 | 134
mistyrose1 | 255 | 228 | 225
mistyrose2 | 238 | 213 | 210
mistyrose3 | 205 | 183 | 181
mistyrose4 | 139 | 125 | 123
azure1 | 240 | 255 | 255
azure2 | 224 | 238 | 238
azure3 | 193 | 205 | 205
azure4 | 131 | 139 | 139
slateblue1 | 131 | 111 | 255
slateblue2 | 122 | 103 | 238
slateblue3 | 105 | 89 | 205
slateblue4 | 71 | 60 | 139
royalblue1 | 72 | 118 | 255
royalblue2 | 67 | 110 | 238
royalblue3 | 58 | 95 | 205
royalblue4 | 39 | 64 | 139
blue1 | 0 | 0 | 255
blue2 | 0 | 0 | 238
blue3 | 0 | 0 | 205
blue4 | 0 | 0 | 139
dodgerblue1 | 30 | 144 | 255
dodgerblue2 | 28 | 134 | 238
dodgerblue3 | 24 | 116 | 205
dodgerblue4 | 16 | 78 | 139
steelblue1 | 99 | 184 | 255
steelblue2 | 92 | 172 | 238
steelblue3 | 79 | 148 | 205
steelblue4 | 54 | 100 | 139
deepskyblue1 | 0 | 191 | 255
deepskyblue2 | 0 | 178 | 238
deepskyblue3 | 0 | 154 | 205
deepskyblue4 | 0 | 104 | 139
skyblue1 | 135 | 206 | 255
skyblue2 | 126 | 192 | 238
skyblue3 | 108 | 166 | 205
skyblue4 | 74 | 112 | 139
lightskyblue1 | 176 | 226 | 255
lightskyblue2 | 164 | 211 | 238
lightskyblue3 | 141 | 182 | 205
lightskyblue4 | 96 | 123 | 139
slategray1 | 198 | 226 | 255
slategray2 | 185 | 211 | 238
slategray3 | 159 | 182 | 205
slategray4 | 108 | 123 | 139
lightsteelblue1 | 202 | 225 | 255
lightsteelblue2 | 188 | 210 | 238
lightsteelblue3 | 162 | 181 | 205
lightsteelblue4 | 110 | 123 | 139
lightblue1 | 191 | 239 | 255
lightblue2 | 178 | 223 | 238
lightblue3 | 154 | 192 | 205
lightblue4 | 104 | 131 | 139
lightcyan1 | 224 | 255 | 255
lightcyan2 | 209 | 238 | 238
lightcyan3 | 180 | 205 | 205
lightcyan4 | 122 | 139 | 139
paleturquoise1 | 187 | 255 | 255
paleturquoise2 | 174 | 238 | 238
paleturquoise3 | 150 | 205 | 205
paleturquoise4 | 102 | 139 | 139
cadetblue1 | 152 | 245 | 255
cadetblue2 | 142 | 229 | 238
cadetblue3 | 122 | 197 | 205
cadetblue4 | 83 | 134 | 139
turquoise1 | 0 | 245 | 255
turquoise2 | 0 | 229 | 238
turquoise3 | 0 | 197 | 205
turquoise4 | 0 | 134 | 139
cyan1 | 0 | 255 | 255
cyan2 | 0 | 238 | 238
cyan3 | 0 | 205 | 205
cyan4 | 0 | 139 | 139
darkslategray1 | 151 | 255 | 255
darkslategray2 | 141 | 238 | 238
darkslategray3 | 121 | 205 | 205
darkslategray4 | 82 | 139 | 139
aquamarine1 | 127 | 255 | 212
aquamarine2 | 118 | 238 | 198
aquamarine3 | 102 | 205 | 170
aquamarine4 | 69 | 139 | 116
darkseagreen1 | 193 | 255 | 193
darkseagreen2 | 180 | 238 | 180
darkseagreen3 | 155 | 205 | 155
darkseagreen4 | 105 | 139 | 105
seagreen1 | 84 | 255 | 159
seagreen2 | 78 | 238 | 148
seagreen3 | 67 | 205 | 128
seagreen4 | 46 | 139 | 87
palegreen1 | 154 | 255 | 154
palegreen2 | 144 | 238 | 144
palegreen3 | 124 | 205 | 124
palegreen4 | 84 | 139 | 84
springgreen1 | 0 | 255 | 127
springgreen2 | 0 | 238 | 118
springgreen3 | 0 | 205 | 102
springgreen4 | 0 | 139 | 69
green1 | 0 | 255 | 0
green2 | 0 | 238 | 0
green3 | 0 | 205 | 0
green4 | 0 | 139 | 0
chartreuse1 | 127 | 255 | 0
chartreuse2 | 118 | 238 | 0
chartreuse3 | 102 | 205 | 0
chartreuse4 | 69 | 139 | 0
olivedrab1 | 192 | 255 | 62
olivedrab2 | 179 | 238 | 58
olivedrab3 | 154 | 205 | 50
olivedrab4 | 105 | 139 | 34
darkolivegreen1 | 202 | 255 | 112
darkolivegreen2 | 188 | 238 | 104
darkolivegreen3 | 162 | 205 | 90
darkolivegreen4 | 110 | 139 | 61
khaki1 | 255 | 246 | 143
khaki2 | 238 | 230 | 133
khaki3 | 205 | 198 | 115
khaki4 | 139 | 134 | 78
lightgoldenrod1 | 255 | 236 | 139
lightgoldenrod2 | 238 | 220 | 130
lightgoldenrod3 | 205 | 190 | 112
lightgoldenrod4 | 139 | 129 | 76
lightyellow1 | 255 | 255 | 224
lightyellow2 | 238 | 238 | 209
lightyellow3 | 205 | 205 | 180
lightyellow4 | 139 | 139 | 122
yellow1 | 255 | 255 | 0
yellow2 | 238 | 238 | 0
yellow3 | 205 | 205 | 0
yellow4 | 139 | 139 | 0
gold1 | 255 | 215 | 0
gold2 | 238 | 201 | 0
gold3 | 205 | 173 | 0
gold4 | 139 | 117 | 0
goldenrod1 | 255 | 193 | 37
goldenrod2 | 238 | 180 | 34
goldenrod3 | 205 | 155 | 29
goldenrod4 | 139 | 105 | 20
darkgoldenrod1 | 255 | 185 | 15
darkgoldenrod2 | 238 | 173 | 14
darkgoldenrod3 | 205 | 149 | 12
darkgoldenrod4 | 139 | 101 | 8
rosybrown1 | 255 | 193 | 193
rosybrown2 | 238 | 180 | 180
rosybrown3 | 205 | 155 | 155
rosybrown4 | 139 | 105 | 105
indianred1 | 255 | 106 | 106
indianred2 | 238 | 99 | 99
indianred3 | 205 | 85 | 85
indianred4 | 139 | 58 | 58
sienna1 | 255 | 130 | 71
sienna2 | 238 | 121 | 66
sienna3 | 205 | 104 | 57
sienna4 | 139 | 71 | 38
burlywood1 | 255 | 211 | 155
burlywood2 | 238 | 197 | 145
burlywood3 | 205 | 170 | 125
burlywood4 | 139 | 115 | 85
wheat1 | 255 | 231 | 186
wheat2 | 238 | 216 | 174
wheat3 | 205 | 186 | 150
wheat4 | 139 | 126 | 102
tan1 | 255 | 165 | 79
tan2 | 238 | 154 | 73
tan3 | 205 | 133 | 63
tan4 | 139 | 90 | 43
chocolate1 | 255 | 127 | 36
chocolate2 | 238 | 118 | 33
chocolate3 | 205 | 102 | 29
chocolate4 | 139 | 69 | 19
firebrick1 | 255 | 48 | 48
firebrick2 | 238 | 44 | 44
firebrick3 | 205 | 38 | 38
firebrick4 | 139 | 26 | 26
brown1 | 255 | 64 | 64
brown2 | 238 | 59 | 59
brown3 | 205 | 51 | 51
brown4 | 139 | 35 | 35
salmon1 | 255 | 140 | 105
salmon2 | 238 | 130 | 98
salmon3 | 205 | 112 | 84
salmon4 | 139 | 76 | 57
lightsalmon1 | 255 | 160 | 122
lightsalmon2 | 238 | 149 | 114
lightsalmon3 | 205 | 129 | 98
lightsalmon4 | 139 | 87 | 66
orange1 | 255 | 165 | 0
orange2 | 238 | 154 | 0
orange3 | 205 | 133 | 0
orange4 | 139 | 90 | 0
darkorange1 | 255 | 127 | 0
darkorange2 | 238 | 118 | 0
darkorange3 | 205 | 102 | 0
darkorange4 | 139 | 69 | 0
coral1 | 255 | 114 | 86
coral2 | 238 | 106 | 80
coral3 | 205 | 91 | 69
coral4 | 139 | 62 | 47
tomato1 | 255 | 99 | 71
tomato2 | 238 | 92 | 66
tomato3 | 205 | 79 | 57
tomato4 | 139 | 54 | 38
orangered1 | 255 | 69 | 0
orangered2 | 238 | 64 | 0
orangered3 | 205 | 55 | 0
orangered4 | 139 | 37 | 0
red1 | 255 | 0 | 0
red2 | 238 | 0 | 0
red3 | 205 | 0 | 0
red4 | 139 | 0 | 0
deeppink1 | 255 | 20 | 147
deeppink2 | 238 | 18 | 137
deeppink3 | 205 | 16 | 118
deeppink4 | 139 | 10 | 80
hotpink1 | 255 | 110 | 180
hotpink2 | 238 | 106 | 167
hotpink3 | 205 | 96 | 144
hotpink4 | 139 | 58 | 98
pink1 | 255 | 181 | 197
pink2 | 238 | 169 | 184
pink3 | 205 | 145 | 158
pink4 | 139 | 99 | 108
lightpink1 | 255 | 174 | 185
lightpink2 | 238 | 162 | 173
lightpink3 | 205 | 140 | 149
lightpink4 | 139 | 95 | 101
palevioletred1 | 255 | 130 | 171
palevioletred2 | 238 | 121 | 159
palevioletred3 | 205 | 104 | 137
palevioletred4 | 139 | 71 | 93
maroon1 | 255 | 52 | 179
maroon2 | 238 | 48 | 167
maroon3 | 205 | 41 | 144
maroon4 | 139 | 28 | 98
violetred1 | 255 | 62 | 150
violetred2 | 238 | 58 | 140
violetred3 | 205 | 50 | 120
violetred4 | 139 | 34 | 82
magenta1 | 255 | 0 | 255
magenta2 | 238 | 0 | 238
magenta3 | 205 | 0 | 205
magenta4 | 139 | 0 | 139
orchid1 | 255 | 131 | 250
orchid2 | 238 | 122 | 233
orchid3 | 205 | 105 | 201
orchid4 | 139 | 71 | 137
plum1 | 255 | 187 | 255
plum2 | 238 | 174 | 238
plum3 | 205 | 150 | 205
plum4 | 139 | 102 | 139
mediumorchid1 | 224 | 102 | 255
mediumorchid2 | 209 | 95 | 238
mediumorchid3 | 180 | 82 | 205
mediumorchid4 | 122 | 55 | 139
darkorchid1 | 191 | 62 | 255
darkorchid2 | 178 | 58 | 238
darkorchid3 | 154 | 50 | 205
darkorchid4 | 104 | 34 | 139
purple1 | 155 | 48 | 255
purple2 | 145 | 44 | 238
purple3 | 125 | 38 | 205
purple4 | 85 | 26 | 139
mediumpurple1 | 171 | 130 | 255
mediumpurple2 | 159 | 121 | 238
mediumpurple3 | 137 | 104 | 205
mediumpurple4 | 93 | 71 | 139
thistle1 | 255 | 225 | 255
thistle2 | 238 | 210 | 238
thistle3 | 205 | 181 | 205
thistle4 | 139 | 123 | 139
gray0 | 0 | 0 | 0
grey0 | 0 | 0 | 0
gray1 | 3 | 3 | 3
grey1 | 3 | 3 | 3
gray2 | 5 | 5 | 5
grey2 | 5 | 5 | 5
gray3 | 8 | 8 | 8
grey3 | 8 | 8 | 8
gray4 | 10 | 10 | 10
grey4 | 10 | 10 | 10
gray5 | 13 | 13 | 13
grey5 | 13 | 13 | 13
gray6 | 15 | 15 | 15
grey6 | 15 | 15 | 15
gray7 | 18 | 18 | 18
grey7 | 18 | 18 | 18
gray8 | 20 | 20 | 20
grey8 | 20 | 20 | 20
gray9 | 23 | 23 | 23
grey9 | 23 | 23 | 23
gray10 | 26 | 26 | 26
grey10 | 26 | 26 | 26
gray11 | 28 | 28 | 28
grey11 | 28 | 28 | 28
gray12 | 31 | 31 | 31
grey12 | 31 | 31 | 31
gray13 | 33 | 33 | 33
grey13 | 33 | 33 | 33
gray14 | 36 | 36 | 36
grey14 | 36 | 36 | 36
gray15 | 38 | 38 | 38
grey15 | 38 | 38 | 38
gray16 | 41 | 41 | 41
grey16 | 41 | 41 | 41
gray17 | 43 | 43 | 43
grey17 | 43 | 43 | 43
gray18 | 46 | 46 | 46
grey18 | 46 | 46 | 46
gray19 | 48 | 48 | 48
grey19 | 48 | 48 | 48
gray20 | 51 | 51 | 51
grey20 | 51 | 51 | 51
gray21 | 54 | 54 | 54
grey21 | 54 | 54 | 54
gray22 | 56 | 56 | 56
grey22 | 56 | 56 | 56
gray23 | 59 | 59 | 59
grey23 | 59 | 59 | 59
gray24 | 61 | 61 | 61
grey24 | 61 | 61 | 61
gray25 | 64 | 64 | 64
grey25 | 64 | 64 | 64
gray26 | 66 | 66 | 66
grey26 | 66 | 66 | 66
gray27 | 69 | 69 | 69
grey27 | 69 | 69 | 69
gray28 | 71 | 71 | 71
grey28 | 71 | 71 | 71
gray29 | 74 | 74 | 74
grey29 | 74 | 74 | 74
gray30 | 77 | 77 | 77
grey30 | 77 | 77 | 77
gray31 | 79 | 79 | 79
grey31 | 79 | 79 | 79
gray32 | 82 | 82 | 82
grey32 | 82 | 82 | 82
gray33 | 84 | 84 | 84
grey33 | 84 | 84 | 84
gray34 | 87 | 87 | 87
grey34 | 87 | 87 | 87
gray35 | 89 | 89 | 89
grey35 | 89 | 89 | 89
gray36 | 92 | 92 | 92
grey36 | 92 | 92 | 92
gray37 | 94 | 94 | 94
grey37 | 94 | 94 | 94
gray38 | 97 | 97 | 97
grey38 | 97 | 97 | 97
gray39 | 99 | 99 | 99
grey39 | 99 | 99 | 99
gray40 | 102 | 102 | 102
grey40 | 102 | 102 | 102
gray41 | 105 | 105 | 105
grey41 | 105 | 105 | 105
gray42 | 107 | 107 | 107
grey42 | 107 | 107 | 107
gray43 | 110 | 110 | 110
grey43 | 110 | 110 | 110
gray44 | 112 | 112 | 112
grey44 | 112 | 112 | 112
gray45 | 115 | 115 | 115
grey45 | 115 | 115 | 115
gray46 | 117 | 117 | 117
grey46 | 117 | 117 | 117
gray47 | 120 | 120 | 120
grey47 | 120 | 120 | 120
gray48 | 122 | 122 | 122
grey48 | 122 | 122 | 122
gray49 | 125 | 125 | 125
grey49 | 125 | 125 | 125
gray50 | 127 | 127 | 127
grey50 | 127 | 127 | 127
gray51 | 130 | 130 | 130
grey51 | 130 | 130 | 130
gray52 | 133 | 133 | 133
grey52 | 133 | 133 | 133
gray53 | 135 | 135 | 135
grey53 | 135 | 135 | 135
gray54 | 138 | 138 | 138
grey54 | 138 | 138 | 138
gray55 | 140 | 140 | 140
grey55 | 140 | 140 | 140
gray56 | 143 | 143 | 143
grey56 | 143 | 143 | 143
gray57 | 145 | 145 | 145
grey57 | 145 | 145 | 145
gray58 | 148 | 148 | 148
grey58 | 148 | 148 | 148
gray59 | 150 | 150 | 150
grey59 | 150 | 150 | 150
gray60 | 153 | 153 | 153
grey60 | 153 | 153 | 153
gray61 | 156 | 156 | 156
grey61 | 156 | 156 | 156
gray62 | 158 | 158 | 158
grey62 | 158 | 158 | 158
gray63 | 161 | 161 | 161
grey63 | 161 | 161 | 161
gray64 | 163 | 163 | 163
grey64 | 163 | 163 | 163
gray65 | 166 | 166 | 166
grey65 | 166 | 166 | 166
gray66 | 168 | 168 | 168
grey66 | 168 | 168 | 168
gray67 | 171 | 171 | 171
grey67 | 171 | 171 | 171
gray68 | 173 | 173 | 173
grey68 | 173 | 173 | 173
gray69 | 176 | 176 | 176
grey69 | 176 | 176 | 176
gray70 | 179 | 179 | 179
grey70 | 179 | 179 | 179
gray71 | 181 | 181 | 181
grey71 | 181 | 181 | 181
gray72 | 184 | 184 | 184
grey72 | 184 | 184 | 184
gray73 | 186 | 186 | 186
grey73 | 186 | 186 | 186
gray74 | 189 | 189 | 189
grey74 | 189 | 189 | 189
gray75 | 191 | 191 | 191
grey75 | 191 | 191 | 191
gray76 | 194 | 194 | 194
grey76 | 194 | 194 | 194
gray77 | 196 | 196 | 196
grey77 | 196 | 196 | 196
gray78 | 199 | 199 | 199
grey78 | 199 | 199 | 199
gray79 | 201 | 201 | 201
grey79 | 201 | 201 | 201
gray80 | 204 | 204 | 204
grey80 | 204 | 204 | 204
gray81 | 207 | 207 | 207
grey81 | 207 | 207 | 207
gray82 | 209 | 209 | 209
grey82 | 209 | 209 | 209
gray83 | 212 | 212 | 212
grey83 | 212 | 212 | 212
gray84 | 214 | 214 | 214
grey84 | 214 | 214 | 214
gray85 | 217 | 217 | 217
grey85 | 217 | 217 | 217
gray86 | 219 | 219 | 219
grey86 | 219 | 219 | 219
gray87 | 222 | 222 | 222
grey87 | 222 | 222 | 222
gray88 | 224 | 224 | 224
grey88 | 224 | 224 | 224
gray89 | 227 | 227 | 227
grey89 | 227 | 227 | 227
gray90 | 229 | 229 | 229
grey90 | 229 | 229 | 229
gray91 | 232 | 232 | 232
grey91 | 232 | 232 | 232
gray92 | 235 | 235 | 235
grey92 | 235 | 235 | 235
gray93 | 237 | 237 | 237
grey93 | 237 | 237 | 237
gray94 | 240 | 240 | 240
grey94 | 240 | 240 | 240
gray95 | 242 | 242 | 242
grey95 | 242 | 242 | 242
gray96 | 245 | 245 | 245
grey96 | 245 | 245 | 245
gray97 | 247 | 247 | 247
grey97 | 247 | 247 | 247
gray98 | 250 | 250 | 250
grey98 | 250 | 250 | 250
gray99 | 252 | 252 | 252
grey99 | 252 | 252 | 252
gray100 | 255 | 255 | 255
grey100 | 255 | 255 | 255
dark grey | 169 | 169 | 169
darkgrey | 169 | 169 | 169
dark gray | 169 | 169 | 169
darkgray | 169 | 169 | 169
dark blue | 0 | 0 | 139
darkblue | 0 | 0 | 139
dark cyan | 0 | 139 | 139
darkcyan | 0 | 139 | 139
dark magenta | 139 | 0 | 139
darkmagenta | 139 | 0 | 139
dark red | 139 | 0 | 0
darkred | 139 | 0 | 0
light green | 144 | 238 | 144
lightgreen | 144 | 238 | 144

See Also

color , name2rgb , rgb2name ,


color

Scilab Function
Last update : 07/07/2004

color - returns the color id of a color

Calling Sequence

id=color(name)
id=color(r,g,b)

Parameters

  • name : name of a color.
  • r,g,b : RGB integer values of a color.
  • id : id of the color.

Description

color returns the color id corresponding to its argument:

  • name must be the name of a known color (see color_list ).
  • r , g and b must be integers between 0 and 255 corresponding to colors components red, green and blue. As usual 0 means no intensity and 255 means all the intensity of the color.

    • If the requested color does not exist in the current colormap it is added to the colormap.

    This function can be used to specify the foreground or background colors when plotting.

    Examples

x=linspace(-2*%pi,2*%pi,100)';
// using existing colors
plot2d(x,[sin(x),cos(x)],style=[color("red"),color("green")]);
// new colors: there are added to the colormap
e=gce(); p1=e.children(1); p2=e.children(2);
p1.foreground=color("purple"); p2.foreground=color("navy blue");
// using RGV values
p1.foreground=color(255,128,128);

    See Also

    colormap , color_list , getcolor ,


Compound_properties

Scilab Data type
Last update : 09/12/2005

Compound_properties - description of the Compound entity properties

Description

The Compound entity is a third of the graphics entities hierarchy. This entity defines interdependencies of the various graphics entities and their global visibility property.

parent: This property contains the handle of the parent. The parent of the text entity should be of the type "Axes" or "Compound" .
children: A vector containing the handles of all graphics objects children of the Compound These graphics objects can be of type "Compound" , "Rectangle" , "Polyline" , "Patch" , "Segs" , "Arc" , "Grayplot" ,..
visible: This field contains the visible property value for the entity . It should be "on" or "off" . By default, value is "on" where graphics entities children of the Compound are drawn according to their visibility property. If "off" all children of Compound are not displayed on the screen.
user_data: This field can be use to store any scilab variable in the figure data structure, and to retreive it.

See Also

glue , unglue , graphics_entities ,

Author

Djalel ABDEMOUCHE


contour2di

Scilab Function
Last update : 06/07/2004

contour2di - calcule les courbes de niveau d'une surface

Calling Sequence

[xc,yc]=contour2di(x,y,z,nz)

Parameters

  • x,y : deux vecteurs lignes de taille n1 et n2.
  • z : matrice réelle de taille (n1,n2), les valeurs de la fonction.
  • nz : valeurs des niveaux ou nombre de niveaux
    • - Si nz est un entier, sa valeur définit le nombre de courbes de niveaux espacées régulièrement entre zmin et zmax :
             z= zmin + (1:nz)*(zmax-zmin)/(nz+1)

      Noter que les niveaux zmin et zmax ne sont pas dessinés (génériquement ils sont réduits à des points) mais peuvent être ajoutés avec

             [im,jm] = find(z == zmin);     // ou zmax
        plot2d(x(im)',y(jm)',-9,"000")
    • - - Si nz est un vecteur, nz(i) done la valeur de la ième courbe de niveau.
  • xc,yc : vecteurs de taille identique contenant la définition des contours. Voir ci-dessous pour les détails.

Description

contour2di calcule les courbes de niveau (dans le plan) de la surface z=f(x,y) . Les valeurs de f(x,y) sont données par la matrice z aux points du plan définis par x et y .

xc(1) contient le niveau associé à la première courbe de niveau, yc(1) contient le nombre de points N1 définissant cette courbe et ( xc(1+(1:N1)) , yc(1+(1:N1)) ) contiennent les coordonnées des points de la courbe. La seconde courbe commence à xc(2+N1) et yc(2+N1) et ainsi de suite.

Examples

[xc,yc]=contour2di(1:10,1:10,rand(10,10),5);
k=1;n=yc(k);c=1;
while k+yc(k)<size(xc,'*')
  n=yc(k);
  plot2d(xc(k+(1:n)),yc(k+(1:n)),c)
  c=c+1;
  k=k+n+1;
end

See Also

contour , fcontour , fcontour2d , contour2d , plot2d , xset ,

Author

J.Ph.C.


contour2d

Scilab Function
Last update : 02/09/2005

contour2d - level curves of a surface on a 2D plot

Calling Sequence

contour2d(x,y,z,nz,[style,strf,leg,rect,nax])
contour2d(x,y,z,nz,<opt_args>)

Parameters

  • x,y : two real row vectors of size n1 and n2: the grid.
  • z : real matrix of size (n1,n2), the values of the function on the grid or a Scilab function which defines the surface z=f(x,y) .
  • nz : the level values or the number of levels.
    • - If nz is an integer, its value gives the number of level curves equally spaced from zmin to zmax as follows:
      z= zmin + (1:nz)*(zmax-zmin)/(nz+1)

      Note that the zmin and zmax levels are not drawn (generically they are reduced to points) but they can be added with

      [im,jm] = find(z == zmin); // or zmax
plot2d(x(im)',y(jm)',-9,"000")
    • - If nz is a vector, nz(i) gives the value of the ith level curve.
  • <opt_args> : This represents a sequence of statements key1=value1,key2=value2 ,... where key1 , key2,... can be one of the following: style, leg, rect, nax, strf or axesflag and frameflag (see plot2d )
  • style,strf,leg,rect,nax : see plot2d . The argument style gives the dash styles or colors which are to be used for level curves. It must have the same size as the number of levels.

Description

contour2d draws level curves of a surface z=f(x,y) on a 2D plot. The values of f(x,y) are given by the matrix z at the grid points defined by x and y .

You can change the format of the floating point number printed on the levels by using xset("fpf",string) where string gives the format in C format syntax (for example string="%.3f" ). Use string="" to switch back to default format and Use string=" " to suppress printing. This last feature is useful in conjunction with legends to display the level numbers in a legend and not directly onto the level curves as usual (see Examples).

The optional arguments style,strf,leg,rect,nax , can be passed by a sequence of statements key1=value1, key2=value2 , ... where keys may be style , strf , leg , rect , nax . In this case, the order has no special meaning.

Use contour to draw levels curves on a 3D surface.

Examples

contour2d(1:10,1:10,rand(10,10),5,rect=[0,0,11,11])
// changing the format of the printing of the levels
xset("fpf","%.2f")
clf()
contour2d(1:10,1:10,rand(10,10),5,rect=[0,0,11,11])

// now an example with level numbers drawn in a legend
// Caution there are a number of tricks...
x = linspace(0,4*%pi,80);
z = cos(x')*cos(x);
clf(); f=gcf();
xset("fpf"," ")  // trick 1: this implies that the level numbers are not
                 //          drawn on the level curves
f.color_map=jetcolormap(7);
// trick 2: to be able to put the legend on the right without
//          interfering with the level curves use rect with a xmax
//          value large enough
contour2d(x,x,z,-0.75:0.25:0.75,frameflag=3,rect=[0,0,5*%pi,4*%pi])
// trick 3: use legends (note that the more practical legend function
//          will not work as soon as one of the level is formed by 2 curves)
legends(string(-0.75:0.25:0.75),1:7,"lr");
xtitle("Some level curves of the function cos(x)cos(y)")

See Also

contour , contour2di , plot2d ,

Author

J.Ph.C.


contourf

Scilab Function
Last update : 16/06/2004

contourf - courbes de niveaux 2D remplies d'une surface 3D

Calling Sequence

contourf(x,y,z,nz,[style,strf,leg,rect,nax])

Parameters

  • x,y : deux vecteurs lignes de taille n1 et n2.
  • z : matrice réelle de taille (n1,n2), les valeurs de la fonction.
  • nz : valeurs des niveaux ou nombre de niveaux
    • - Si nz est un entier, sa valeur définit le nombre de courbes de niveaux espacées régulièrement entre zmin et zmax :
       z= zmin + (1:nz)*(zmax-zmin)/(nz+1)

      Noter que les niveaux zmin et zmax ne sont pas dessinés (génériquement ils sont réduits à des points) mais peuvent être ajoutés avec

       [im,jm] = find(z == zmin);     // ou zmax
 plot2d(x(im)',y(jm)',-9,"000")
    • - Si nz est un vecteur, nz(i) donne la valeur du ième niveau. Noter qu'il peut être utile pour voir les niveaux zmin et zmax d'ajouter une tolérance de l'ordre de %eps : nz=[ zmin+%eps,..,zmax-%eps] .
  • style,strf,leg,rect,nax : voir plot2d . L'argument style définit les styles de pointillés ou les couleurs utilisés pour dessiner les courbes. Il doit être de même taille que le nombre de niveaux.

Description

contourf remplit l'espace entre deux courbes de niveaux consécutives d'une surface z=f(x,y) sur un dessin 2D. Les valeurs de f(x,y) sont données par la matrice z aux points du plan définis dans x et y .

Il est possible de changer le format des nombres affichés sur les courbes de niveau en utilisant xset("fpf",string) où string précise le format comme en langage C (par exemple string="%.3f" ). Utiliser string="" pour revenir au format par défaut.

Taper contour2d() pour voir une démonstration de la fonction.

Examples

contourf(1:10,1:10,rand(10,10),5,1:5,"011"," ",[0,0,11,11])

See Also

contour , fcontour , fcontour2d , contour2di , plot2d , xset ,

Author

J.Ph.C.


contour

Scilab Function
Last update : 08/12/2006

contour - level curves on a 3D surface

Calling Sequence

contour(x,y,z,nz,[theta,alpha,leg,flag,ebox,zlev])
contour(x,y,z,nz,<opt_args>)

Parameters

  • x,y : two real row vectors of size n1 and n2.
  • z : real matrix of size (n1,n2), the values of the function or a Scilab function which defines the surface z=f(x,y) .
  • nz : the level values or the number of levels.
    • - If nz is an integer, its value gives the number of level curves equally spaced from zmin to zmax as follows:

 z= zmin + (1:nz)*(zmax-zmin)/(nz+1)
      Note that the zmin and zmax levels are not drawn (generically they are reduced to points) but they can be added with

 [im,jm] = find(z == zmin);     // or zmax
 plot2d(x(im)',y(jm)',-9,"000")
    • - If nz is a vector, nz(i) gives the value of the ith level curve. Note that it can be useful in order to see zmin and zmax level curves to add an epsilon tolerance: nz=[zmin+%eps,..,zmax-%eps] .
  • <opt_args> : a sequence of statements key1=value1, key2=value2 , ... where keys may be theta , alpha , leg , flag , ebox , zlev (see below). In this case, the order has no special meaning.
  • theta, alpha : real values giving in degree the spherical coordinates of the observation point.
  • leg : string defining the captions for each axis with @ as a field separator, for example "X@Y@Z".
  • flag : a real vector of size three flag=[mode,type,box] .
    • mode : string representation mode.
      • mode=0: the level curves are drawn on the surface defined by (x,y,z).
      • mode=1: the level curves are drawn on a 3D plot and on the plan defined by the equation z=zlev.
      • mode=2: the level curves are drawn on a 2D plot.
    • type : an integer (scaling).
      • type=0 the plot is made using the current 3D scaling (set by a previous call to param3d , plot3d , contour or plot3d1 ).
      • type=1 rescales automatically 3d boxes with extreme aspect ratios, the boundaries are specified by the value of the optional argument ebox .
      • type=2 rescales automatically 3d boxes with extreme aspect ratios, the boundaries are computed using the given data.
      • type=3 3d isometric with box bounds given by optional ebox , similarily to type=1
      • type=4 3d isometric bounds derived from the data, to similarily type=2
      • type=5 3d expanded isometric bounds with box bounds given by optional ebox , similarily to type=1
      • type=6 3d expanded isometric bounds derived from the data, similarily to type=2
    • box : an integer (frame around the plot).
      • box=0 nothing is drawn around the plot.
      • box=1 unimplemented (like box=0).
      • box=2 only the axes behind the surface are drawn.
      • box=3 a box surrounding the surface is drawn and captions are added.
      • box=4 a box surrounding the surface is drawn, captions and axes are added.
  • ebox : used when type in flag is 1. It specifies the boundaries of the plot as the vector [xmin,xmax,ymin,ymax,zmin,zmax] .
  • zlev : real number.

Description

contour draws level curves of a surface z=f(x,y). The level curves are drawn on a 3D surface. The optional arguments are the same as for the function plot3d (except zlev ) and their meanings are the same. They control the drawing of level curves on a 3D plot. Only flag(1)=mode has a special meaning.

mode=0: the level curves are drawn on the surface defined by (x,y,z).
mode=1: the level curves are drawn on a 3D plot and on the plan defined by the equation z=zlev.
mode=2: the level curves are drawn on a 2D plot.

You can change the format of the floating point number printed on the levels by using xset("fpf",string) where string gives the format in C format syntax (for example string="%.3f" ). Use string="" to switch back to default format and Use string=" " to suppress printing.

Usually we use contour2d to draw levels curves on a 2D plot.

Enter the command contour() to see a demo.

Examples

t=linspace(-%pi,%pi,30);
function z=my_surface(x,y),z=x*sin(x)^2*cos(y),endfunction

contour(t,t,my_surface,10)
// changing the format of the printing of the levels
xset("fpf","%.1f")
xbasc()
contour(t,t,my_surface,10)
// 3D
xbasc()
z=feval(t,t,my_surface);
plot3d(t,t,z);contour(t,t,z+0.2*abs(z),20,flag=[0 2 4]);
//

See Also

contour2d , plot3d ,

Author

J.Ph.C.


copy

Scilab Function
Last update : 12/01/2004

copy - copy a graphics entity.

Calling Sequence

copy(h)
copy(h,h_axes)
h_copy=copy(h)

Parameters

  • h : a handle, the handle of the entity to copy.
  • h_axes : a handle, the handle of the parent entity for the destination. It should be an axes entity.
  • h_copy : a handle, the handle on the entity copied.

Description

This routine can be used to make a copy of a graphics entity with all its propeties'values, it returns the handle on this new entity. h_axes omitted, graphics entity is cloned and it's copied in the same parent axes entity.

Examples

See Also

get , set , delete , move , graphics_entities ,

Author

Djalel ABDEMOUCHE


delete

Scilab Function
Last update : 12/01/2004

delete - delete a graphic entity and its children.

Calling Sequence

delete(h)
delete(h,"callback")
delete()
delete("all")

Parameters

  • h : a handle, the handle of the entity to delete. h can be a vector of handles, in which case all objects identified by h(i) will be deleted.
  • "all" : string keyword (optional).

Description

This routine can be used to delete a graphics entity identified by the handle given as argument. In this case, All children of this graphics entity will be deleted. Without any argument delete removes the current entity. With "all" argument it deletes all the entities of the current figure.

The "callback" argument is not yet handled.

Examples

  set("figure_style","new") // select entity based graphics
  subplot(211);
  t=1:10;plot2d(t,t.^2),
  subplot(223);
  plot3d();
  subplot(224);
  plot2d();
  xfrect(1,0,3,1);
  a=get("current_axes")
  delete(); //delete the graphics object newly created
  delete(a.children); //delete all children of the current axes
  delete(a); //delete the axes
  delete("all"); //delete all the graphics objects of the figure

See Also

get , set , copy , move , graphics_entities ,

Author

Djalel ABDEMOUCHE


dragrect

Scilab Function
Last update : 16/06/2004

dragrect - déplace un ou plusieurs rectangles avec la souris

Calling Sequence

final_rect=dragrect(initial_rect)

Parameters

  • initial_rect : matrice 4xn contenant les définitions initiales des rectangles. Chaque colonne contient [x_gauche; y_haut; largeur; hauteur]. Si un seul rectangle est présent initial_rect peut être un rectangle.
  • final_rect : un rectangle défini par [x_gauche, y_haut, largeur, hauteur]
  • btn :un entier, le numero du bouton de la souris actionné.

Description

dragrect permet de déplacer un ou plusieurs rectangles à l'écran. La matrice 4xn initial_rect définit les rectangles. Chaque colonne de initial_rect contient les définitions initiales des rectangles. Chaque colonne contient [x_gauche; y_haut; largeur; hauteur]. Quand un bouton de la souris est actionné dragrect renvoie les rectangles finaux dans final_Rect .

Examples

xsetech(frect=[0,0,100,100])
r=dragrect([10;10;30;10])
xrect(r)

See Also

xrect , xrects , xclick , xgetmouse ,


drawaxis

Scilab Function
Last update : 16/06/2004

drawaxis - dessine un axe

Calling Sequence

drawaxis([options])
// options: x,y,dir,sub_int,fontsize,format_n,seg,textcolor,ticscolor,tics

Parameters

  • dir=chaîne : utilisé pour spécifier la direction des graduations. chaîne peut être choisi parmi 'u','r','d','l' ('l' est la valeur par défaut). Les valeurs 'u','r','d','l' signifient up (en haut), right (à droite) , down (en bas) , left (à gauche).
  • tics=chaîne : valeur décrivant comment sont données les graduations. chaîne peut être choisi parmi 'v','r', et 'i' ('v' est la valeur par défaut).
  • x,y : deux vecteurs donnant les positions des graduations.
  • val=chaîne : une matrice de chaînes de caractères donnant les labels à dessiner en face des graduations.
  • fontsize=int : spécifie la taille de la police utilisée pour dessiner les labels des graduations. La valeur par défaut est -1 (taille courante de police).
  • format_n=chaîne : format utilisé pour afficher les nombres au dessus des graduations.
  • seg= 1 ou 0 : valeur contrôlant l'affichage du segment de base de l'axe (1 par défaut).
  • sub_int=entier : un entier donnant le nombre de sous-graduations
  • textcolor=entier : spécifie la couleur à utiliser pour afficher les valeurs sur l'axe. La valeur par défaut est -1 (couleur courante).
  • ticscolor=entier : spécifie la couleur à utiliser pour dessiner les graduations. La valeur par défaut est -1 (couleur courante).

Description

drawaxis est utilisée pour dessiner un axe vertical ou horizontal. La direction de l'axe est donnée par dir dir = 'u' ou 'd' donne un axe horizontal avec des graduations dirigées vers le haut ( 'u' ) ou le bas ( 'd' ). dir = 'r' ou 'l' donne un axe vertical avec des graduations allant vers la droite ( 'r' ) ou vers la gauche ( 'l' ).

x et y donnent les positions des graduations. Si l'axe est horizontal alors y doit être un scalaire ou peut être omis et x est un vecteur. La signification de x est contrôlée par tics .

Si tics='v' alors x donne les positions des graduations sur l'axe des x.

Si tics='r' alors x doit être de taille 3. x=[xmin,xmax,n] et n donne le nombre d'intervalles.

Si tics='i' alors x doit être de taille 4, x=[k1,k2,a,n] . Dans ce cas xmin=k1*10^a , xmax=k2*10^a et n donne le nombre d'intervalles.

Si y est omis alors l'axe est positionné en haut du cadre si dir='u' ou en bas si dir='d'

Par défaut, les nombres sont dessinés sur l'axe. Ils sont dessinés en utilisant un format par défaut qui peut être changé avec format_n . Il est aussi possible d'afficher des chaînes de caractères données au lieu des nombres, si val est fourni en argument. La taille de val doit alors être égale au nombre de graduations.

Examples

plot2d(1:10,1:10,1,"020")
// axe horizontal
drawaxis(x=2:7,y=4,dir='u',tics='v')
// axe horizontal en haut du cadre
drawaxis(x=2:7,dir='u',tics='v')
// axe horizontal en bas du cadre
drawaxis(x=2:7,dir='d',tics='v')

// axe horizontal donné par une plage de variation
drawaxis(x=[2,7,3],y=4,dir='d',tics='r')

// axe vertical
drawaxis(x=4,y=2:7,dir='r',tics='v')
drawaxis(x=2,y=[2,7,3],dir='l',tics='r')
drawaxis(y=2:7,dir='r',tics='v')
drawaxis(y=2:7,dir='l',tics='v')

// axe horizontal avec chaînes de caractères au dessus des graduations
drawaxis(x=2:7,y=8,dir='u',tics='v',val='A'+string(1:6));
// axe vertical avec chaînes de caractères au dessus des graduations
drawaxis(x=8,y=2:7,dir='r',tics='v',val='B'+string(1:6));

// axe horizontal avec 'i'
drawaxis(x=[2,5,0,3],y=9,dir='u',tics='i');
drawaxis(x=9,y=[2,5,0,3],dir='r',tics='i',sub_int=5);

// encore un axe horizontal
drawaxis(x=2:7,y=4,dir='u',tics='v',fontsize=10,textcolor=9,ticscolor=7,seg=0,sub_int=20)

Author

J.Ph.C.


drawlater

Scilab Function
Last update : 13/12/2005

drawlater - makes axes children invisible.

Calling Sequence

drawlater()

Description

This function can be used not to display immediatly onto the current figure the next created graphics objects - i.e. by calling high level functions such as plotting functions or setting properties to existant objects. The immediate_drawing property of the current figure is set to 'off' in order to postpon the next drawings.

It can specially be used with the drawnow function.

To enable back the immediate_drawing for the current figure, you can use drawnow function.

Warning : note that between drawlater and drawnow calls, the current figure may have changed. Therefore, this must be used carefully.

Examples

  //Example :  one axes / one figure
  set("figure_style","new") // select entity based graphics
  drawlater();
  xfarc(.25,.55,.1,.15,0,64*360);
  xfarc(.55,.55,.1,.15,0,64*360);
  xfrect(.3,.8,.3,.2);
  xfrect(.2,.7,.5,.2);
  xfrect(.32,.78,.1,.1);
  xfrect(.44,.78,.14,.1);
  xfrect(-.2,.4,1.5,.8);
  xstring(0.33,.9,"A Scilab Car");
  a=get("current_axes");
  a.children(1).font_size=4;
  a.children(1).font_style=4;
  a.children(1).background=5;
  a.children(3).background=8;
  a.children(4).background=8;
  a.children(5).background=17;
  a.children(6).background=17;
  a.children(7).background=25;
  a.children(8).background=25;
  xclick();drawnow();

  //Example 2:: two axes / one figure

  subplot(212)
  a=gca();
  drawlater // what will be present in this axes will be displayed later
  plot2d // draw these axes and children later...

  subplot(211) // Warning: we change the axes
  plot2d1 // default drawing mode

  draw(a) // ...axes only is visible providing you not redraw the window
  drawnow() // all is visible

See Also

get , set , drawnow , graphics_entities ,

Author

Djalel ABDEMOUCHE, F.Leray


drawnow

Scilab Function
Last update : 28/09/2005

drawnow - draw hidden graphics entities.

Calling Sequence

drawnow()

Description

Considering the current figure, this function can be used to draw the hidden graphics entities and all its chidren, that may have been postponed by a previous call to drawlater . The immediate_drawing property of the current figure is set to "on" .

It can specially be used with the drawlater function.

Examples

  set("figure_style","new") // select entity based graphics
  f=get("current_figure") // handle of the current figure

  drawlater()
  subplot(221);
  t=1:10;plot2d(t,t.^2)
  subplot(222);
  x=0:1:7;plot2d(x,cos(x),2)
  subplot(234);
  plot2d(t,cos(t),3);
  subplot(235);
  plot2d(x,sin(2*x),5);
  subplot(236);
  plot2d(t,tan(2*t));

  draw(gca()); //draw the current axes and its children
  draw(f.children([3 4])); // draw the specified axes and their children
  drawnow(); // draw the current figure

See Also

get , set , drawlater , graphics_entities ,

Author

Djalel ABDEMOUCHE, F.Leray


draw

Scilab Function
Last update : 10/10/2005

draw - draw an entity.

Calling Sequence

draw()
draw(h)

Parameters

  • h : a handle, the handle on an entity to draw. h can be a vector of handles, in which case all objects identified by h(i) will be drawn.

Description

This function can be used to draw entities specified by h even if its parent figure immediate_drawing property is "off" . If no argument is specified, the current object is drawn. Note that the window must not be resized ; if not, those objects are hidden back.

Examples

   subplot(212)
   a=gca();
    plot2d
   drawlater

    subplot(211)
    plot2d1 // default drawing mode

    e=gce();
    draw(e.children(2)) // draw a single polyline of the second axes

    e.children(1).visible='off'; // We can choose to make a line invisible

    draw(e) // draw Compound and its children <=> draw all the visible polylines

    drawnow // ...now!

    e.children(1).visible='on';

See Also

get , set , drawnow , drawlater , graphics_entities ,

Author

Djalel ABDEMOUCHE, F.Leray


driver

Scilab Function
Last update : 12/01/2004

driver - select a graphics driver

Calling Sequence

driver(driver_name)
current_driver=driver()

Parameters

  • driver_name : string, driver to be selected.

Description

This function is used to select a graphics driver, or with no arguments to get the current graphics driver name. Most of the time, a user can ignore this function and change the driver by calling high level functions such as xbasc or xbasimp . The selected driver can be one of the followings:

"X11": output to the screen of the computer.
"Pos": output into Postscript format.
"Rec": output to the screen of the computer with recording of all the graphics commands. This is the default driver.
"Fig": output into XFig format. Clipping of objects is not provided in XFig.
"GIF": output into Gif format based on gd (http://www.boutell.com/gd)
"PPM": output into PPM format based on gd (http://www.boutell.com/gd)

Remark

To convert "GIF" or "PPM" files to other image format or for building animation one can use the "convert" program for ImageMagic (http://www.imagemagick.org/)

For example if one has generated a sequence of Gif files named img*.gif it is possible to build an animated Gif file (named anim.gif) by

convert -delay 10  img*.gif anim.gif

See Also

xtape , xbasc , xbasimp ,

Author

J.Ph.C.


edit_curv

Scilab Function
Last update : 16/06/2004

edit_curv - éditeur graphique interactif

Calling Sequence

[x,y,ok,gc] = edit_curv(y)
[x,y,ok,gc] = edit_curv(x,y)
[x,y,ok,gc] = edit_curv(x,y,job)
[x,y,ok,gc] = edit_curv(x,y,job,tit)
[x,y,ok,gc] = edit_curv(x,y,job,tit,gc)

Parameters

  • x : vecteur de coordonnées x
  • y : vecteur de coordonnées y
  • job : chaîne de caractères composée d'un à trois des caractères 'a','x','y'
    • 'a' : pour ajouter des points à la courbe éditée
    • 'x' : pour modifier les coordonnées x des points de la courbe éditée
    • 'y' : pour modifier les coordonnées y des points de la courbe éditée
  • tit : un vecteur de 3 chaînes de caractères donnant les légendes de la courbe
  • gc : une liste de paramètres pour la fenêtre graphique : gc=list(rect,nax)
    • rect : bornes du graphique (voir plot2d)
    • nax : paramètres de graduation (voir plot2d)
  • ok : si ok==%t l'utilisateur a quitté avec le menu 'ok' sinon l'utilisateur a quitté avec le menu 'abort'. : list (objets graphiques créés avec edit_curv

Description

edit_curv est un éditeur de courbes interactif. Pour ajouter un nouveau point cliquer à la position désirée, le point ajouté sera connecté au point final le plus proche. Pour bouger un point cliquer dessus, bouger la souris et cliquer pour définir la nouvelle position.

Author

Serge Steer ; ; ; ; ;


errbar

Scilab Function
Last update : 16/06/2004

errbar - ajoute des barres d'erreur sur un dessin 2D

Calling Sequence

errbar(x,y,em,ep)

Parameters

  • x,y,em,ep : 4 matrices de même taille.

Description

errbar ajoute des barres d'erreur sur un dessin 2D. x et y ont la même signification que dans plot2d . em(i,j) et ep(i,j) représentent l'intervalle d'erreur autour de la valeur y(i,j) : [y(i,j)-em(i,j),y(i,j)+ep(i,j)] .

Taper errbar() pour voir une démonstration de la fonction.

Examples

t=[0:0.1:2*%pi]';
y=[sin(t) cos(t)]; x=[t t];
plot2d(x,y)
errbar(x,y,0.05*ones(x),0.03*ones(x))

See Also

plot2d ,

Author

J.Ph.C.


eval3dp

Scilab Function
Last update : 16/06/2004

eval3dp - calcule les facettes d'une surface 3D paramétrique

Calling Sequence

[Xf,Yf,Zf]=eval3dp(fun,p1,p2)

Parameters

  • Xf,Yf,Zf : matrices de taille (4,n-1*m-1). Xf(:,i) , Yf(:,i) et Zf(:,i) sont respectivement les coordonnées sur les axes x,y, et z des 4 points de la facette numéro i.
  • fun : une fonction Scilab.
  • p1 : un vecteur de taille n .
  • p2 : un vecteur de taille m .

Description

eval3dp calcule la représentation sous forme de facettes à 4 points de la surface définie par la fonction fun . fun(p1,p2) calcule les coordonnées x,y et z des points correspondant sur la surface paramétrique définie par [x(i),y(i),z(i)]=fun(p1(i),p2(i)).

Examples

p1=linspace(0,2*%pi,10);
p2=linspace(0,2*%pi,10);
deff("[x,y,z]=scp(p1,p2)",["x=p1.*sin(p1).*cos(p2)";..
                            "y=p1.*cos(p1).*cos(p2)";..
                            "z=p1.*sin(p2)"])
[Xf,Yf,Zf]=eval3dp(scp,p1,p2);
plot3d(Xf,Yf,Zf)

See Also

genfac3d , plot3d ,


eval3d

Scilab Function
Last update : 16/06/2004

eval3d - valeurs d'une fonction sur une grille

Calling Sequence

[z]=eval3d(fun,x,[y])

Parameters

  • fun : fonction acceptant des arguments vectoriels
  • x,y : 2 vecteurs de tailles (1,n1) et (1,n2) (par défaut y=x ).
  • z : matrice de taille (n1,n2).

Description

Cette fonction renvoie une matrice z(n1,n2) où z(i,j)=fun(x(i),y(j)) . Si la fonction fun n'accepte pas d'arguments vectoriels utiliser la primitive feval .

Examples

  x=-5:5;y=x;
  deff('[z]=f(x,y)',['z= x.*y']);
  z=eval3d(f,x,y);
  plot3d(x,y,z);
//
  deff('[z]=f(x,y)',['z= x*y']);
  z=feval(x,y,f);
  plot3d(x,y,z);

See Also

feval ,

Author

Steer S.; ; ;


evans

Scilab Function
Last update : 08/06/2005

evans - Evans root locus

Calling Sequence

evans(H [,kmax])

Parameters

  • H : list (linear system syslin )
  • kmax : real (maximum gain desired for the plot )

Description

Gives the Evans root locus for a linear system in state-space or transfer form H(s) ( syslin list). This is the locus of the roots of 1+k*H(s)=1+k*N(s)/D(s) , in the complex plane. For a selected sample of gains k <= kmax , the imaginary part of the roots of D(s)+k*N(s) is plotted vs the real part.

To obtain the gain at a given point of the locus you can simply execute the following instruction : k=-1/real(horner(h,[1,%i]*locate(1))) and click the desired point on the root locus. If the coordinates of the selected point are in the real 2 x 1 vector P=locate(1) this k solves the equation k*N(w) + D(w) =0 with w=P(1)+%i*P(2)=[1,%i]*P .

Examples

H=syslin('c',352*poly(-5,'s')/poly([0,0,2000,200,25,1],'s','c'));
evans(H,100)
P=3.0548543 - 8.8491842*%i;    //P=selected point
k=-1/real(horner(H,P));
Ns=H('num');Ds=H('den');
roots(Ds+k*Ns)     //contains P as particular root
// Another one
clf();s=poly(0,'s');n=1+s;
d=real(poly([-1 -2 -%i %i],'s'));
evans(n,d,100);
//
clf();n=real(poly([0.1-%i 0.1+%i,-10],'s'));
evans(n,d,80);

See Also

kpure , krac2 , locate ,


fac3d

Scilab Function
Last update : 16/06/2004

fac3d - dessin en 3D d'une surface (obsolète)

Calling Sequence

fac3d(x,y,z,[theta,alpha,leg,flag,ebox])
fac3d1(x,y,z,[theta,alpha,leg,flag,ebox])

Description

Ces fonctions sont obsolètes et ont été remplacées par plot3d et plot3d1 .

See Also

plot3d , plot3d1 ,


fchamp

Scilab Function
Last update : 08/06/2005

fchamp - direction field of a 2D first order ODE

Calling Sequence

fchamp(f,t,xr,yr,[arfact,rect,strf])
fchamp(f,t,xr,yr,<opt_args>)

Parameters

  • f : An external (function or character string) or a list which describes the ODE.
    • - It can be a function name f , where f is supposed to be a function of type y=f(t,xy [p1,..pn]) . f returns a column vector of size 2, y , which gives the value of the direction field f at point xy=[x,y] and at time t .
    • - It can also be an object of type list, list(f,P1,..Pn) where f is a function of type y=f(t,xy,p1,..pn) and Pi gives the value of the parameter pi .
  • t : The selected time.
  • xr,yr : Two row vectors of size n1 and n2 which define the grid on which the direction field is computed.
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following: arfact, rect, strf (see below).
  • arfact,rect,strf : Optional arguments, see champ .

Description

fchamp is used to draw the direction field of a 2D first order ODE defined by the external function f . Note that if the ODE is autonomous, argument t is useless, but it must be given.

Enter the command fchamp() to see a demo.

Examples

deff("[xdot] = derpol(t,x)",..
        ["xd1 = x(2)";..
         "xd2 = -x(1) + (1 - x(1)**2)*x(2)";..
         "xdot = [ xd1 ; xd2 ]"])
xf= -1:0.1:1;
yf= -1:0.1:1;
fchamp(derpol,0,xf,yf)
clf()
fchamp(derpol,0,xf,yf,1,[-2,-2,2,2],"011")

See Also

champ , champ1 ,

Author

J.Ph.C.


fcontour2d

Scilab Function
Last update : 02/09/2005

fcontour2d - level curves of a surface defined by a function on a 2D plot

Calling Sequence

fcontour2d(xr,yr,f,nz,[style,strf,leg,rect,nax])
fcontour2d(xr,yr,f,nz,<opt_args>)

Description

This function is obsolete. It is now included in the contour2d function.

Author

J.Ph.C.


fcontour

Scilab Function
Last update : 02/09/2005

fcontour - level curves on a 3D surface defined by a function

Calling Sequence

fcontour(xr,yr,f,nz,[theta,alpha,leg,flag,ebox,zlev])
fcontour(xr,yr,f,nz,<opt_args>)

Description

This function is obsolete. It is now included in the contour function.

Author

J.Ph.C.


fec_properties

Scilab Data type
Last update : 09/12/2005

fec_properties - description of the fec entities properties

Description

The Fec entity is a leaf of the graphics entities hierarchy. It represents 2D finite elements plots (see fec , Sgrayplot ).

parent: This property contains the handle of the parent. The parent of the fec entity should be of the type "Axes" or "Compound" .
children: This property contains a vector with the children of the handle. However, Fec handles currently do not have any children .
visible: This field contains the visible property value for the entity . It should be "on" or "off" . By default, the plot is visible, the value's property is "on" . If "off" the plot is not drawn on the screen.
data: This is a three column matrix [x,y,f] , where x(i) and y(i) are the coordinates of the i 'th node. f(i) is the value associated to the node i .
triangles: This is a five column matrix [tn,n1,n2,n3,flag] . tn(j) is the triangle number. n1(j) , n2(j) and n3(j) are the index of the nodes which constitute the triangle. ( flag(j) is not used).
z_bounds: This [zmin,zmax] vector gives the z values associated with the first and the last color (of the current colormap). More exactly if the colormap have nc colors and if we note dz = (zmax-zmin)/nc, then the part of the triangulation where zmin + (i-1)dz <= z < zmin + i dz is filled with the color i). By default zmin = min(func) and zmax = max(func). If you want to do an animation with func values that varie in time, take for zmin and zmax the global minimum and maximum or something close.
user_data: This field can be use to store any scilab variable in the fec data structure, and to retreive it.

Examples

   set("figure_style","new"); //create a figure

   x=-10:10; y=-10:10;m =rand(21,21);
   Sgrayplot(x,y,m);
   a=get("current_axes");
   f=a.children.children(1)
   f.data(:,3)=(1:size(f.data,1))';
   a.parent.color_map=hotcolormap(64);

See Also

set , get , delete , fec , Sgrayplot , graphics_entities ,

Author

Djalel ABDEMOUCHE


fec

Scilab Function
Last update : 09/02/2006

fec - dessin en pseudo-couleurs d'une surface définie sur une triangulation

Calling Sequence

fec(x,y,triangles,func,[strf,leg,rect,nax,zminmax,colminmax])

Parameters

  • x,y : deux vecteurs de taille n , (x(i),y(i)) donne les coordonnées du sommet i
  • func : un vecteur de taille n : func(i) donne la valeur de la fonction à représenter
  • triangles : une matrice [Ntr,5] . Chaque ligne de triangles représente un triangle du maillage triangle(j) = [number,node1,node2,node3,flag] . node1,node2,node3 sont les numéros des sommets qui constituent le triangle j. number est le numéro du triangle et flag est un entier qui n'est pas utilisé par fec.
  • strf,leg,rect,nax : voir plot2d
  • zminmax : parfait pour faire des animations avec fec. zminmax est un vecteur de taille 2 [zmin zmax] qui donne les z associés à la première et la dernière couleur (de la table des couleurs courante). Plus exactement si la table des couleurs a nc couleurs et si on note dz = (zmax-zmin)/nc, alors la partie de la triangulation où zmin + (i-1)dz <= z < zmin + i dz est remplie avec la couleur i). Par défaut zmin = min(func) et zmax = max(func). Si vous voulez faire une animation avec des valeurs de func changeant en fonction du temps, prenez zmin et zmax égaux au minimum et maximum globaux. ATTENTION : pour les valeurs de func plus grandes que zmax la dernière couleur est utilisée, et pour les valeurs plus petites que zmin la première couleur est utilisée (on ne voit donc pas que les niveaux de zminmax sont franchis).
  • colminmax : un vecteur de 2 entiers positifs colminmax=[colmin colmax] avec 1 <= colmin < colmax <= nc (où nc est la taille de la table des couleurs). Permet de définir un sous-ensemble de la table des couleurs à utiliser, ici cmap(colmin:colmax). Par défaut toute la table des couleurs est utilisée.

Description

Voir les fonctions de démonstration dans le répertoire demos/fec .

fec.ex1 est une simple démo dans laquelle le maillage et la fonction sont construits en langage Scilab.

fec.ex2 est un exemple où le maillage est construit avec un mailleur externe (type amdba). Un ensemble de macros ( macros.sci ) peut être utilisé pour lire les fichiers de données correspondants.

Examples

// define a mini triangulation (4 vertices, 2 triangles)
x = [0 1 0 -1];
y = [0 0 1  1];
T = [1 1 2 3 1;
     2 3 4 1 1];
z = [0 1 0 -1];  // values of the func at each vertices
xbasc()
xset("colormap",jetcolormap(64))
subplot(1,2,1)
   colorbar(-1,1)
   fec(x,y,T,z,strf="040",mesh=%t)
   xtitle("fec example (with the mesh)")
subplot(1,2,2)
   colorbar(-1,1)
   fec(x,y,T,z,strf="040")  // rmq: mesh=%f by default
   xtitle("fec example (without the mesh)")
xselect()

// this example shows the effect of zminmax and uses the
// previous example datas (you have to execute the it before)
xbasc()
xset("colormap",jetcolormap(64))
colorbar(-0.5,0.5)  // be careful colorbar must be set by hands !
fec(x,y,T,z,strf="040", zminmax=[-0.5 0.5], mesh=%t)
xtitle("fec example : using zminmax argument")
xselect()

// this example shows the effect of zminmax and colout. It uses
// also the datas of the first example (you have to execute the it before)
xbasc()
xset("colormap",jetcolormap(64))
subplot(2,2,1)
   colorbar(-0.5,0.5)
   fec(x,y,T,z,strf="040", zminmax=[-0.5 0.5], colout=[0 0], mesh=%t)
   xtitle("fec example : using zminmax and colout =[0 0]")
subplot(2,2,2)
   colorbar(-0.5,0.5)
   fec(x,y,T,z,strf="040", zminmax=[-0.5 0.5], colout=[32 32], mesh=%t)
   xtitle("fec example : using zminmax and colout =[32 32]")
subplot(2,2,3)
   colorbar(-0.5,0.5)
   fec(x,y,T,z,strf="040", zminmax=[-0.5 0.5], colout=[-1 0], mesh=%t)
   xtitle("fec example : using zminmax and colout =[-1 0]")
subplot(2,2,4)
   colorbar(-0.5,0.5)
   fec(x,y,T,z,strf="040", zminmax=[-0.5 0.5], colout=[0 -1], mesh=%t)
   xtitle("fec example : using zminmax and colout =[0 -1]")
xselect()

// this example shows a feature from colminmax:
// playing with 2 colormaps for 2 subplots. It
// uses also the data of the first example.
xbasc()
xset("colormap",[hotcolormap(64);jetcolormap(64)])
subplot(1,2,1)
   colorbar(-1,1,[1 64])
   fec(x,y,T,z,strf="040", colminmax=[1 64], mesh=%t)
   xtitle("fec using the hot colormap")
subplot(1,2,2)
   colorbar(-1,1,[65 128])
   fec(x,y,T,z,strf="040", colminmax=[65 128], mesh=%t)
   xtitle("fec using the jet colormap")
xselect()

See Also

Sfgrayplot , Sgrayplot ,


fgrayplot

Scilab Function
Last update : 08/12/2006

fgrayplot - représentation 2D en pseudo-couleurs d'une surface définie par une fonction

Calling Sequence

fgrayplot(x,y,f,[strf,rect,nax])
fgrayplot(x,y,f,<opt_args>)

Parameters

  • x,y : vecteurs lignes de taille n1 et n2.
  • f : fonction externe du type z=f(x,y)
  • <opt_args> : une séquence d'affectations key1=value1, key2=value2 ,... où key1 , key2,... peuvent prendre les valeurs : rect, nax, strf, axesflag ou frameflag (voir plot2d ).
  • strf,rect,nax : voir plot2d .

Description

fgrayplot dessine une représentation 2D en pseudo-couleurs d'une surface définie par z=f(x,y) sur une grille définie par x et y . Chaque rectangle sur la grille est rempli avec une couleur dépendant de la moyenne des valeurs de z aux coins du rectangle.

Taper fgrayplot() pour voir une démonstration de la fonction.

Examples

t=-1:0.1:1;
deff("[z]=my_surface(x,y)","z=x**2+y**2")
fgrayplot(t,t,my_surface,rect=[-2,-2,2,2])

See Also

grayplot , plot2d , Sgrayplot , Sfgrayplot ,

Author

J.Ph.C.


figure_properties

Scilab Data type
Last update : 21/03/2006

figure_properties - description of the graphics figure entity properties

Description

The figure entity is the top level of the graphics entities hierarchy. This entity contain a number of properties designed to control many aspects of displaying Scilab graphics objects. These properties fall into two categories. Properties that contain information about figure itself and others related to set default values for the children creation.

Figure properties:
children: This handles represent the vector of the figure's children . Note that all figure children are of type "Axes" . Also keep in mind that, when creating a figure entity (using scf command), an Axes entity is simultaneously built too.
figure_style: The value of this field defines the figure style, it should be "old" or "new" . The "new" value sets the entity based style. The "old" value represents the old Scilab graphic mode. In this case figure_style is the only defined property.
figure_position: This field contains the position in pixel of the graphic window on the screen. The size is the vector [x,y] . The point [0,0] if the upper-left corner of the screen.
figure_size: This property controls the size in pixel of the screen's graphics window. The size is the vector [width,height] .
axes_size: Used to Specifies the size in pixel of the virtual graphics window. The size is the vector [width,height] . The virtual graphic window should be bigger than the part really visible on the screen.
auto_resize: This property determines if graphics window is resized. If the value is "on" then the axes_size property is equaled to the figure_size and the axes children are zoomed accordingly. If the value is "off" that indicate that axes_size cannot be resized when figure_size is changed.
figure_name: This field contains the name of the figure. This name is a character string displayed at the top of the graphics_window. The name can contain a single substring %d which will be replaced by the figure_id . No other instance of the % character is allowed inside the name.
figure_id: This field contains the identifier of the figure. This is an integer number which is set at figure creation and cannot be changed after.
color_map: Property which defines the colormap used by this figure. The colormap is a m by 3 matrix. m is the number of colors. Color number i is given as a 3-uple R , G , B corresponding respectively to red, green and blue intensity between 0 and 1.
pixmap: This property controls the pixmap status of a Graphic Window. If this property value is "off" the graphics are directly displayed on the screen. If it is "on" the graphics are done on a pixmap and are sent to the graphics window with the command show_pixmap() .
pixel_drawing_mode: This field defines the bitwise operation used to draw the pixel on the screen. The default mode is copy what is to say the pixel is drawn as required. More generally the bitwise operation is performed between the color of the source pixel and the color of the pixel already present on the screen. Operations are : "clear" , "and" , "andReverse" , "copy" , "andInverted" , "noop" , "xor" , "or" , "nor" , "equiv" , "invert" , "orReverse" , "copyInverted" , "orInverted" , "nand" , "set" ,
immediate_drawing: This property controls the figure display. Its value can be "on" (default mode) or "off" . It is used to delay a huge succession of graphics commands (implying several drawings or redrawings). Note that, when using drawlater or drawnow commands, it affects the property value of the current figure (which is respectively turned to 'off' or 'on' ).
background: This property controls the figure window background color. It takes as value an index relative to the current colormap.
user_data: This field can be use to store any scilab variable in the figure data structure, and to retreive it.
Children's default values:
visible: This field rules if the contents of the figure as to be redrawn. Its value should be "on" or "off" .
rotation_style: This field is related to the "3D Rot" button. It takes unary as value (default) in the aim to rotate only selected 3D plot. In the other case its value can be multiple : all 3D plots are rotated.
Note on default values :
All these listed properties and fields inherit from default values stored in a figure model. These default values can be seen and changed. To do so, use the get("default_figure") command : it returns a graphic handle on the figure model. Note that no graphic window is created by this command. The next created figures will inherit from this model (see example 2 below).

Examples

   lines(0) // disables vertical paging
  //Example 1
   set("figure_style","new") //create a figure and set the figure as the current selected one
   f=get("current_figure") //get the handle of the current figure :
                                           //if none exists, create a figure and return the corresponding handle
   f.figure_position
   f.figure_size=[200,200]
   f.background=2
   f.children  // man can see that an Axes entity already exists
   delete(f);
   f=gcf(); // macro shortcut <=> f=get("current_figure")
   f.pixmap = "on" // set pixmap status to on
   plot2d() // nothing happens on the screen...
   show_pixmap() // ...display the pixmap on screen
   //Example 2 : default_figure settings
   df=get("default_figure") // get the default values (shortcut is gdf() )
   // Let's change the defaults...
   df.color_map=hotcolormap(128)
   df.background= 110 // set background toa kind of yellow (Note that we are using a color index inside the color_map previously redefined)
   scf(122); // creates new figure number 122 with the new default
   plot2d()
   scf(214);
   t=-%pi:0.3:%pi;
   plot3d(t,t,sin(t)'*cos(t),35,45,'X@Y@Z',[15,2,4]);

See Also

lines , set , get , scf , gcf , gdf , gca , gda , axes_properties , show_pixmap , clear_pixmap , , hotcolormap ,

Author

Djalel ABDEMOUCHE


fplot2d

Scilab Function
Last update : 08/06/2005

fplot2d - 2D plot of a curve defined by a function

Calling Sequence

fplot2d(xr,f,[style,strf,leg,rect,nax])
fplot2d(xr,f,<opt_args>)

Parameters

  • xr : vector.
  • f : external of type y=f(x) i.e. a scilab function or a dynamically linked routine referred to as a string.
  • style,strf,leg,rect,nax : see plot2d
  • <opt_args> : see plot2d

Description

fplot2d plots a curve defined by the external function f . The curve is approximated by a piecewise linear interpolation using the points (xr(i),f(xr(i)) . The values of f(x) are obtained by feval(xr,f) .

Enter the command fplot2d() to see a demo.

Examples

deff("[y]=f(x)","y=sin(x)+cos(x)")
x=[0:0.1:10]*%pi/10;
fplot2d(x,f)
clf();
fplot2d(1:10,'parab')

See Also

plot2d , feval , paramfplot2d ,

Author

J.Ph.C.


fplot3d1

Scilab Function
Last update : 08/06/2005

fplot3d1 - 3D gray or color level plot of a surface defined by a function

Calling Sequence

fplot3d1(xr,yr,f,[theta,alpha,leg,flag,ebox])
fplot3d1(xr,yr,f,<opt_args>)

Parameters

  • xr : row vector of size n1.
  • yr : row vector of size n2.
  • f : external of type z=f(x,y).
  • theta,alpha,leg,flag,ebox : see plot3d1 .
  • <opt_args> : see plot3d .

Description

fplot3d1 plots a 3D gray or color level plot of a surface defined by the external function f on the grid defined by xr and yr .

Enter the command fplot3d1() to see a demo.

Examples

deff('z=f(x,y)','z=x^4-y^4')
x=-3:0.2:3 ;y=x ;
clf() ;fplot3d1(x,y,f,alpha=5,theta=31)

See Also

plot3d1 ,

Author

J.Ph.C.


fplot3d

Scilab Function
Last update : 08/06/2005

fplot3d - 3D plot of a surface defined by a function

Calling Sequence

fplot3d(xr,yr,f,[theta,alpha,leg,flag,ebox])
fplot3d(xr,yr,f,<opt_args>)

Parameters

  • xr : row vector of size n1.
  • yr : row vector of size n2.
  • f : external of type z=f(x,y).
  • theta,alpha,leg,flag,ebox : see plot3d .
  • <opt_args> : see plot3d .

Description

fplot3d plots a surface defined by the external function f on the grid defined by xr and yr .

Enter the command fplot3d() to see a demo.

Examples

deff('z=f(x,y)','z=x^4-y^4')
x=-3:0.2:3 ;y=x ;
clf() ;fplot3d(x,y,f,alpha=5,theta=31)

See Also

plot3d ,

Author

J.Ph.C.


gainplot

Scilab Function
Last update : 08/06/2005

gainplot - magnitude plot

Calling Sequence

gainplot(sl,fmin,fmax [,step] [,comments] )
gainplot(frq,db,phi [,comments])
gainplot(frq, repf [,comments])

Parameters

  • sl : list ( syslin SIMO linear system).
  • fmin,fmax : real scalars (frequency interval).
  • step : real (discretization step (logarithmic scale))
  • comments : string
  • frq : matrix (row by row frequencies)
  • db,phi : matrices (magnitudes and phases corresponding to frq )
  • repf : complex matrix. One row for each frequency response.

Description

Same as Bode but plots only the magnitude.

Examples

s=poly(0,'s')
h=syslin('c',(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01))
gainplot(h,0.01,100,'(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01)')
clf()
h1=h*syslin('c',(s^2+2*0.1*15.1*s+228.01)/(s^2+2*0.9*15*s+225))
gainplot([h1;h],0.01,100,['h1';'h'])

See Also

bode , black , nyquist , freq , repfreq , g_margin , p_margin ,


gca

Scilab Function
Last update : 27/01/2004

gca - Return handle of current axes.

Calling Sequence

a = gca()

Parameters

  • a : handle, the handle of the current axes entity.

Description

This routine returns the handle of the current axes for the current figure.

Examples

    set("figure_style","new") //create a figure
    subplot(211)
    a=gca() //get the current axes
    a.box="off";
    t=-%pi:0.3:%pi;plot3d(t,t,sin(t)'*cos(t),80,50,'X@Y@Z',[5,2,4]);
    subplot(212)
    plot2d(); //simple plot
    a=gca() //get the current axes
    a.box="off";
    a.x_location="middle";
    a.parent.background=4;
    delete(gca()) // delete the current axes
    xdel(0) //delete a graphics window

See Also

gda , gcf , gce , get , graphics_entities ,

Author

Djalel ABDEMOUCHE


gce

Scilab Function
Last update : 22/12/2005

gce - Get current entity handle.

Calling Sequence

e = gce()

Parameters

  • e : handle, the handle of the current entity.

Description

This routine returns the handle of the last created (and still existent) entity.

Examples

    set("figure_style","new") //create a figure entity
    a=gca() //get the handle of the newly created axes
    a.data_bounds=[1,1;10,10];
    a.axes_visible = 'on' ;
    for i=1:5
      xfrect(7-i,9-i,3,3);
      e=gce();
      e.background=i;
     end
    delete(); // delete current entity
    delete(gce()); // delete current entity
    delete(gcf()); // delete current figure

See Also

gcf , gca , get , graphics_entities ,

Author

Djalel ABDEMOUCHE


gcf

Scilab Function
Last update : 08/06/2005

gcf - Return handle of current graphic or GUI window.

Calling Sequence

h = gcf()

Parameters

  • h : handle or integer.

Description

This routine returns the handle of the current graphic or GUI window. If the current figure is a graphic one gcf() returns a handle on it. If the current figure is a uicontrol one gcf() returns it's figure number.

Examples

    set("figure_style","new") //create a figure
    f=gcf()
    f.figure_size= [610,469]/2;
    f.figure_name= "Foo";

    f=figure(); // create a figure
    h=uicontrol(f,'style','listbox','position', [10 10 150 160]);// create a listbox
    set(h, 'string', "item 1|item 2|item3");// fill the list
    set(h, 'value', [1 3]); // select item 1 and 3 in the list
    gcf()

    scf(0); //make graphic window 0 the current figure
    gcf()  // return the graphic handle of the current figure

    figure(f) //make GUI  window f the current figure
    gcf()

See Also

gdf , gca , gce , get , scf , set , graphics_entities , uicontrol ,

Author

Serge Steer, INRIA


gda

Scilab Function
Last update : 13/12/2005

gda - Return handle of default axes.

Calling Sequence

a = gda()
a = get("default_axes")

Parameters

  • a : handle, the handle of the default axes.

Description

The default axes is a graphic entity which is never drawn. It is used as a reference for the axes properties default values. These default properties values are used to initialize new axes inside figures.

The gda function returns the handle on the default axes. The user can use this handle to set or get the axes properties default values.

Note that an equivalent default graphic entity exists for figure entities too (see gdf ).

Examples

    a=gda() // get the handle of the model axes
    // set its' properties
    a.box="off";
    a.foreground=2;
    a.labels_font_size=3;
    a.labels_font_color=5;
    a.sub_tics=[5 5 3];
    a.x_location="top";

    //now used the model axes for drawing
    set("figure_style","new")
    subplot(211) //create an axes entity
    plot2d()

   // set other model's properties
    a.background=color('gray')
    a.grid=[5 5 5];
    subplot(212)
    t=0:0.1:5*%pi;
    plot2d(sin(t),cos(t))

    set(a,"default_values",1); // return to the  default values of the model
                               // see sda() function
    clf()
    plot2d(sin(t),cos(t))

See Also

gdf , sda , sdf , clf , gca , get , graphics_entities ,

Author

Djalel ABDEMOUCHE


gdf

Scilab Function
Last update : 08/06/2005

gdf - Return handle of default figure.

Calling Sequence

f = gdf()
f = get("default_figure")

Parameters

  • f : handle, the handle of the default figure.

Description

The default figure is a graphic entity which is never drawn. It is used as a reference for the figure properties default values. These default properties values are used to initialize new figures.

The gdf function returns the handle on the default figure. The user can use this handle to set or get the figure properties default values.

Note that an equivalent default graphic entity exists for axes entities too (see gda ).

Examples

   set old_style off
   f=gdf() // get the handle of the model figure
   // setting its' properties
   f.background=7;
   f.figure_name="Function gdf()";
   f.figure_position=[-1 100];
   f.auto_resize="off";
   f.figure_size=[300 461];
   f.axes_size=[600 400];
   plot2d() //create a figure
   scf(1);
   plot3d() //create a second figure
   set(f,"default_values",1); // return to the  default values of figure's model
                              // see sdf() function
   scf(2);
   plot2d()

See Also

gda , sdf , sda , gcf , get , scf , set , graphics_entities ,

Author

Djalel ABDEMOUCHE


genfac3d

Scilab Function
Last update : 16/06/2004

genfac3d - calcule les facettes d'une surface 3D non-paramétrique

Calling Sequence

[xx,yy,zz]=genfac3d(x,y,z,[mask])

Parameters

  • xx,yy,zz : matrices de taille (4,n-1xm-1). xx(:,i) , yy(:,i) et zz(:,i) sont respectivement les coordonnées des 4 points de la facette numéro i.
  • x : vecteur de taille m.
  • y : vecteur de taille n.
  • z : matrice de taille (m,n). z(i,j) est la hauteur de la surface au point (x(i),y(j)).
  • mask : matrice booléenne optionnelle de même taille que z utilisée pour sélectionner les termes de z à représenter par des facettes.

Description

genfac3d calcule la représentation en facettes à 4 points d'une surface 3D non-paramétrique z=f(x,y) définie par x , y et z .

Examples

t=[0:0.3:2*%pi]'; z=sin(t)*cos(t');
[xx,yy,zz]=genfac3d(t,t,z);
plot3d(xx,yy,zz)

See Also

eval3dp , plot3d ,


geom3d

Scilab Function
Last update : 22/12/2005

geom3d - projection 3D vers 2D après une instruction de dessin 3D

Calling Sequence

[x,y]=geom3d(x1,y1,z1)

Parameters

  • x1,y1,z1 : vecteur réels de même taille (points 3D).
  • x,y : vecteurs réels de même taille que x1 , y1 et z1 .

Description

Après l'utilisation d'une instruction de dessin 3D du type plot3d , plot3d1 ou param3d , geom3d permet de faire la correspondance entre un point de l'espace 3D (x1(i),y1(i),z1(i)) et le point correspondant (x(i),y(i)) dans le plan projeté 2D. On peut ainsi utiliser les primitives graphiques avec (x,y) pour superposer des dessins.

Examples

deff("[z]=surf(x,y)","z=sin(x)*cos(y)")
t=%pi*(-10:10)/10;
// 3D plot of the surface
fplot3d(t,t,surf,35,45,"X@Y@Z")
// now (t,t,sin(t).*cos(t)) is a curve on the surface
// which can be drawn using geom3d and xpoly
[x,y]=geom3d(%pi/2,0,surf(%pi/2,0))

Author

J.Ph.C.


getcolor

Scilab Function
Last update : 07/07/2004

getcolor - opens a dialog to show colors in the current colormap

Calling Sequence

c=getcolor(title,[cini])
c=getcolor()

Parameters

  • title : string, dialog title.
  • cini : initial selected color id. Default value is 1.
  • c : selected color id or [] if the user has clicked on the "Cancel" button.

Description

getcolor opens a window displaying the palette of the current colormap. The user can click on a color to show its id and RGB values. getcolor returns the id of the selected color or [] if the user has clicked on the "Cancel" button

See Also

color , colormap , getmark , getfont ,


getfont

Scilab Function
Last update : 12/01/2004

getfont - dialog to select font

Calling Sequence

[fId,fSize]=getfont()
[fId,fSize]=getfont(str)
fnt=getfont()
fnt=getfont(str)
fnt=getfont(S=str,font=[fId,fSize])

Parameters

  • str : character (e.g. "a")
  • fId : integer, the number of the selected font
  • fSize : integer, the size of the selected font
  • fnt : vector [fId,fSize]

Description

getfont opens a graphic window to select a font. User has to select a font and a size clicking on the corresponding displayed character. Killing a keyboard key changes the displayed character.

Examples

[fId,fSize]=getfont();
xset("font",fId,fSize)
plot2d(0,0,rect=[0 0 10 10],axesflag=0)
xstring(5,5,"string")

See Also

xset , getmark , xlfont ,


getlinestyle

Scilab Function
Last update : 10/10/2005

getlinestyle - dialog to select linestyle

Calling Sequence

k=getlinestyle()

Parameters

  • k : integer, selected linestyle or [] if the "Cancel" button has been clicked.

Description

getlinestyle opens a graphic window to select a line style.

Examples

set("figure_style","new")
x=0:0.1:10;
plot2d(x,sin(x))
e=gce(); // store the Compound containing the plot
e.children(1).line_style = getlinestyle();

See Also

getmark ,


getmark

Scilab Function
Last update : 10/10/2005

getmark - dialog to select mark (symbol)

Calling Sequence

[mark,mrkSize]=getmark()

Parameters

  • mark : integer, the number of the selected mark
  • mrkSize : integer, the size of the selected mark

Description

getmark opens a graphic window to select a mark (symbol).

Examples

x=0:0.1:10;
set("figure_style","new")
[mark,mrkSize]=getmark();
plot2d(x,sin(x),style=-mark);
clf();
plot2d(x,sin(x))
e=gce(); // store the Compound containing the plot
[mark,mrkSize]=getmark();
e.children(1).mark_style = mark;

See Also

, getfont , getlinestyle ,


getsymbol

Scilab Function
Last update : 14/12/2005

getsymbol - boîte de dialogue pour sélectionner un marqueur

Calling Sequence

c=getsymbol([title])

Parameters

  • title : chaîne de caractères, titre de la boîte
  • c : vecteur de taille 2 [n,sz] .

Description

Cette fonction est obsolete, il est conseillé d'utiliser la fonction getmark ou l'éditeur interactif de propiétés graphiques.

getsymbol ouvre une boîte de dialogue avec pour titre title , où l'utilisateur peut choisir un marqueur ainsi que sa taille. getsymbol renvoie le numéro du marqueur n et le code de sa taille sz .

See Also

getmark , xset ,


get

Scilab Function
Last update : 08/06/2005

get - Retrieve a property value from a graphics entity or an User Interface object.

Calling Sequence

h=get(prop)
val=get(h,prop)
val=h.prop
val=get(n,prop)

Parameters

  • h : handle, the handle of the entity to retrieve a property. h can be a vector of handles, in which case get returns the property's value for all objects identified by h(i).
  • n : integer, the handle of the User Interface object to retrieve a property.
  • prop : character string name of the property.
  • val : scilab object value of the property.

Description

This routine can be used to retrieve the value of a specified property graphics entity or a GUI object. If the handle is not specified, the current object is taken as the default handle. It is also used to return a list of all children, parent, or type for the input handle if this one is specified. Otherwise, the current axes object is taken as the default input.

Property name are character strings.

See graphics_entities for details about properties' names and values for graphics entities.

See uicontrol for details about properties' names and values for User Interface objects.

For graphics entities handle it is possible to use a dot notation like h.background instead of get .

Examples

  // for graphics entities
    clf()
    get("old_style") // check the state of the graphics' style
    set("figure_style","new") //create a figure
    get("figure_style") // check the style of the graphics' figure

    // simple graphics objects
    subplot(121);
    x=[-.2:0.1:2*%pi]';
    plot2d(x-2,x.^2);
    subplot(122);
    xrect(.2,.7,.5,.2);
    xrect(.3,.8,.3,.2);
    xfarc(.25,.55,.1,.15,0,64*360);
    xfarc(.55,.55,.1,.15,0,64*360);
    xstring(0.2,.9,"Example <<A CAR>>");

    h=get("hdl") //get the object newly created
    h.font_size=3;

    f=get("current_figure") //get the current figure
    f.figure_size
    f.figure_size=[700 500];
    f.children
    f.children(2).type
    f.children(2).children
    f.children(2).children.children.thickness=4;

    a=get("current_axes") //get the current axes
    a.children.type
    a.children.foreground //get the foreground color of a set of graphics objects
    a.children.foreground=9;

  // for  User Interface objects
   h=uicontrol('string', 'Button'); // Opens a window with a  button.
   p=get(h,'position'); // get the geometric aspect of the button
   disp('Button width: ' + string(p(3))); // print the width of the button
   close(); // close figure

See Also

uicontrol , set ,

Author

Djalel ABDEMOUCHE


glue

Scilab Function
Last update : 10/10/2005

glue - glue a set of graphics entities into an Compound.

Calling Sequence

glue(H)
h_agreg=glue(H)

Parameters

  • H : a vector of handle.
  • h_agreg : a handle, the handle on the Compound entity.

Description

Given a vector of handles, this function glue the corresponding entities in a single Compound and returns the handle on this new entity.

Examples

See Also

get , set , move , unglue , graphics_entities ,

Author

Djalel ABDEMOUCHE


graduate

Scilab Function
Last update : 16/06/2004

graduate - graduations simplifiées des axes 2D

Calling Sequence

[xi,xa,np]=graduate( xmi, xma,n1,n2)
[xi,xa,np]=graduate( xmi, xma)

Parameters

  • xmi,xma : scalaire réel
  • n1, n2 : entiers avec comme valeurs par défaut 3, 10
  • xi, xa : scalaire réel
  • np : entier

Description

graduate recherche l'intervalle minimum [xi,xa] et un nombre de graduations np tels que :

xi <= xmi <= xma <= xa

xa - xi / np = k(10^n) , k dans [1 3 5] pour un entier n

n1 < np < n2

Examples

  y=(0:0.33:145.78)';
  xbasc();plot2d1('enn',0,y)
  [ymn,ymx,np]=graduate(mini(y),maxi(y))
  rect=[1,ymn,prod(size(y)),ymx];
  xbasc();plot2d1('enn',0,y,1,'011',' ',rect,[10,3,10,np])

See Also

xsetech , plot2d ,

Author

S. Steer 1992;


graphics_entities nouveau graphique figure_style old_style

Scilab Data type
Last update : 13/12/2005

graphics_entities - description of the graphics entities data structures

nouveau graphique - description of the graphics entities data structures

figure_style - description of the graphics entities data structures

old_style - description of the graphics entities data structures

Description

Scilab graphics is based on two differents modes. In the "old" mode, the graphics functions are stored to enable redisplay, zoom and rotations. In the "new" mode, each graphics window and the drawing it contains are represented by hierchical entities. The hierachy top level is the Figure. Each Figure defines at least one child of type Axes. Each Axes entity contains a set of leaf entities which are the basic graphics objects like Polylines, Rectangles, Arcs, Segs,... It can also contain an Compound type which are recursive sets of entities. The main interest of the new graphic mode is to make property change easier. This new graphics'mode provides a set of high-level graphing routines (see set , get ) used to control objects' properties such as data, coordinates and scaling, color and appearences without requiring to replay the initial graphics commands.

Graphics entities are associated to Scilab variables of type handle . The handle is a unique identifier which is associated to each instance of a created graphical entity. Using this handle, it will be possible to reach entities' properties through "set" and "get" routines. The handles are also used to manipulate graphics objects, to move them, to make copies or delete them.

To set the current graphics window mode we can use these following instructions: set("figure_style","new") to have a graphics window under the "new" mode or set("figure_style","old ") for the "old" mode.

The instructions set("old_style","off") and set("old_style","on") are used to set the default mode to be used when a new graphics window is created.

Figure: The figure entity is the top level of the graphics entities hierarchy. This entity defines the parameters for the figure itself as well as the parameters' default values for the children creation. The figure children are the Axes entities.

The handle on the current figure (the figure used where the drawing are sent) may be got using get("current_figure") and it may be set using set("current_figure",h) , where h is either a handle on a figure or a figure_id in this last case if the figure does not already exists , it is created

See figure_properties for details.

Axes:

The Axes entity is the second level of the graphics entities hierarchy. This entity defines the parameters for the change of coordinates and the axes drawing as well as the parameters' default values for its children creation. See axes_properties for details. The handle on the current Axes may be got using get("current_axes") .

Compound: The Compound entity is just a vector of children and with a single property (visibility property). It is used to glue a set of entities together.

See glue , unglue and Compound_properties functions.

Axis: The Axis entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for axis scaling and appearance.

See axis_properties for details.

Polyline: The polyline entity is a leaf of the graphics entities hierarchy. It defines 2D and 3D polylines and polylines extensions drawing properties.

See polyline_properties for details.

Arc: The Arc entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for ellipses and part of ellipses.

See arc_properties for details.

Rectangle: The Rectangle entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for rectangles and filled rectangles.

See rectangle_properties for details.

Surface: The Surface entity is a leaf of the graphics entities hierarchy. It has sub types Fac3d or Plot3d . This entity defines the parameters for 3d surface plots.

See surface_properties for details.

Fec: The Fec entity is a leaf of the graphics entities hierarchy. It represents 2D finite elements plots .

See fec_properties for details.

Grayplot: The Grayplot entity is a leaf of the graphics entities hierarchy. It represents 2D plots of surface using colors and images.

See grayplot_properties for details.

Matplot: The Matplot entity is a leaf of the graphics entities hierarchy. It represents 2D plots using integer matrices.

See Matplot_properties for details.

Segs: The Segs entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for a set of colored segments or colored arrows.

See segs_properties for details.

Champ: The Champ entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for a 2D vector field.

See champ_properties for details.

Text: The Text entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for string drawing.

See text_properties for details.

Label: The Labels entity are children of the Axes graphics entity. This entity defines the parameters for the 3 x,y and z labels and title drawn on a graphics window.

See label_properties for details.

Legend: The Legend entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for legends drawn below plot2dx graphs. This entity requires further developments.

See legend_properties for details.

Examples

  //Play this example line per line

  set("figure_style","new") //create a figure in entity mode

  //get the handle on the Figure entity and display its properties
  f=get("current_figure")
  a=f.children // the handle on the Axes child
  x=(1:10)';  plot2d(x,[x.^2 x.^1.5])
  e=a.children //Compound of 2 polylines

  p1=e.children(1) //the last drawn polyline properties
  p1.foreground=5;  // change the polyline color
  e.children.thickness=5; // change the thickness of the two polylines

  delete(e.children(2))

  move(e.children,[0,30]) //translate the polyline

  a.axes_bounds=[0 0 0.5 0.5];

  subplot(222) //create a new Axes entity
  plot(1:10);
  a1=f.children(1); //get its handle
  copy(e.children,a1); //copy the polyline of the first plot in the new Axes
  a1.data_bounds=[1 0;10 100]; //change the Axes bounds

  set("current_figure",10) //create a new figure with figure_id=10
  plot3d() //the drawing are sent to figure 10
  set("current_figure",f) //make the previous figure the current one
  plot2d(x,x^3)  //the drawing are sent to the initial figure

See Also

set , get , move , draw , delete , object_editor , plot , surf ,


graycolormap

Scilab Function
Last update : 24/03/2004

graycolormap - linear gray colormap

Calling Sequence

cmap=graycolormap(n)

Parameters

  • n : integer >= 1, the colormap size.
  • cmap : matrix with 3 columns [R,G,B] .

Description

graycolormap computes a colormap with n gray colors varying linearly from black to white.

Examples

xset("colormap",graycolormap(32))
plot3d1()

See Also

colormap , hotcolormap , jetcolormap , xset ,


grayplot_properties

Scilab Data type
Last update : 09/12/2005

grayplot_properties - description of the grayplot entities properties

Description

The Grayplot entity is a leaf of the graphics entities hierarchy. It represents 2D plots of surface using colors and images (see grayplot , Sgrayplot , fgrayplot and Sfgrayplot ).

parent: This property contains the handle of the parent. The parent of the grayplot entity should be of the type "Axes" .
children: This property contains a vector with the children of the handle. However, grayplot handles currently do not have any children .
visible: This field contains the visible property value for the entity . It should be "on" or "off" . By default, the plot is visible, the value's property is "on" . If "off" the plot is not drawn on the screen.
data: This field defines a tlist data structure of type "grayplotdata" composed of a row and column indices of each element : the x and y grid coordinates are contained respectively in data.x and data.y . The complementary field named data.z is the value of the surface at the point (x(i),y(j)) (scaled mode) or the centered value of the surface defined between two consecutive x(i) and y(j) (direct mode). If data_mapping (see below) is set to "scaled" , the entire z data is used to perform a color interpolation whereas, if data_mapping 's value is "direct" , the last line and column of the z data indices are ignored and the color is determined directly in the colormap by the indices of the submatrix data.z(1:$-1,1:$-1) .
data_mapping: By default the value of this property is "scaled" : the indices of painting colors are proportional to the value z coordinates. In the other case, the property takes as value "direct" where the plot is a grayplot and the indices of painting colors are given by the data (see above).
user_data: This field can be use to store any scilab variable in the grayplot data structure, and to retreive it.

Examples

   set("figure_style","new") //create a figure

   m=5;n=5;
   M=round(32*rand(m,n));
   grayplot(1:m,1:n,M)

   a=get("current_axes");
   a.data_bounds=  [-1,-1;7,7]
   h=a.children

   h.data_mapping="direct";

   // A 2D ploting of a matrix using colors
   xbasc()
   a=get("current_axes");
   a.data_bounds=  [0,0;4,4];

   b=5*ones(11,11); b(2:10,2:10)=4; b(5:7,5:7)=2;
   Matplot1(b,[1,1,3,3])  ;

   h=a.children
   for i=1:7
    xclick(); // click the mouse to sets Matplot data
    h.data=h.data+4;
   end

See Also

set , get , delete , grayplot , Matplot , Matplot1 , graphics_entities , Matplot_properties ,

Author

Djalel ABDEMOUCHE & F.Leray


grayplot

Scilab Function
Last update : 08/06/2005

grayplot - 2D plot of a surface using colors

Calling Sequence

grayplot(x,y,z,[strf,rect,nax])
grayplot(x,y,z,<opt_args>)

Parameters

  • x,y : real row vectors of size n1 and n2.
  • z : real matrix of size (n1,n2). z(i,j) is the value of the surface at the point (x(i),y(j)).
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following: rect, nax, strf or axesflag and frameflag (see plot2d and plot2d_old_version ).
  • strf,rect,nax : see plot2d .

Description

grayplot makes a 2D plot of the surface given by z on a grid defined by x and y . Each rectangle on the grid is filled with a gray or color level depending on the average value of z on the corners of the rectangle.

Enter the command grayplot() to see a demo.

Examples

x=-10:10; y=-10:10;m =rand(21,21);
grayplot(x,y,m,rect=[-20,-20,20,20])
t=-%pi:0.1:%pi; m=sin(t)'*cos(t);
clf()
grayplot(t,t,m)

See Also

fgrayplot , plot2d , Sgrayplot , Sfgrayplot ,

Author

J.Ph.C.


graypolarplot

Scilab Function
Last update : 08/06/2005

graypolarplot - Polar 2D plot of a surface using colors

Calling Sequence

graypolarplot(theta,rho,z,[strf,rect])

Parameters

  • rho : a vector with size n1, the discretization of the radius
  • theta : a vector with size n2, the discretization of the the angle.
  • z : real matrix of size (n1,n2). z(i,j) is the value of the surface at the point (rho(i),theta(j)).
  • strf : is a string of length 3 "xy0" .
    • default The default is "030" .
    • x : controls the display of captions.
      • x=0 : no captions.
      • x=1 : captions are displayed. They are given by the optional argument leg .
    • y : controls the computation of the frame.
      • y=0 : the current boundaries (set by a previous call to another high level plotting function) are used. Useful when superposing multiple plots.
      • y=1 : the optional argument rect is used to specify the boundaries of the plot.
      • y=2 : the boundaries of the plot are computed using min and max values of x and y .
      • y=3 : like y=1 but produces isoview scaling.
      • y=4 : like y=2 but produces isoview scaling.
      • y=5 : like y=1 but plot2d can change the boundaries of the plot and the ticks of the axes to produce pretty graduations. When the zoom button is activated, this mode is used.
      • y=6 : like y=2 but plot2d can change the boundaries of the plot and the ticks of the axes to produce pretty graduations. When the zoom button is activated, this mode is used.
      • y=7 : like y=5 but the scale of the new plot is merged with the current scale.
      • y=8 : like y=6 but the scale of the new plot is merged with the current scale.
  • leg : a string. It is used when the first character x of argument strf is 1. leg has the form "leg1@leg2@...." where leg1 , leg2 , etc. are respectively the captions of the first curve, of the second curve, etc. The default is " " .
  • rect : This argument is used when the second character y of argument strf is 1, 3 or 5. It is a row vector of size 4 and gives the dimension of the frame: rect=[xmin,ymin,xmax,ymax] .

Description

Takes a 2D plot of the surface given by z on a polar coordinate grid defined by rho and theta . Each grid region if filled with a gray or color level depending on the average value of z on the corners of the grid.

Examples

  rho=1:0.1:4;theta=(0:0.02:1)*2*%pi;
  z=30+round(theta'*(1+rho^2));
  f=gcf();
  f.color_map= hotcolormap(128);
  clf();graypolarplot(theta,rho,z)


gr_menu

Scilab Function
Last update : 16/06/2004

gr_menu - petit éditeur graphique interactif

Calling Sequence

[sd1]=gr_menu([sd,flag,no_frame])

Parameters

  • sd : liste (sortie de gr_menu ), ou vecteur de longueur 4 [xmin,ymin,xmax,ymax] donnant les bornes du dessin).
  • sd1 : liste (objets graphiques créés avec gr_menu
  • flag, noframe : entiers valant 0 ou 1. Utiliser flag=1 pour le mode non-interactif (i.e. pour redessiner des graphiques déjà créés avec gr_menu ) et no_frame=1 pour supprimer le cadre autour des graphiques faits avec gr_menu .

Description

gr_menu est petit éditeur graphique interactif. Quand on exécute gr_menu() , 3 nouveaux menus, Objects , Settings et Edit sont ajoutés à la fenêtre graphique courante. Utiliser l'article Exit du menu Edit pour sortir de gr_menu .

Les graphiques sont sauvés sous forme d'une liste pouvant être donnée en entrée de gr_menu .

[sd]=gr_menu([xmin,ymin,xmax,ymax]): lance gr_menu avec un cadre donné
[sd]=gr_menu();: lance gr_menu avec le cadre par défaut [0 0 100 100].
[sd]=gr_menu(sd): redessine les graphiques stockés dans sd et entre en mode interactif.
[sd]=gr_menu(sd,1): redessine uniquement les graphiques stockés dans sd .
[sd]=gr_menu(sd,1,1) : redessine uniquement les graphiques stockés dans sd et aucun cadre n'est dessiné.

Author

S.S. & J.Ph.C.; ; ; ; ;


hist3d

Scilab Function
Last update : 16/06/2004

hist3d - représentation 3D d'un histogramme

Calling Sequence

hist3d(f,[theta,alpha,leg,flag,ebox])
hist3d(list(f,x,y),[theta,alpha,leg,flag,ebox])

Parameters

  • f : matrice de taille (m,n) définissant l'histogramme f(i,j)=F(x(i),y(j)) , où x et y sont considérés égaux à 0:m et 0:n .
  • list(f,x,y) : où f est une matrice de taille (m,n) définissant l'histogramme f(i,j)=F(x(i),y(j)) , avec x et y deux vecteurs de tailles respectives (1,n+1) et (1,m+1).
  • theta,alpha,leg,flag,ebox : voir plot3d .

Description

hist3d représente un histogramme 2D dans l'espace. Les valeurs sont associées aux intervalles [x(i) x(i+1)[ X [y(i) y(i+1)[ .

Taper hist3d() pour voir une démonstration de la fonction.

See Also

histplot , plot3d ,

Author

Steer S. & JPhilippe C.


histplot

Fonction Scilab
Last update : 08/06/2005

histplot - dessine un histogramme

Calling Sequence

histplot(n, data, <opt_args>)
histplot(x, data, <opt_args>)

Parameters

  • n : entier strictement positif (nombre de classes)
  • x : vecteur (strictement croissant) definissant les classes
  • data : vecteur (contenant les données à analyser)
  • <opt_args> : Représente une séquence de la forme clé1=valeur1, clé2=valeur2 ,... où clé1 , clé2,... peut être n'importe quel paramètre optionnel de plot2d (style,strf,leg, rect,nax, logflag,frameflag, axesflag) ou encore normalization. Pour ce dernier la valeur correspondante est un scalaire booléen (la valeur par défaut étant %t).

Description

Cette fonction dessine un histogramme des données contenues dans le vecteur data en utilisant les classes x . Quand le nombre de classes n est fourni au lieu de x , celles-ci sont définies de manière équirépartie et telles que x(1) = min(data) < x(2) = x(1) + dx < ... < x(n+1) = max(data) avec dx = (x(n+1)-x(1))/n.

Les classes sont définies par C1 = [x(1), x(2)] puis Ci = ] x(i), x(i+1)] pour i = 2,3,...,n. En notant Nmax le nombre total de données (Nmax = length(data)) et Ni le nombre de données se situant dans Ci, la valeur de l'histogramme pour x appartenant à Ci est égale à Ni/(Nmax (x(i+1)-x(i))) quand normalization est vrai (comportement par défaut) et sinon elle vaut simplement Ni. Quand l'histogramme est normalisé il vérifie la propriété suivante :

            x(n+1)
           /
           |   h(x) dx = 1,  quand x(1)<=min(data) et max(data) <= x(n+1))
           /
           x(1)

N'importe quel paramètre optionnel de plot2d peut être passé à histplot ; par exemple pour dessiner votre histogramme avec la couleur numéro 2 (du bleu si vous utilisez la carte des couleurs standard) tout en restreignant le dessin au le rectangle [-3,3]x[0,0.5], vous pouvez utiliser histplot(n,data, style=2, rect=[-3,0,3,0.5]).

La commande histplot() sans argument montre un example.

Examples

// exemple #1: variations sur l'histogramme d'un échantillon gaussien N(0,1)
d=rand(1,10000,'normal');
clf();histplot(20,d)
clf();histplot(20,d,normalization=%f)
clf();histplot(20,d,leg='rand(1,10000,''normal'')',style=5)
clf();histplot(20,d,leg='rand(1,10000,''normal'')',style=16, rect=[-3,0,3,0.5]);

// exemple #2: histogramme d'un échantillon de loi binomiale B(6,0.5)
d = grand(1000,1,"bin", 6, 0.5);
c = linspace(-0.5,6.5,8);
xbasc()
subplot(2,1,1)
   histplot(c, d, style=2)
   xtitle("l''histogramme normalisé")
subplot(2,1,2)
   histplot(c, d, normalization=%f, style=5)
   xtitle("l''histogramme non normalisé")

// exemple #3: histogramme d'un échantillon de loi exponentielle E(lambda)
lambda = 2;
X = grand(100000,1,"exp", 1/lambda);
Xmax = max(X);
xbasc()
histplot(40, X, style=2)
x = linspace(0,max(Xmax),100)';
plot2d(x,lambda*exp(-lambda*x),strf="000",style=5)
legend(["histogramme d''un échantillon E(lambda)" "densité exacte"]);
// Rmq: si vous utilisez l'ancien mode graphique, la légende peut s'obtenir avec :
// legends(["histogramme d''un échantillon E(lambda)" "densité exacte"],[2 5],"ur");

See Also

hist3d , plot2d , dsearch ,


hotcolormap

Scilab Function
Last update : 24/03/2004

hotcolormap - red to yellow colormap

Calling Sequence

cmap=hotcolormap(n)

Parameters

  • n : integer >= 3, the colormap size.
  • cmap : matrix with 3 columns [R,G,B] .

Description

hotcolormap computes a colormap with n hot colors varying from red to yellow.

Examples

xset("colormap",hotcolormap(32))
plot3d1()

See Also

colormap , graycolormap , jetcolormap , xset ,


hsv2rgb

Scilab Function
Last update : 13/06/2005

hsv2rgb - Converts HSV colors to RGB

Calling Sequence

[r,g,b] = hsv2rgb(h,s,v)
rgb = hsv2rgb(h,s,v)
[r,g,b] = hsv2rgb(hsv)
rgb = hsv2rgb(hsv)

Parameters

  • h : a vector of size n. The "hue" values.
  • s : a vector of size n. The "saturation" values.
  • v : a vector of size n. The "value" values
  • hsv : a n x 3 matrix. Each row contains a [hue saturation value] tripple.
  • r : a column vector of size n. The associated "red" values.
  • g : a column vector of size n. The associated "green" values.
  • b : a column vector of size n. The associated "blue" values.
  • rgb : a n x 3 matrix. Each row contains a [red green blue] tripple.

Description

The function hsv2rgb converts colormaps between the RGB and HSV color spaces. As hue varies from 0 to 1.0, the corresponding colors vary from red through yellow, green, cyan, blue, magenta, and back to red, so that there are actually red values both at 0 and 1.0. As saturation varies from 0 to 1.0, the corresponding colors (hues) vary from unsaturated (shades of gray) to fully saturated (no white component). As value, or brightness, varies from 0 to 1.0, the corresponding colors become increasingly brighter.

Examples

    t=[0:0.3:2*%pi]'; z=sin(t)*cos(t');
    plot3d1(t,t,z)
    f=gcf();f.pixmap='on';
    for h=0:0.1:1
      hsv=[h*ones(32,1) linspace(0,1,32)' 0.7*ones(32,1)];
      f.color_map=hsv2rgb(hsv);
      show_pixmap()
      xpause(10000)
    end
    for v=0:0.1:1
      hsv=[ones(32,1) linspace(0,1,32)' v*ones(32,1)];
      f.color_map=hsv2rgb(hsv);
      show_pixmap()
      xpause(10000)
    end

Authors

Serge Steer INRIA


hsvcolormap

Scilab Function
Last update : 13/06/2005

hsvcolormap - Hue-saturation-value colormap

Calling Sequence

cmap = hsvcolormap(n)

Parameters

  • n : integer >= 1, the colormap size.
  • cmap : matrix with 3 columns [R,G,B] .

Description

hsvcolormap computes a colormap with n colors. This colormap varies the hue component of the hsv color model. The colors begin with red, pass through yellow, green, cyan, blue, magenta, and return to red. The map is particularly useful for displaying periodic functions.

Examples

    t=[0:0.1:2*%pi]'; z=sin(t)*cos(t');
    f=gcf();f.color_map=hsvcolormap(64);
     plot3d1(t,t,z,35,45,"X@Y@Z",[-2,2,2])

Authors

Serge Steer INRIA


isoview

Scilab Function
Last update : 12/01/2004

isoview - set scales for isometric plot (do not change the size of the window)

Calling Sequence

isoview(xmin,xmax,ymin,ymax)

Parameters

  • xmin,xmax,ymin,ymax : four real values

Description

This function is obsolete, use preferably the frameflag=4 plot2d option which enable window resizing.

isoview is used to have isometric scales on the x and y axes. It does not change the size of the graphics window. The rectangle xmin, xmax, ymin, ymax will be contained in the computed frame of the graphics window. isoview set the current graphics scales and can be used in conjunction with graphics routines which request the current graphics scale (for instance strf="x0z" in plot2d ).

Examples

t=[0:0.1:2*%pi]';
plot2d(sin(t),cos(t))
xbasc()
isoview(-1,1,-1,1)
plot2d(sin(t),cos(t),1,"001")
xset("default")

plot2d(sin(t),cos(t),frameflag=4)

See Also

square , xsetech ,

Author

Steer S.


jetcolormap

Scilab Function
Last update : 31/03/2004

jetcolormap - blue to red colormap

Calling Sequence

cmap=jetcolormap(n)

Parameters

  • n : integer >= 3, the colormap size.
  • cmap : matrix with 3 columns [R,G,B] .

Description

jetcolormap computes a colormap with n colors varying from blue, lightblue, green, yellow, orange then red

Examples

xset("colormap",jetcolormap(64))
plot3d1()

See Also

colormap , graycolormap , hotcolormap , xset ,


label_properties

Scilab Data type
Last update : 25/01/2006

label_properties - description of the Label entity properties

Description

The Label entity is a child of an Axes entity. When an Axes entity is built, the Title and Labels handles come with it and are part of the Axes properties. Therefore, the properties of those sub-objects are editable via the Axes handle (see gca and gda ). This entity defines the parameters for label drawing:

parent: This property contains the handle of the parent. The parent of the label entity should be of type "Axes" .

Note that, for now, Label entity is exclusively used in title , x_label , y_label and z_label building.

visible: This field contains the visible property value for the entity . It should be "on" or "off" .By default, the label is visible, the value's property is "on" . If "off" the label is not displayed on the screen.
text: This field is the character string vector which contains the label.
foreground: This field contains the color used to display the characters label and the line around the box if any. Its value should be a color index (relative to the current colormap).
background: This field contains the color used to fill the box if any. Its value should be a color index (relative to the current colormap).
fill_mode: This field takes the values "on" or "off" . If "on" a box is draw around the text with a line on its edge and a background.
font_style: Seven differents fonts are available : "Courrier", "Symbol", "Times", "Times Italic", "Times Bold", "User defined". The font_size property is an index in [0 6] which is associated to the previous font names.
font_size: The font_size property is used to select the type of size of the label. Its value should be an integer in between 0 and 5 which stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt.
font_angle: This scalar allows you to turn the label. The font is turned clockise with the angle given in degrees. Note that changing the font_angle will automatically disable the auto_rotation property.
auto_rotation: If "on" , Scilab computes automaticaly the best angle to turn the label for the display. If "off" , the label can be manually turned with the font_angle property.
position: This 2d vector allows you to place manually the label on the screen. The position is stored in the data units of the axes. Note that changing the font_angle will automatically disable the auto_position property.
auto_position: If "on" , Scilab computes automaticaly the best position in the graphic window for the display. If "off" , the label can be manually places with the position property.

Examples

   set("figure_style","new") //create a figure
   a=get("current_axes");
   a.title
   type(a.title)
   plot3d()
   a.x_label
   a.y_label
   a.z_label
   xtitle("My title","my x axis label", "Volume")
   a.z_label.text="Month"

   t=a.title;
   t.foreground=9;
   t.font_size=5;
   t.font_style=5;
   t.text="SCILAB";

   xlabel=a.x_label;
   xlabel.text=" Weight"
   xlabel.font_style= 5;
   a.y_label.foreground = 12;

See Also

set , get , delete , xtitle , graphics_entities , axes_properties , text_properties ,

Author

Djalel ABDEMOUCHE


legends

Scilab Function
Last update : 09/02/2006

legends - dessine des légendes de courbes 2D

Calling Sequence

legends(strings,style [,opt])
legends(strings,style,xy)

Parameters

  • strings : vecteur de chaînes de caractères, strings(i) est la légende de la ième courbe
  • style : vecteur ligne entier de taille n (les styles de dessin de chaque courbe, troisième paramètre de plot2d) ou une matrice d'entiers 2 x n, style(1,k) contenant le style pour la k-ième courbe et style(2,k) contient le style de ligne (si style(1,k)>0) ou la couleur du marqueur (si style(1,k)<0).
  • opt
    • 1 = coin en haut à droite 2 = coin en haut à gauche
    • 3 = coin en bas à gauche
    • 4 = coin en bas à droite
    • 5 = placement interactif avec la souris (par défaut)
  • xy : un vecteur [x,y] donnant les coordonnées du coin en haut à gauche de la boîte contenant la légende

Description

Dessine des légendes sur le dessin courant en utilisant des chaînes de caractères données.

En cas de placement interactif (opt=5) déplacer la boîte de la légende avec la souris et presser bouton de gauche pour la fixer.

Cette fonction permet de placer les légendes avec plus de liberté que l'argument leg de plot2d.

Examples

t=0:0.1:2*%pi;
plot2d(t,[cos(t'),cos(2*t'),cos(3*t')],[-1,2 3]);
legends(['cos(t)';'cos(2*t)';'cos(3*t)'],[-1,2 3],opt="lr")
xset("line style",2);plot2d(t,cos(t),style=5);
xset("line style",4);plot2d(t,sin(t),style=3);
legends(["sin(t)";"cos(t)"],[[5;2],[3;4]], with_box=%f, opt="?")

See Also

plot2d , xstring , xtitle ,


legend_properties

Scilab Data type
Last update : 09/12/2005

legend_properties - description of the Legend entity properties. Warning: This object will be rebuild in the next version.

Description

The Legend entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for legends drawn below plot2dx graphs. For each line plotted, the legend shows a sample of the line type, marker symbol, and color.

parent: This property contains the handle of the parent. The parent of the legend entity should be of the type "Compound" . This Compound entity contains also the remainder of the graph's entities.
children: This property contains a vector with the children of the handle. However, legend handles currently do not have any children .
line_mode: This field contains the default line_mode property value for the segs. Its value should be "on" (line drawn) or "off" (no line drawn).
mark_mode: This field contains the default mark_mode property value for the polyline. Its value should be "on" (marks drawn) or "off" (no marks drawn).
mark_foreground: This field contains the mark_foreground property value which is the marks' edge color. Its value should be a color index (relative to the current color_map).
mark_background: This field contains the mark_background property value which is the marks' face color. Its value should be a color index (relative to the current color_map).
foreground: This field contains the color index used to draw legend. Its value should be a color index (relative to the current colormap).
visible: This field contains the visible property value for the entity . It should be "on" or "off" . If "on" the legend is drawn , If "off" the legend is not displayed on the screen.
text: This field is the character string vector which contains the legend.
font_size: The font_size property is used to select the type of size of the text. Its value should be an integer in between 0 and 5 which stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt.
font_style: Seven differents fonts are available : "Courrier", "Symbol", "Times", "Times Italic", "Times Bold", "User defined". The font_style property is an index in [0 6] which is associated to the previous font names.

Examples

set("figure_style","new") //create a figure
// x initialisation
x=[0:0.1:2*%pi]';
plot2d(x,[sin(x) sin(2*x) sin(3*x)],..
  [1,2,3],leg="L1@L2@L3")
a=get("current_axes");
l=a.children.children(1)
l.text="sin(x)@sin(2*x)@sin(3*x)";
l.visible="off"; // invisible
l.font_size = 2;
l.font_style = 5;
l.visible='on';

See Also

plot2d , graphics_entities ,

Author

Djalel ABDEMOUCHE


legend

Scilab Function
Last update : 10/10/2005

legend - draw graph legend

Calling Sequence

hl=legend([h,] string1,string2, ... [,pos] [,boxed])
hl=legend([h,] strings [,pos] [,boxed])

Parameters

  • h : graphic handle on an Axes entity or vector of handles on polyline entities. The default value is the handle on current_axes .
  • string1,string2, ... : character strings stringsi is the legend of the ith curve
  • strings : n vector of strings, strings(i) is the legend of the ith curve
  • pos : (optionnal) specify where to draw the legend; this parameter may be a integer flag (or equivalently a string flag) or a vector [x,y] which gives the coordinates of the upper left corner of the legend box. In the first case the possible values are:
    • 1 the legend are drawn in the upper right-hand corner (default).
    • 2 the legend are drawn in the upper left-hand corner.
    • 3 the legend are drawn in the lower left-hand corner.
    • 4 the legend are drawn in the lower right-hand corner.
    • 5 interactive placement with the mouse .
  • boxed : a boolean (default value %t) which sets ot not the drawing of the box.
  • hl : a handle, points to the Compound containing all the legend .

Description

Puts a legend on the current plot using the specified strings as labels. legend prepends labels by a recall of the corresponding line or patch. The recall is type ans properties are recover from the given handles:

when called without handle argument (or with a handle on a axes entity) the function looks first build the vectors of handle on polylines entities which are the children of the given axes.

In the interactive placement (opt=5) move the legend box with the mouse and press the left button to release it.

This function allows more flexible placement of the legend than the leg plot2d argument.

Examples

set figure_style new
t=0:0.1:2*%pi;
a=gca();a.data_bounds=[t(1) -1.8;t($) 1.8];

plot2d(t,[cos(t'),cos(2*t'),cos(3*t')],[-1,2 3]);
e=gce();
e.children(1).thickness=3;
e.children(2).line_style=4;

hl=legend(['cos(t)';'cos(2*t)';'cos(3*t)'],a=1);

See Also

plot2d , xstring , polyline_properties ,


loadplots

Scilab Function
Last update : 25/01/2006

loadplots - loads and formats saved old style plots

Calling Sequence

rec=loadplots(fil)

Parameters

  • fil : character string giving the path of the binary file containing the save of a graphic (old style)
  • rec : A data structure (see Description below)

Description

Given a file generated by xsave of by the save menu in graphic window this function returns a data structure containing the context and plot definition.

rec is a typed list with type "SPLOT" . Each of its 2:$ fields contains a graphic instruction definition and its parameters. rec(i)(1) gives the fields names of the i th graphic instruction

txt=string(rec) generates the Scilab instructions which reproduce the plot. To make the necessary functions known, load the loadplots function first. This can be done with the instruction

loadplots;

Warning: The loadplots function is currently available with the graphic files saved under the old graphic mode.

Examples

set old_style on // switch to old graphic mode
driver('Rec');xbasc();plot2d([0 1.5 4]) //make a plot
xsave(TMPDIR+'/foo.scg') //save it in a binary file

rec=loadplots(TMPDIR+'/foo.scg'); //get the associated data structure
//here rec($) is the data structure associated with the plot2d instruction
rec($).x //the x vector
rec($).y //the y vector

string(rec) //the scilab instructions producing the same plot

mputl(string(rec),TMPDIR+'/foo.sce') //creates a script file
xbasc();exec(TMPDIR+'/foo.sce',-1) //execute it to re-create the plot

xbasc();
set old_style off  // switch nack to new graphic mode

See Also

xsave , xload ,


locate

Scilab Function
Last update : 16/06/2004

locate - sélection avec la souris d'un ensemble de points

Calling Sequence

x=locate([n,flag])

Parameters

  • x : matrice de taille (2,n1). n1=n si le paramètre n est donné.
  • n,flag : entiers.

Description

locate est utilisée pour récupérer les coordonnées d'un ou plusieurs points sélectionnés avec la souris dans une fenêtre graphique. Les coordonnées sont données dans l'échelle graphique courante.

Si n>0, n points sont sélectionnés et leurs coordonnées sont renvoyées dans la matrice x .

Si n<=0, les points sont sélectionnés jusqu'à ce que l'on presse le bouton de gauche de la souris. Le dernier point sélectionné (avec le bouton de gauche) n'est dans ce cas pas renvoyé. x=locate() est identique à x=locate(-1) .

Si flag=1 une croix est dessinée aux points sélectionnés.

See Also

xclick , xgetmouse ,

Author

S.S. & J.Ph.C


mesh

Scilab Function
Last update : 09/12/2005

mesh - 3D mesh plot

Calling Sequence

mesh(Z)
mesh(X,Y,Z)
mesh(...,<GlobalProperty>)
mesh(...,<color>,<GlobalProperty>)
mesh(<axes_handle>,...)

Parameters

  • Z : a real matrix defining the surface height. It can not be omitted. The Z data is a m x n matrix.
  • X,Y : two real matrices : always set together, these data defines a new standard grid. This new X and Y components of the grid must match Z dimensions (see description below).
  • color : an optional real matrix defining a color value for each (X(j),Y(i)) point of the grid (see description below).
  • <GlobalProperty> : This optional argument represents a sequence of couple statements {PropertyName,PropertyValue} that defines global objects' properties applied to all the curves created by this plot. For a complete view of the available properties (see GlobalProperty ).
  • <axes_handle> : This optional argument forces the plot to appear inside the selected axes given by axes_handle rather than the current axes (see gca ).

Description

mesh draws a parametric surface using a rectangular grid defined by X and Y coordinates (if {X,Y} are not specified, this grid is determined using the dimensions of the Z matrix) ; at each point of this grid, a Z coordinate is given using the Z matrix. mesh is based on the surf command with default option color_mode = white index (inside the current colormap) and color_flag = 0.

Data entry specification :

In this paragraph and to be more clear, we won't mention GlobalProperty optional arguments as they do not interfer with entry data (except for "Xdata" , "Ydata" and "Zdata" property, see GlobalProperty ). It is assumed that all those optional arguments could be present too.

If Z is the only matrix specified, (Z) plots the matrix Z versus the grid defined by 1:size(Z,2) along the x axis and 1:size(Z,1) along the y axis.

Remarks

To enable the tranparency mode you should set the color_mode option to 0.

Examples

[X,Y]=meshgrid(-1:.1:1,-1:.1:1);
Z=X.^2-Y.^2;
xtitle('z=x2-y ^2');
mesh(X,Y,Z);

See Also

surf , meshgrid , plot2d , LineSpec , GlobalProperty ,

Author

F.Belahcene


milk_drop

Scilab Function
Last update : 16/06/2004

milk_drop - représentation d'une goutte de lait

Calling Sequence

z=milk_drop(x,y)

Parameters

  • x,y : deux vecteurs lignes de taille n1 et n2.
  • z : matrice de taille (n1,n2).

Description

milk_drop est une fonction représentant la surface d'une goutte de lait tombant dans du lait. Elle peut être utilisée pour tester les fonctions eval3d et plot3d .

Examples

x=-2:0.1:2; y=x;
z=eval3d(milk_drop,x,y);
plot3d(x,y,z)

See Also

eval3d , plot3d ,

Author

Steer S.


move

Scilab Function
Last update : 12/01/2004

move - move, translate, a graphic entity and its children.

Calling Sequence

move(h,xy)
move(h,xy,"alone")

Parameters

  • h : a handle, the handle of the entity to move.
  • xy : an array [dx,dy] which gives the translation vector to apply.
  • "alone" : string keyword (optional).

Description

This routine can be used to apply a translation to a graphics entity. If the entity has children, they will be also translated.

Given the keyword "alone" , only the specified entity needs to be redraw. It must specially be used with the pixel_drawing_mode property of the figure entity (see draw objects under "xor" drawing mode).

Examples

See Also

get , set , draw , figure_properties , graphics_entities ,

Author

Djalel ABDEMOUCHE


m_circle

Scilab Function
Last update : 12/01/2004

m_circle - M-circle plot

Calling Sequence

m_circle()
m_circle(gain)

Parameters

  • gain : vector of gains (in DB). The default value is
    • gain =[-12 -8 -6 -5 -4 -3 -2 -1.4 -1 -.5 0.25 0.5 0.7 1 1.4 2 2.3 3 4 5 6 8 12]

Description

m_circle is used with nyquist .

Examples

//Example 1 :
  s=poly(0,'s')
  h=syslin('c',(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01))
  nyquist(h,0.01,100,'(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01)')
  m_circle();
//Example 2:
  xbasc();
  h1=h*syslin('c',(s^2+2*0.1*15.1*s+228.01)/(s^2+2*0.9*15*s+225))
  nyquist([h1;h],0.01,100,['h1';'h'])
  m_circle([-8 -6 -4]);

See Also

nyquist , chart , black ,

Author

S.Steer.;


name2rgb

Scilab Function
Last update : 07/07/2004

name2rgb - returns the RGB values of a named color

Calling Sequence

rgb=name2rgb(name)

Parameters

  • name : name of the color.
  • rgb : vector of RGB integer values of a color.

Description

name2rgb returns the RGB values of a color given by its name. The result is a vector [r,g,b] where r , g and b are integers between 0 and 255 corresponding to colors components red, green and blue. As usual 0 means no intensity and 255 means all the intensity of the color.

If no color is found [] is returned.

The list of all known colors is given by color_list .

Examples

rgb=name2rgb("gold")
rgb2name(rgb)

See Also

color , color_list , rgb2name ,


newaxes

Scilab Function
Last update : 06/12/2005

newaxes - Creates a new Axes entity

Calling Sequence

a=newaxes()

Parameters

  • a : a handle, the handle on the newly created Axes entity

Description

newaxes() is used to create a new Axes entity (see graphics_entities ) in the current figure. The properties of this entity are inherited from the default_axes entity (see gda )

Examples

clf()
a1=newaxes();
a1.axes_bounds=[0,0,1.0,0.5];
t=0:0.1:20;
plot(t,acosh(t),'r')
a2=newaxes();
a2.axes_bounds=[0,0.5,1.0,0.5];
x=0:0.1:4;
plot(x,sinh(x))
legend('sinh')

sca(a1); //make first axes current
plot(t,asinh(t),'g')
legend(['acosh','asinh'])

See Also

subplot , gda , sca ,

Author

S. Steer, INRIA


nf3d

Scilab Function
Last update : 16/06/2004

nf3d - conversion de facettes pour plot3d

Calling Sequence

[xx,yy,zz]=nf3d(x,y,z)

Parameters

  • x,y,x,xx,yy,zz : 6 matrices réelles

Description

Fonction utilitaire utilisée pour convertir des facettes codées dans trois matrices x,y,z (format plot3d2) dans un format accepté par plot3d.

Examples

// une sphère...
u = linspace(-%pi/2,%pi/2,40);
v = linspace(0,2*%pi,20);
x= cos(u)'*cos(v);
y= cos(u)'*sin(v);
z= sin(u)'*ones(v);
// plot3d2(x,y,z) est équivalent à ...
[xx,yy,zz]=nf3d(x,y,z); plot3d(xx,yy,zz)

See Also

plot3d , plot3d2 ,


nyquist

Scilab Function
Last update : 08/06/2005

nyquist - nyquist plot

Calling Sequence

nyquist( sl,[fmin,fmax] [,step] [,comments] )
nyquist( sl, frq [,comments] )
nyquist(frq,db,phi [,comments])
nyquist(frq, repf [,comments])

Parameters

  • sl : syslin list (SIMO linear system in continuous or discrete time )
  • fmin,fmax : real scalars (frequency bounds (in Hz))
  • step : real (logarithmic discretization step)
  • comments : string vector (captions).
  • frq : vector or matrix of frequencies (in Hz) (one row for each output of sl ).
  • db,phi : real matrices of modulus (in Db) and phases (in degree) (one row for each output of sl ).
  • repf : matrix of complex numbers. Frequency response (one row for aech output of sl )

Description

Nyquist plot i.e Imaginary part versus Real part of the frequency response of sl .

For continous time systems sl(2*%i*%pi*w) is plotted. For discrete time system or discretized systems sl(exp(2*%i*%pi*w*fd) is used ( fd=1 for discrete time systems and fd=sl('dt') for discretized systems )

sl can be a continuous-time or discrete-time SIMO system (see syslin ). In case of multi-output the outputs are plotted with different symbols.

The frequencies are given by the bounds fmin,fmax (in Hz) or by a row-vector (or a matrix for multi-output) frq .

step is the ( logarithmic ) discretization step. (see calfrq for the choice of default value).

comments is a vector of character strings (captions).

db,phi are the matrices of modulus (in Db) and phases (in degrees). (One row for each response).

repf is a matrix of complex numbers. One row for each response.

Default values for fmin and fmax are 1.d-3 , 1.d+3 if sl is continuous-time or 1.d-3 , 0.5 if sl is discrete-time.

Automatic discretization of frequencies is made by calfrq .

Examples

clf();
s=poly(0,'s');
h=syslin('c',(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01));
comm='(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01)';
nyquist(h,0.01,100,comm);
h1=h*syslin('c',(s^2+2*0.1*15.1*s+228.01)/(s^2+2*0.9*15*s+225))
clf();
nyquist([h1;h],0.01,100,['h1';'h'])
clf();nyquist([h1;h])

See Also

bode , black , calfrq , freq , repfreq , phasemag ,


object_editor graphic graphique menus

Scilab Data type
Last update : 06/01/2006

object_editor - description des capacités de l'éditeur graphique

graphic - description des capacités de l'éditeur graphique

graphique - description des capacités de l'éditeur graphique

menus - description des capacités de l'éditeur graphique

Description

Comme explicité dans le fichier d'aide graphics_entities , le graphique Scilab possède désormais un nouveau mode. Ce mode facilite les intéractions entre l'utilisateur et le graphique aussi bien avant qu'après sa création. Dans ce "nouveau ", chaque fenêtre graphique et les dessins qu'elle contient sont représentés sous forme d'entités hiérarchiques. Le plus haut niveaui de la hiérarchie est toujours l'entité Figure. Chaque Figure définit au moins un enfant de type Axes. Chaque entité Axes contient un ensemble d'entités feuilles (entités terminales de la hiérarchie - elles n'ont pas de fils) qui sont les objets de type Polylines, Rectangles, Arcs, Segs,... L'entités Axes peut également contenir une entité intermédiaire nommé Compound qui regroupe un ensemble d'entités filles.

Le principal intérêt du nouveau mode graphique réside dans sa capacité à changer à volonté les propriétés des objets graphiques a priori et surtout a posteriori. Ce nouveua mode graphique est fourni avec une suite de commandes graphiques de haut niveau (voir set , get ) utliisées pour positionner les proriéts des objets telles que les données, les coordonnées, échelles, couleur etc... sans avoir à rejouer les commandes initiales (comportement de l'ancien mode graphique).

Les entités graphiques ont un type handle dans Scilab.Un handle est un identificateur unique qui est associé chaque instance d'un objet graphique créé. En utilisant ce handle, il sera possible d'atteindre les propriétés de l'entité considérée à travers l'utilisation des commandes "set" et "get". Les handles sont aussi utiles pour manipuler des objets graphiques, les bouger, les copier ou encore les supprimer.

Pour compléter ce nouveau mode, un éditeur graphique a été développé pour ces objets. Il s'agit d'un ensemble d'interfaces en Tcl/Tk disponibles pour chaque objet graphique (voir graphics_entities pour plus de détail). Pour lancer l'interface, il faut sélectionner le menu Edit dans la fenêtre graphique. On a alors sept opérations d'édition disponibles:

Select figure as current: Positionne la figure comme étant la nouvelle figure courante.

Redraw figure: Redessinne le contenu de la figure (seulement utile en ancien mode (old_style mode on)).

Erase figure: Efface le contenu de la figure. Son action correspond à un appel à xbasc (ancienne syntaxe) ou clf (nouveau mode graphique).

Les 8 derniers items sont dédiés exclusivement au nouveau mode graphique :

Copy object/Copier: En utilisant la souris, cela permet de sélectionner un objet graphique 2D (comme une courbe, un rectangle...) et de le glisser dans le presse-papier. Ainsi, par un prochain appel à Paste object , l'objet est recopié dans les axe courant.

Paste object/Coller: Permet à l'utilisateur de coller un objet précédemment placé dans le presse-papier sur l'axe courant.

Move object/Déplacer: En utilisant la souris, cette fonction permet de bouger un objet 2D (comme une courbe, un rectangle...) à l'intérieur d'un axe courant.

Delete object/Détruire: En utilisant la souris, cette fonction permet de détruire un objet 2D (like a curve, a rectangle...) que l'on sélectionne a posteriori.

Figure Properties: Lance l'interface Tcl/Tk pour l'objet Figure, handle de la figure de la fenêtre courante.

Current Axes Properties: Lance l'interface Tcl/Tk pour l'objet Axes courant, handle de l'axe courant de la fenêtre courante.

Start Entity Picker/Démarrer le sélecteur d'entités: Démarre un sélecteur d'entité pour pointer des objets 2D à la souris et ainsi ouvrir leur interface Tcl/Tk pour pouvoir modifier leurs propriétés. Le clic souris gauche permet d'éditer l'objet cliqué; le clic droit réalise un déplacement de l'objet sélectionné. Remarque: pour l'instant, cette option fonctionne uniquement avec des objets 2D.

Stop Entity Picker/Arrêter le sélecteur d'entités: Arrête l'action du sélecteur d'entité.

Une fois l'interface graphique (fenêtre Tcl/Tk) activée en utilisant les commandes Figure Properties ou Current Axes Properties , on distingue 2 zones pricnipales sur ces interfaces :

Un arbre sélecteur: placé sur la gauche de la fenêtre de l'éditeur graphique, l'arbre sélecteur permet de parcourir la hiérarchie des objets présents au sein de la figure. On peut passer d'un objet à l'autre en déroulant la hiérarchie.

Des onglets: La seconde zone d'intérêt est à droite: les propriétés de l'objet sélectionné dans l'arbre sont disposées dans une structure multi-onglets. On y trouve différents types de propriétés telles le Style , Data , Clipping ... Elles dépendent du type d'objet considéré. A travers cet éditeur, on peut voir et changer les propriétés de ces objets de façon graphique comme on le ferait à travers l'emploi des fonctions "set" et "get" dans la console. Voici un exemple d'onglets affichant les propriétés d'un objet de type Axes:

See Also

graphics_entities , set , get , clf , plot ,

Author

F.Leray INRIA


oldplot

Scilab Function
Last update : 08/06/2005

oldplot - simple plot (old version)

Calling Sequence

oldplot(x,y,[xcap,ycap,caption])
oldplot(y)

Parameters

  • x,y : two vectors with same sizes
  • xcap,ycap,caption : character strings or string matrices

Description

Plot y as function of x . xcap and ycap are captions for x-axis and y-axis respectively and caption is the caption of the plot.

Invoked with only one argument, oldplot(y) plots the y vector or, if y is a matrix, it plots all its row vectors on the same plot. This plot is done with respect to the vector 1:<number of columns of y >.

oldplot is obsolete. Use plot2d or plot instead.

Examples

x=0:0.1:2*%pi;
// simple plot
oldplot(sin(x))
// using captions
xbasc()
oldplot(x,sin(x),"sin","time","plot of sinus")
// plot 2 functions
xbasc()
oldplot([sin(x);cos(x)])

See Also

plot2d , plot ,

Author

J.Ph.C.


param3d1

Scilab Functio
Last update : 10/10/2005

param3d1 - 3D plot of parametric curves

Calling Sequence

param3d1(x,y,z,[theta,alpha,leg,flag,ebox])
param3d1(x,y,list(z,colors),[theta,alpha,leg,flag,ebox])

Parameters

  • x,y,z

    : matrices of the same size (nl,nc).

    Each column i of the matrices corresponds to the coordinates of the ith curve. You can give a specific color for each curve by using list(z,colors) instead of z , where colors is a vector of size nc . If color(i) is negative the curve is plotted using the mark with id abs(style(i)) ; if style(i) is strictly positive, a plain line with color id style(i) or a dashed line with dash id style(i) is used.

  • theta,alpha : real values giving in degree the spherical coordinates of the observation point.
  • leg : string defining the captions for each axis with @ as a field separator, for example "X@Y@Z".
  • flag=[type,box] : type and box have the same meaning as in plot3d :
    • type : an integer (scaling).
      • type=0 the plot is made using the current 3D scaling (set by a previous call to param3d , plot3d , contour or plot3d1 ).
      • type=1 rescales automatically 3d boxes with extreme aspect ratios, the boundaries are specified by the value of the optional argument ebox .
      • type=2 rescales automatically 3d boxes with extreme aspect ratios, the boundaries are computed using the given data.
      • type=3 3d isometric with box bounds given by optional ebox , similarily to type=1 .
      • type=4 3d isometric bounds derived from the data, to similarily type=2 .
      • type=5 3d expanded isometric bounds with box bounds given by optional ebox , similarily to type=1 .
      • type=6 3d expanded isometric bounds derived from the data, similarily to type=2 .Note that axes boundaries can be customized through the axes entity properties (see axes_properties ).
    • box : an integer (frame around the plot).
      • box=0 nothing is drawn around the plot.
      • box=1 unimplemented (like box=0).
      • box=2 only the axes behind the surface are drawn.
      • box=3 a box surrounding the surface is drawn and captions are added.
      • box=4 a box surrounding the surface is drawn, captions and axes are added.Note that axes aspect can also be customized through the axes entity properties (see axes_properties ).
  • ebox : It specifies the boundaries of the plot as the vector [xmin,xmax,ymin,ymax,zmin,zmax] . This argument is used together with type in flag : if it is set to 1 , 3 or 5 (see above to see the corresponding behaviour). If flag is missing, ebox is not taken into acoount. Note that, when specified, the ebox argument acts on the data_bounds field that can also be reset through the axes entity properties (see axes_properties ).

Description

param3d1 is used to plot 3D curves defined by their coordinates x , y and z . Note that data can also be set or get through the surface entity properties (see surface_properties ).

Note that properties like rotation angles , colors and thickness of the plotted curves can also be set through the param3d entity properties (see param3d_properties ).

Enter the command param3d1() to see a demo.

Examples

xset('window',20) // create a window number 20
t=[0:0.1:5*%pi]';
param3d1([sin(t),sin(2*t)],[cos(t),cos(2*t)],..
  list([t/10,sin(t)],[3,2]),35,45,"X@Y@Z",[2,3])

xdel(20);
 set("figure_style","new") //create a figure
 a=get("current_axes");//get the handle of the newly created axes
 t=[0:0.1:5*%pi]';
 param3d1([sin(t),sin(2*t)],[cos(t),cos(2*t)],[t/10,sin(t)])
 a.rotation_angles=[65,75];
 a.data_bounds=[-1,-1,-1;1,1,2]; //boundaries given by data_bounds
 a.thickness = 2;
 h=a.children //get the handle of the param3d entity: an Compound composed of 2 curves
 h.children(1).foreground = 3 // first curve
 curve2 = h.children(2);
 curve2.foreground = 6;
 curve2.mark_style = 2;

See Also

param3d , plot3d , plot2d , gca , xdel , delete ,

Author

J.Ph.C.


param3d_properties

Scilab Data type
Last update : 10/10/2005

param3d_properties - description of the 3D curves entities properties

Description

The Param3d entity is a leaf of the graphics entities hierarchy.

visible: This field contains the visible property value for the entity . It should be "on" or "off" . By default, the curves are visibles, the value's property is "on" . If "off" the curves are not drawn on the screen.
data: This field contains the coordinates of the 3d curves. it is the matrix [X,Y,Z] such as X(:,i) , Y(:,i) , Z(:,i) contain the 3D coordinates of the i 'th curve. This field contains the default line_style property value for Segs, Arcs, Rectangle and Polyline objects.
line_mode: This field contains the default line_mode property value for the polyline. Its value should be "on" (line drawn) or "off" (no line drawn).
line_style: This field selects the type of line to be used to draw lines . Its value should be an integer in [0 6]. 0 stands for solid, the other values stand for a selection of dashes (see getlinestyle ).
polyline_style: This field selects the way curve are drawn: interpolated (default), staircase, barplot, arrowed and filled modes are available through integer index [1:5].
mark_mode: This field contains the default mark_mode property value. Its value should be "on" or "off" (default value).
mark_style: This field contains the default mark_style property value. The mark_style selects the type of mark to be displayed. Its value should be an integer in [0 9] which stands for: dot, plus, cross, star, filled diamond, diamond, triangle up, triangle down, trefle and circle.
mark_size_unit: This field contains the default mark_size_unit property value. If mark_size_unit is set to "point" , then the mark_size value is directly given in points. When mark_size_unit is set to "tabulated" , mark_size is computed relative to the font size array: therefore, its value should be an integer in [0 5] whith stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt. Note that param3d and pure scilab functions use tabulated mode as default ; when using plot function, the point mode is automatically enabled.
mark_size: This field contains the default mark_size property value. The mark_size selects the font size of the mark to be displayed. Its value should be an integer in [0 5] whith stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt (see getmark ).
mark_foreground: This field contains the mark_foreground property value which is the marks' edge color. Its value should be a color index (relative to the current color_map).
mark_background: This field contains the mark_background property value which is the marks' face color. Its value should be a color index (relative to the current color_map).
thickness: This field contains the default thickness value of the lines used to draw the axes and the curves. It should be a positive integer.
foreground: This field contains the color index used to draw the curves. Its value should be a color index (relative to the current colormap).
clip_state: This field contains the default clip_state property value. Its value should be :
"off" this means that all curves created after that are not clipped (default value).
"clipgrf" this means that all curves created after that are clipped outside the Axes boundaries.
"on" this means that all curves created after that are clipped outside the rectangle given by property clip_box.
clip_box: This field contains the default clip_box property value. Its value should be an empty matrix if clip_state is "off" . Other case the clipping is given by the vector [x,y,w,h] (upper-left point width height).
user_data: This field can be use to store any scilab variable in the param3d data structure, and to retreive it.
parent: This property contains the handle of the parent. The parent of the 3D curves entity should be of type "Axes" or "Compound" .

Examples

   set("figure_style","new") //create a figure
   a=get("current_axes");//get the handle of the newly created axes
   t=[0:0.1:5*%pi]';
   param3d1([sin(t),sin(2*t)],[cos(t),cos(2*t)],[t/10,sin(t)])

   a.rotation_angles=[65,75];
   a.data_bounds=[-1,-1,-1;1,1,2]; //boundaries given by data_bounds
   a.thickness = 2;
   h=a.children //get the handle of the param3d entity: an Compound composed of 2 curves
   h.children(1).foreground = 3 // first curve
   curve2 = h.children(2);
   curve2.foreground = 6;
   curve2.mark_style = 2;

See Also

set , get , delete , param3d , param3d1 , graphics_entities ,

Author

Djalel ABDEMOUCHE


param3d

Scilab Function
Last update : 08/06/2005

param3d - 3D plot of a parametric curve

Calling Sequence

param3d(x,y,z,[theta,alpha,leg,flag,ebox])

Parameters

  • x,y,z : three vectors of the same size (points of the parametric curve).
  • theta, alpha : real values giving in degree the spherical coordinates of the observation point.
  • leg : string defining the labels for each axis with @ as a field separator, for example "X@Y@Z".
  • flag=[type,box] : type and box have the same meaning as in plot3d :
    • type : an integer (scaling).
      • type=0 the plot is made using the current 3D scaling (set by a previous call to param3d , plot3d , contour or plot3d1 ).
      • type=1 rescales automatically 3d boxes with extreme aspect ratios, the boundaries are specified by the value of the optional argument ebox .
      • type=2 rescales automatically 3d boxes with extreme aspect ratios, the boundaries are computed using the given data.
      • type=3 3d isometric with box bounds given by optional ebox , similarily to type=1 .
      • type=4 3d isometric bounds derived from the data, to similarily type=2 .
      • type=5 3d expanded isometric bounds with box bounds given by optional ebox , similarily to type=1 .
      • type=6 3d expanded isometric bounds derived from the data, similarily to type=2 .Note that axes boundaries can be customized through the axes entity properties (see axes_properties ).
    • box : an integer (frame around the plot).
      • box=0 nothing is drawn around the plot.
      • box=1 unimplemented (like box=0).
      • box=2 only the axes behind the surface are drawn.
      • box=3 a box surrounding the surface is drawn and captions are added.
      • box=4 a box surrounding the surface is drawn, captions and axes are added.Note that axes aspect can also be customized through the axes entity properties (see axes_properties ).
  • ebox : It specifies the boundaries of the plot as the vector [xmin,xmax,ymin,ymax,zmin,zmax] . This argument is used together with type in flag : if it is set to 1 , 3 or 5 (see above to see the corresponding behaviour). If flag is missing, ebox is not taken into acoount. Note that, when specified, the ebox argument acts on the data_bounds field that can also be reset through the axes entity properties (see axes_properties ).

Description

param3d is used to plot a 3D curve defined by its coordinates x , y and z . Note that data can also be set or get through the surface entity properties (see surface_properties ).

Note that properties like rotation angles , colors and thickness of the plotted curves can also be set through the param3d entity properties (see param3d_properties ).

Use param3d1 to do multiple plots.

Enter the command param3d() to see a demo.

Examples

t=0:0.1:5*%pi;
param3d(sin(t),cos(t),t/10,35,45,"X@Y@Z",[2,3])

See Also

param3d1 , plot3d ,

Author

J.Ph.C.


paramfplot2d

Scilab Function
Last update : 16/06/2004

paramfplot2d - animation dans le plan d'une courbe définie par une fonction

Calling Sequence

paramfplot2d(f,x,theta)
paramfplot2d(f,x,theta,flag)
paramfplot2d(f,x,theta,flagrect)

Parameters

  • x : valeurs réelles.
  • f : fonction y=f(x,t) . f est une fonction Scilab ou une routine externe liée dynamiquement (sous forme d'une chaîne de caractères).
  • theta : valeurs réelles (ensemble des paramètres).
  • flag : chaîne de caractères 'no' ou 'yes' : si "yes" l'écran est effacé entre deux dessins consécutifs.
  • rect : "rectangle" [xmin, xmax, ymin, ymax] (vecteur 1 x 4 de valeurs réelles),

Description

Dessin animé de la fonction x-->f(x,t) pour t=theta(1),theta(2), etc. f peut être une fonction Scilab ou une routine externe liée dynamiquement puisque y=f(x,t) est évaluée comme y=feval(x(:),t,f) (voir feval).

f: fonction x,t -> f(x,t) = à valeur dans R^N pour x = vecteur de R^N et t = nombre réel. x est un N-vecteur de valeurs de x et pour chaque t dans theta, f(x,t) = N-vecteur de valeurs de y.

Examples

deff('y=f(x,t)','y=t*sin(x)')
x=linspace(0,2*%pi,50);theta=0:0.05:1;
paramfplot2d(f,x,theta);

See Also

plot2d , feval , fplot2d ,


pie

Scilab Function
Last update : 30/11/2005

pie - cercle graphique

Calling Sequence

pie(x)
pie(x[,sp[,txt]])

Parameters

  • x : un scalaire ou un vecteur de réels positifs.
  • sp : un scalaire ou un vecteur de réels.
  • txt : une cell ou un vecteur de strings.

Description

x, sp et style doivent etre de meme longueur.

pie(x) : si la longueur du vecteur x est N alors la fonction pie dessine un cercle graphique constitué de N part. La surface de la ième part est egale à : (x(i)/sum(x))*(aire du cercle unité). c'est la division de la valeur de la ième composante de x divisée par la somme des composantes de x

pie(x,sp) : le vecteur sp permet de couper une ou plusieurs parts du cercle, (la longueur de sp doit etre egale a la longueur de x). Si la valeur de la ième composante de sp est different de 0 alors la ième part est séparée des autres part(donc du cercle) par un espace, Si la valeur de la ième composante de sp est egale à 0 alors elle est attachée aux autres.

pie(x,txt) : le vecteur txt permet d'ecrire un texte à coté de chacune des part du cercle, la ième composante de txt correspond au texte de la ième part (par défaut : on ecrit à coté de chaque part le pourcentage de l'aire d'une part par rappport à la surface totale du cercle. La longueur du vecteur txt doit etre égale à la longueur.

Examples

// Premier exemple : un argument d'entrée  x=[1 2 5]
scf(0);
pie([1 2 5]);

// Deuxième example : deux arguments d'entrées x=[5 9  4 6 3], sp=[0 1 0 1 0], la 2ème et 4ème parts du cercle sont séparées des autres
scf(1);
pie([5 9 4 6 3],[0 1 0 1 0]);

// Troisième exemple : trois arguments d'entrées, x=[3 4 6 2], sp=[0 1 0 0], txt=["part1","part2","part3","part4"]
scf(2);
pie([3 4 6 2],[0 1 0 0],["part1","part2","part3","part4"]);

See Also

xfpolys ,

Author

Farid Belahcene


plot2d1

Scilab Function
Last update : 08/06/2005

plot2d1 - 2D plot (logarithmic axes) (obsolete)

Calling Sequence

plot2d1(str,x,y,[style,strf,leg,rect,nax])

Parameters

  • str : is a string of length three "abc" .
    • a : can have the following values: e , o or g .
      • e : means "empty". Itspecifies the fact that the value of x is not used (the x values are supposed to be regularly spaced, ie 1:<number of rows of y >). The user must anyway give a value for x , 1 for instance: plot2d1("enn",1,y) .
      • o : means "one". If there are many curves, they all have the same x-values: x is a column vector of size nl and y is a matrix of size (nl,nc). For example : x=[0:0.1:2*%pi]'; plot2d1("onn",x,[sin(x) cos(x)]) .
      • g : means "general". x and y must have the same size (nl,nc). Each column of y is plotted with respect to the corresponding column of x . nc curves are plotted using nl points.
    • b, c : can have the values n (normal) or l (logarithmic).
      • b=l : a logarithmic axis is used on the x-axis
      • c=l : a logarithmic axis is used on the y-axis
  • x,y,[style,strf,leg,rect,nax] : these arguments have the same meaning as in the plot2d function.
  • opt_args : these arguments have the same meaning as in the plot2d function.

Description

This function is obsolete. USE plot2d INSTEAD !!

plot2d1 plots a set of 2D curves. It is the same as plot2d but with one more argument str which enables logarithmic axis. Moreover, it allows to specify only one column vector for x when it is the same for all the curves.

By default, successive plots are superposed. To clear the previous plot, use clf .

Enter the command plot2d1() to see a demo.

Examples

// multiple plot without giving x
x=[0:0.1:2*%pi]';
plot2d1("enn",1,[sin(x) sin(2*x) sin(3*x)])
// multiple plot using only one x
clf()
plot2d1("onn",x,[sin(x) sin(2*x) sin(3*x)])
// logarithmic plot
x=[0.1:0.1:3]'; clf()
plot2d1("oll",x,[exp(x) exp(x^2) exp(x^3)])

See Also

plot2d , plot2d2 , plot2d3 , plot2d4 , clf ,

Author

J.Ph.C.


plot2d2

Scilab Function
Last update : 08/06/2005

plot2d2 - 2D plot (step function)

Calling Sequence

plot2d2([x],y)
plot2d2([x],y,<opt_args>)
plot2d2([logflag],x,y,[style,strf,leg,rect,nax])

Parameters

  • args : see plot2d for a description of parameters.

Description

plot2d2 is the same as plot2d but the functions given by (x,y) are supposed to be piecewise constant.

By default, successive plots are superposed. To clear the previous plot, use clf() .

Enter the command plot2d2() to see a demo. Note that all the modes proposed by plot2dxx (xx = 1 to 4) can be enabled using plot2d and setting the polyline_style option to the corresponding number.

Examples

// plots a step function of value i on the segment [i,i+1]
// the last segment is not drawn
plot2d2([1:4],[1:4],1,"111","step function",[0,0,5,5])
// compare the following with plot2d
x=[0:0.1:2*%pi]';
clf()
plot2d2(x,[sin(x) sin(2*x) sin(3*x)])
  // In New graphics only
clf()
set("figure_style","new")
plot2d(x,[sin(x) sin(2*x) sin(3*x)])
e=gce();
e.children(1).polyline_style=2;
e.children(2).polyline_style=2;
e.children(3).polyline_style=2;

See Also

plot2d , plot2d3 , plot2d4 , subplot , clf , polyline_properties ,

Author

J.Ph.C.


plot2d3

Scilab Function
Last update : 08/06/2005

plot2d3 - 2D plot (vertical bars)

Calling Sequence

plot2d3([logflags,] x,y,[style,strf,leg,rect,nax])
plot232(y)
plot2d3(x,y <,opt_args>)

Parameters

  • args : see plot2d for a description of parameters.

Description

plot2d3 is the same as plot2d but curves are plotted using vertical bars.

By default, successive plots are superposed. To clear the previous plot, use clf() .

Enter the command plot2d3() to see a demo. Note that all the modes proposed by plot2dxx (xx = 1 to 4) can be enabled using plot2d and setting the polyline_style option to the corresponding number.

Examples

// compare the following with plot2d1
x=[0:0.1:2*%pi]';
plot2d3(x,[sin(x) sin(2*x) sin(3*x)])
// In New graphics only
clf()
set("figure_style","new")
plot2d(x,[sin(x) sin(2*x) sin(3*x)])
e=gce();
e.children(1).polyline_style=3;
e.children(2).polyline_style=3;
e.children(3).polyline_style=3;

See Also

plot2d , plot2d2 , plot2d4 , clf , polyline_properties ,

Author

J.Ph.C.


plot2d4

Scilab Function
Last update : 08/06/2005

plot2d4 - 2D plot (arrows style)

Calling Sequence

plot2d4([logflag,] x,y,[style,strf,leg,rect,nax])
plot2d4(y)
plot2d4(x,y <,opt_args>)

Parameters

  • args : see plot2d for a description of parameters.

Description

plot2d4 is the same as plot2d but curves are plotted using arrows style. This can be useful when plotting solutions of an ODE in a phase space.

By default, successive plots are superposed. To clear the previous plot, use clf() .

Enter the command plot2d4() to see a demo. Note that all the modes proposed by plot2dxx (xx = 1 to 4) can be enabled using plot2d and setting the polyline_style option to the corresponding number.

Examples

// compare the following with plot2d1
x=[0:0.1:2*%pi]';
plot2d4(x,[sin(x) sin(2*x) sin(3*x)])
 // In New graphics only
clf()
set("figure_style","new")
plot2d(x,[sin(x) sin(2*x) sin(3*x)])
e=gce();
e.children(1).polyline_style=4;
e.children(2).polyline_style=4;
e.children(3).polyline_style=4;

See Also

fchamp , plot2d , plot2d2 , plot2d3 , subplot , clf , polyline_properties ,

Author

J.Ph.C.


plot2d_old_version

Scilab Function
Last update : 08/06/2005

plot2d_old_version - 2D plot reference

Calling Sequence

plot2d([x],y)
plot2d([x],y,<opt_args>) (new syntax)
plot2d([logflag],x,y,[style,strf,leg,rect,nax]) (old syntax)

Parameters

  • x,y : two matrices (or column vectors).
    • in the usual way x is a matrix of the same size than y (the column j of y is plotted with respect to column j of x )
    • if all the columns of x are equal (ie the abscissae of all the curves are the same), x may be simply the (column) vector of these abscissae ( x is then a column vector of length equal to the row dimension of y ).
    • when x is not given, it is supposed to be the column vector [1; 2; ...; row dimension of y].
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following:
    • style : sets the style for each curve, see below for value.
    • leg : sets the curves captions. If this key is given and strf is not given then x character of strf is supposed to be 1 . See below for value.
    • rect : sets the bounds of the plot. If this key is given and neither frameflag nor strf is given then the y character of strf is supposed to be 7 . See below for value.
    • nax : sets the grids definition. If this key is given and neither axesflag nor strf is given then the z character of strf is supposed to be 1 . See below for value.
    • logflag : sets the scale (linear or logarithmic) along the axes. See below for value.
    • frameflag : specifies how the frame of the plot is computed. The value is an integer ranging from 0 to 8. It corresponds to the y character of strf . See below.
    • axesflag : specifies what kind of axes are drawn around the plot. The value is an integer ranging from 0 to 5. It corresponds to the z character of strf . See below.
  • style : is a real row vector of size nc. The style to use for curve i is defined by style(i) . The default style is 1:nc (1 for the first curve, 2 for the second, etc.).
    • - if style(i) is negative or zero, the curve is plotted using the mark with id abs(style(i)) ; use xset() to set the mark id and xget('mark') to get the current mark id.
    • - if style(i) is strictly positive, a plain line with color id style(i) or a dashed line with dash id style(i) is used; use xset() to see the color ids.
    • - When only one curve is drawn, style can be the row vector of size 2 [sty,pos] where sty is used to specify the style and pos is an integer ranging from 1 to 6 which specifies a position to use for the caption. This can be useful when a user wants to draw multiple curves on a plot by calling the function plot2d several times and wants to give a caption for each curve.
  • strf : is a string of length 3 "xyz" (by default strf= "081" )
    • x : controls the display of captions.
      • x=0 : no caption.
      • x=1 : captions are displayed. They are given by the optional argument leg .
    • y : controls the computation of the actual coordinate ranges from the minimal requested values. Actual ranges can be larger than minimal requirements.
      • y=0 : no computation, the plot use the previus (or default) scale
      • y=1 : from the rect arg
      • y=2 : from the min/max of the x, y datas
      • y=3 : built for an isometric scale from the rect arg
      • y=4 : built for an isometric plot from the min/max of the x, y datas
      • y=5 : enlarged for pretty axes from the rect arg
      • y=6 : enlarged for pretty axes from the min/max of the x, y datas
      • y=7 : like y=1 but the previus plot(s) are redrawn to use the new scale
      • y=8 : like y=2 but the previus plot(s) are redrawn to use the new scale
    • z : controls the display of information on the frame around the plot. If axes are requested, the number of tics can be specified by the nax optional argument.
      • z=0 : nothing is drawn around the plot.
      • z=1 : axes are drawn, the y=axis is displayed on the left.
      • z=2 : the plot is surrounded by a box without tics.
      • z=3 : axes are drawn, the y=axis is displayed on the right.
      • z=4 : axes are drawn centred in the middle of the frame box.
      • z=5 : axes are drawn so as to cross at point (0,0) . If point (0,0) does not lie inside the frame, axes will not appear on the graph.
  • leg : a string. It is used when the first character x of argument strf is 1. leg has the form "leg1@leg2@...." where leg1 , leg2 , etc. are respectively the captions of the first curve, of the second curve, etc. The default is " " .
  • rect : This argument is used when the second character y of argument strf is 1, 3 or 5. It is a row vector of size 4 and gives the dimension of the frame: rect=[xmin,ymin,xmax,ymax] .
  • nax : This argument is used when the third character z of argument strf is 1. It is a row vector with four entries [nx,Nx,ny,Ny] where nx ( ny ) is the number of subgraduations on the x (y) axis and Nx ( Ny ) is the number of graduations on the x (y) axis.
  • logflag : a string formed by to characters h (for horizontal axis) and v (for vertical axis) each of these characters can take the values "n" or "l". "l" stands for logarithmic graduation and "n" for normal graduation. For example "ll"stands for a log-log plot. Default value is "nn".

Description

plot2d plots a set of 2D curves. Piecewise linear plotting is used.

By default, successive plots are superposed. To clear the previous plot, use xbasc() .

See the meaning of the parameters above for a complete description.

Enter the command plot2d() to see a demo.

Other high level plot2d function exist:

plot2d2: same as plot2d but the curve is supposed to be piecewise constant.
plot2d3: same as plot2d but the curve is plotted with vertical bars.
plot2d4: same as plot2d but the curve is plotted with arrows.

Examples

//simple plot
x=[0:0.1:2*%pi]';
plot2d(sin(x))
xbasc()
plot2d(x,sin(x))
//multiple plot
xbasc()
plot2d(x,[sin(x) sin(2*x) sin(3*x)])
// multiple plot giving the dimensions of the frame
// old syntax and new syntax
xbasc()
plot2d(x,[sin(x) sin(2*x) sin(3*x)],1:3,"011","",[0,0,6,0.5])
xbasc()
plot2d(x,[sin(x) sin(2*x) sin(3*x)],rect=[0,0,6,0.5])
//multiple plot with captions and given tics // old syntax and new syntax
xbasc()
plot2d(x,[sin(x) sin(2*x) sin(3*x)],..
  [1,2,3],"111","L1@L2@L3",[0,-2,2*%pi,2],[2,10,2,10]);
xbasc()
plot2d(x,[sin(x) sin(2*x) sin(3*x)],..
  [1,2,3],leg="L1@L2@L3",nax=[2,10,2,10],rect=[0,-2,2*%pi,2])
// isoview
xbasc()
plot2d(x,sin(x),1,"041")
// scale
xbasc()
plot2d(x,sin(x),1,"061")
// auto scaling with previous plots
xbasc()
plot2d(x,sin(x),1)
plot2d(x,2*sin(x),2)
plot2d(2*x,cos(x),3)
// axis on the right
xbasc()
plot2d(x,sin(x),1,"183","sin(x)")
// centered axis
xbasc()
plot2d(x,sin(x),1,"184","sin(x)")
// axis centered at (0,0)
xbasc()
plot2d(x-4,sin(x),1,"185","sin(x)")

See Also

plot2d1 , plot2d2 , plot2d3 , plot2d4 , xbasc , xset ,

Author

J.Ph.C.


plot2d

Scilab Function
Last update : 20/10/2005

plot2d - 2D plot

Calling Sequence

plot2d([x],y)
plot2d([x],y,<opt_args>)

Parameters

  • x : a real matrice or vector. If omitted, it is assumed to be the vector 1:n where n is the number of curve points given by the y parameter.
  • y : a real matrice or vector.
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following:
    • style : sets the style for each curve. The associated value should be a real vector with integer (positive or negative) values
    • rect : sets the mimimal bounds requested for the plot. The associated value should be a real vector with four entries: [xmin,ymin,xmax,ymax] .
    • logflag : sets the scale (linear or logarithmic) along the axes. The associated value should be a a string with possible values: "nn" , "nl" , "ln" and "ll" .
    • frameflag : controls the computation of the actual coordinate ranges from the minimal requested values. The associated value should be an integer ranging from 0 to 8.
    • axesflag : specifies how the axes are drawn. The associated value should be an integer ranging from 0 to 5.
    • nax : sets the axes labels and tics definition. The associated value should be a real vector with four integer entries [nx,Nx,ny,Ny]
    • leg : sets the curves captions. The associated value should be a character string

Description

plot2d plots a set of 2D curves. If you are familiar with Matlab plot syntax, you should use plot .

If x and y are vectors, plot2d(x,y,<opt_args>) plots vector y versus vector x . x and y vectors should have the same number of entries.

If x is a vector and y a matrix plot2d(x,y,<opt_args>) plots each columns of y versus vector x . In this case the number of columns of y should be equal to the number of x entries.

If x and y are matrices, plot2d(x,y,<opt_args>) plots each columns of y versus corresponding column of x . In this case the x and y sizes should be the same.

If y is a vector, plot2d(y,<opt_args>) plots vector y versus vector 1:size(y,'*') .

If y is a matrix, plot2d(y,<opt_args>) plots each columns of y versus vector 1:size(y,1) .

The <opt_args> arguments sould be used to customize the plot

style: This option may be used to specify how the curves are drawn. If this option is specified, the associated value should be a vector with as many entries as curves.
if style(i) is strictly positive, the curve is drawn as plain line and style(i) defines the index of the color used to draw the curve (see getcolor ). Note that the line style and the thickness can be set throught the polyline entity properties (see polyline_properties ).Piecewise linear interpolation is done between the given curve points.
if style(i) is negative or zero, the given curve points are drawn using marks, abs(style(i)) defines the mark with id used. Note that the marks color and marks sizes can be set throught the polyline entity properties (see polyline_properties ).
logflag: This option may be used to set the scale (linear or logarithmic) along the axes. The associated value should be a a string with possible values: "nn" , "nl" , "ln" and "ll" . "l" stands for logarithmic scale and graduations and "n" for normal scale.
rect: This option may be used to set the mimimal bounds requested for the plot. If this option is specified, the associated value should be a real vector with four entries:

[xmin,ymin,xmax,ymax] . xmin and xmax defines the bounds on the abscissae while ymin and ymax defines the bounds on the ordinates.

This argument may be used together with the frameflag option to specify how the axes boundaries are derived from teh given rect argument. If the frameflag option is not given, it is supposed to be frameflag=7 .

The axes boundaries can also be customized throught the axes entity properties (see axes_properties ).

frameflag: This option may be used to control the computation of the actual coordinate ranges from the minimal requested values. Actual ranges can be larger than minimal requirements.
frameflag=0: no computation, the plot use the previous (or default) scale.
frameflag=1: The actual range is the range given by the rect option.
frameflag=2: The actual range is computed from the min/max of the x and y data.
frameflag=3: The actual range is the range given by the rect option and enlarged to get an isometric scale.
frameflag=4: The actual range is computed from the min/max of the x and y data and enlarged to get an isometric scale.
frameflag=5: The actual range is the range given by the rect option and enlarged to get pretty axes labels.
frameflag=6: The actual range is computed from the min/max of the x and y data and enlarged to get pretty axes labels.
frameflag=7: like frameflag=1 but the previous plot(s) are redrawn to use the new scale. Used to add the current graph to a previous one.
frameflag=8: like frameflag=2 but the previous plot(s) are redrawn to use the new scale. Used to add the current graph to a previous one.
The axes boundaries can also be customized throught the axes entity properties (see axes_properties )
axesflag: This option may be used to specify how the axes are drawn. The associated value should be an integer ranging from 0 to 5 :
axesflag=0: nothing is drawn around the plot.
axesflag=1: axes are drawn, the y=axis is displayed on the left
axesflag=2: the plot is surrounded by a box without tics
axesflag=3: axes are drawn, the y=axis is displayed on the right
axesflag=4: axes are drawn centred in the middle of the frame box
axesflag=5: axes are drawn so as to cross at point (0,0) . If point (0,0) does not lie inside the frame, axes will not appear on the graph

The axes aspect can also be customized throught the axes entity properties (see axes_properties ).

nax: This option may be used to specify the axes labels and tics definition when axesflag=1 option is used. The associated value should be a real vector with four integer entries [nx,Nx,ny,Ny] . Nx gives the number of main tics to be used on the x-axis, nx gives the number of subtics to be drawn between two main x-axis tics. Ny and ny give similar information for the y-axis.If axesflag option is not set nax option supposes that axesflag option has been set to 1.
leg: This option may be used to sets the curve captions. It must be a string with the form "leg1@leg2@...." where leg1 , leg2 , etc. are respectively the captions of the first curve, of the second curve, etc. The default is " " .

The curve captions are drawn on below the x-axis. This option is not flexible enough, use the legends function preferably.

More information

To get more information on the plot2d old syntax , use the plot2d_old_version help document.

By default, successive plots are superposed. To clear the previous plot, use clf() .

Enter the command plot2d() to see a demo.

Other high level plot2d function exist:

  • plot2d2 : same as plot2d but the curve is supposed to be piecewise constant.
  • plot2d3 : same as plot2d but the curve is plotted with vertical bars.
  • plot2d4 : same as plot2d but the curve is plotted with arrows.

    • Examples

// x initialisation
x=[0:0.1:2*%pi]';
//simple plot
plot2d(sin(x))
clf()
plot2d(x,sin(x))
//multiple plot
clf()
plot2d(x,[sin(x) sin(2*x) sin(3*x)])
// multiple plot giving the dimensions of the frame
clf()
plot2d(x,[sin(x) sin(2*x) sin(3*x)],rect=[0,0,6,0.5])
//multiple plot with captions and given tics + style
clf()
plot2d(x,[sin(x) sin(2*x) sin(3*x)],..
  [1,2,3],leg="L1@L2@L3",nax=[2,10,2,10],rect=[0,-2,2*%pi,2])
// isoview
clf()
plot2d(x,sin(x),1,frameflag= 4)
// scale
clf()
plot2d(x,sin(x),1,frameflag= 6)
// auto scaling with previous plots + style
clf()
plot2d(x,sin(x),-1)
plot2d(x,2*sin(x),12)
plot2d(2*x,cos(x),3)
// axis on the right
clf()
plot2d(x,sin(x),leg="sin(x)")
a=gca(); // Handle on axes entity
a.y_location ="right";
// axis centered at (0,0)
clf()
plot2d(x-4,sin(x),1,leg="sin(x)")
a=gca() // Handle on axes entity
a.x_location = "middle";
a.y_location = "middle";
// Some operations on entities created by plot2d ...
a=gca();
a.isoview='on';
a.children // list the children of the axes : here it is an Compound child composed of 2 entities
poly1= a.children.children(2); //store polyline handle into poly1
poly1.foreground = 4; // another way to change the style...
poly1.thickness = 3;  // ...and the tickness of a curve.
poly1.clip_state='off' // clipping control
leg= a.children.children(1); // store legend handle into leg
leg.font_style = 9;
leg.foreground = 6;
a.isoview='off';

    See Also

    plot , plot2d1 , plot2d2 , plot2d3 , plot2d4 , clf , xdel , delete ,

    Author


plot3d1

Scilab Function
Last update : 08/06/2005

plot3d1 - 3D gray or color level plot of a surface

Calling Sequence

plot3d1(x,y,z,[theta,alpha,leg,flag,ebox])
plot3d1(xf,yf,zf,[theta,alpha,leg,flag,ebox])
plot3d1(x,y,z,<opts_args>)
plot3d1(xf,yf,zf,<opts_args>)

Parameters

  • x,y : row vectors of sizes n1 and n2 (x-axis and y-axis coordinates). These coordinates must be monotone.
  • z : matrix of size (n1,n2). z(i,j) is the value of the surface at the point (x(i),y(j)).
  • xf,yf,zf : matrices of size (nf,n). They define the facets used to draw the surface. There are n facets. Each facet i is defined by a polygon with nf points. The x-axis, y-axis and z-axis coordinates of the points of the ith facet are given respectively by xf(:,i) , yf(:,i) and zf(:,i) .
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following: theta, alpha ,leg,flag,ebox (see definition below).
  • theta, alpha : real values giving in degree the spherical coordinates of the observation point.
  • leg : string defining the labels for each axis with @ as a field separator, for example "X@Y@Z".
  • flag : a real vector of size three. flag=[mode,type,box] .
    • mode : an integer (surface color).
      • mode>0 : the surface is painted with color "mode" ; the boundary of the facet is drawn with current line style and color.
      • mode=0: a mesh of the surface is drawn.
      • mode<0: the surface is painted with color "-mode" ; the boundary of the facet is not drawn.

        Note that the surface color treatement can be done using color_mode and color_flag options through the surface entity properties (see surface_properties ).

    • type : an integer (scaling).
      • type=0: the plot is made using the current 3D scaling (set by a previous call to param3d , plot3d , contour or plot3d1 ).
      • type=1: rescales automatically 3d boxes with extreme aspect ratios, the boundaries are specified by the value of the optional argument ebox .
      • type=2: rescales automatically 3d boxes with extreme aspect ratios, the boundaries are computed using the given data.
      • type=3: 3d isometric with box bounds given by optional ebox , similarily to type=1 .
      • type=4: 3d isometric bounds derived from the data, to similarily type=2 .
      • type=5: 3d expanded isometric bounds with box bounds given by optional ebox , similarily to type=1 .
      • type=6: 3d expanded isometric bounds derived from the data, similarily to type=2 .

        Note that axes boundaries can be customized through the axes entity properties (see axes_properties ).

    • box : an integer (frame around the plot).
      • box=0: nothing is drawn around the plot.
      • box=1: unimplemented (like box=0).
      • box=2: only the axes behind the surface are drawn.
      • box=3: a box surrounding the surface is drawn and captions are added.
      • box=4: a box surrounding the surface is drawn, captions and axes are added.

        Note that axes aspect can also be customized through the axes entity properties (see axes_properties ).

  • ebox : It specifies the boundaries of the plot as the vector [xmin,xmax,ymin,ymax,zmin,zmax] . This argument is used together with type in flag : if it is set to 1 , 3 or 5 (see above to see the corresponding behaviour). If flag is missing, ebox is not taken into acoount.

    Note that, when specified, the ebox argument acts on the data_bounds field that can also be reset through the axes entity properties (see axes_properties ).

Description

plot3d1 plots a surface with colors depending on the z-level of the surface. This special plot function can also be enabled setting color_flag=1 after a plot3d (see surface_properties )

Enter the command plot3d1() to see a demo.

Examples

// simple plot using z=f(x,y)
t=[0:0.3:2*%pi]'; z=sin(t)*cos(t');
plot3d1(t,t,z)
// same plot using facets computed by genfac3d
[xx,yy,zz]=genfac3d(t,t,z);
clf();
plot3d1(xx,yy,zz)
// multiple plots
clf();
plot3d1([xx xx],[yy yy],[zz 4+zz])
// simple plot with viewpoint and captions
clf() ;
plot3d1(1:10,1:20,10*rand(10,20),35,45,"X@Y@Z",[2,2,3])
// same plot without grid
clf()
plot3d1(1:10,1:20,10*rand(10,20),35,45,"X@Y@Z",[-2,2,3])
// plot of a sphere using facets computed by eval3dp
deff("[x,y,z]=sph(alp,tet)",["x=r*cos(alp).*cos(tet)+orig(1)*ones(tet)";..
"y=r*cos(alp).*sin(tet)+orig(2)*ones(tet)";..
"z=r*sin(alp)+orig(3)*ones(tet)"]);
r=1; orig=[0 0 0];
[xx,yy,zz]=eval3dp(sph,linspace(-%pi/2,%pi/2,40),linspace(0,%pi*2,20));
clf()

plot3d(xx,yy,zz)
e=gce();
e.color_flag=1;
scf(2);
plot3d1(xx,yy,zz) // the 2 graphics are similar

See Also

plot3d , gca , gce , scf , clf ,

Author

J.Ph.C.


plot3d2

Scilab Function
Last update : 08/06/2005

plot3d2 - plot surface defined by rectangular facets

Calling Sequence

plot3d2(X,Y,Z [,vect,theta,alpha,leg,flag,ebox])
plot3d2(X,Y,Z, <opt_args>)

Parameters

  • X, Y, Z: 3 real matrices defining a data structure.
  • vect : a real vector.
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following: theta, alpha ,leg,flag,ebox (see definition below).
  • theta, alpha : real values giving in degree the spherical coordinates of the observation point.
  • leg : string defining the labels for each axis with @ as a field separator, for example "X@Y@Z".
  • flag : a real vector of size three. flag=[mode,type,box] .
    • mode : an integer (surface color).
      • mode>0 : the surface is painted with color "mode" ; the boundary of the facet is drawn with current line style and color.
      • mode=0: a mesh of the surface is drawn.
      • mode<0: the surface is painted with color "-mode" ; the boundary of the facet is not drawn.

        Note that the surface color treatement can be done using color_mode and color_flag options through the surface entity properties (see surface_properties ).

    • type : an integer (scaling).
      • type=0: the plot is made using the current 3D scaling (set by a previous call to param3d , plot3d , contour or plot3d1 ).
      • type=1: rescales automatically 3d boxes with extreme aspect ratios, the boundaries are specified by the value of the optional argument ebox .
      • type=2: rescales automatically 3d boxes with extreme aspect ratios, the boundaries are computed using the given data.
      • type=3: 3d isometric with box bounds given by optional ebox , similarily to type=1 .
      • type=4: 3d isometric bounds derived from the data, to similarily type=2 .
      • type=5: 3d expanded isometric bounds with box bounds given by optional ebox , similarily to type=1 .
      • type=6: 3d expanded isometric bounds derived from the data, similarily to type=2 .

        Note that axes boundaries can be customized through the axes entity properties (see axes_properties ).

    • box : an integer (frame around the plot).
      • box=0: nothing is drawn around the plot.
      • box=1: unimplemented (like box=0).
      • box=2: only the axes behind the surface are drawn.
      • box=3: a box surrounding the surface is drawn and captions are added.
      • box=4: a box surrounding the surface is drawn, captions and axes are added.

        Note that axes aspect can also be customized through the axes entity properties (see axes_properties ).

  • ebox : It specifies the boundaries of the plot as the vector [xmin,xmax,ymin,ymax,zmin,zmax] . This argument is used together with type in flag : if it is set to 1 , 3 or 5 (see above to see the corresponding behaviour). If flag is missing, ebox is not taken into acoount.

    Note that, when specified, the ebox argument acts on the data_bounds field that can also be reset through the axes entity properties (see axes_properties ).

Description

plot3d2 plots a surface defined by rectangular facets. (X,Y,Z) are three matrices which describe a surface. The surface is composed of four sided polygons. The X-coordinates of a facet are given by X(i,j),X(i+1,j),X(i,j+1),X(i+1,j+1). And similarly Y and Z are Y and Z coordinates. The vect vector is used when multiple surfaces are coded in the same (X,Y,Z) matrices. vect(j) gives the line at which the coding of the jth surface begins. Like in plot3d , the same properties are editable (see surface_properties and axes_properties ).

Examples

u = linspace(-%pi/2,%pi/2,40);
v = linspace(0,2*%pi,20);
X = cos(u)'*cos(v);
Y = cos(u)'*sin(v);
Z = sin(u)'*ones(v);
plot3d2(X,Y,Z);
 // New Graphic mode only
 e=gce();
e.color_mode=4; // change color
f=e.data;
TL = tlist(["3d" "x" "y" "z" "color"],f.x,f.y,f.z,10*(f.z)+1);
e.data=TL;
e.color_flag=2;

See Also

plot3d , genfac3d ,


plot3d3

Scilab Function
Last update : 08/06/2005

plot3d3 - mesh plot surface defined by rectangular facets

Calling Sequence

plot3d3(X,Y,Z [,vect,theta,alpha,leg,flag,ebox])
plot3d3(X,Y,Z, <opt_args>)

Parameters

  • X, Y, Z: 3 real matrices defining a data structure.
  • vect : a real vector.
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following: theta, alpha ,leg,flag,ebox (see definition below).
  • theta, alpha : real values giving in degree the spherical coordinates of the observation point.
  • leg : string defining the labels for each axis with @ as a field separator, for example "X@Y@Z".
  • flag : a real vector of size three. flag=[mode,type,box] .
    • mode : an integer (surface color).
      • mode>0 : the surface is painted with color "mode" ; the boundary of the facet is drawn with current line style and color.
      • mode=0: a mesh of the surface is drawn.
      • mode<0: the surface is painted with color "-mode" ; the boundary of the facet is not drawn.

        Note that the surface color treatement can be done using color_mode and color_flag options through the surface entity properties (see surface_properties ).

    • type : an integer (scaling).
      • type=0: the plot is made using the current 3D scaling (set by a previous call to param3d , plot3d , contour or plot3d1 ).
      • type=1: rescales automatically 3d boxes with extreme aspect ratios, the boundaries are specified by the value of the optional argument ebox .
      • type=2: rescales automatically 3d boxes with extreme aspect ratios, the boundaries are computed using the given data.
      • type=3: 3d isometric with box bounds given by optional ebox , similarily to type=1 .
      • type=4: 3d isometric bounds derived from the data, to similarily type=2 .
      • type=5: 3d expanded isometric bounds with box bounds given by optional ebox , similarily to type=1 .
      • type=6: 3d expanded isometric bounds derived from the data, similarily to type=2 .

        Note that axes boundaries can be customized through the axes entity properties (see axes_properties ).

    • box : an integer (frame around the plot).
      • box=0: nothing is drawn around the plot.
      • box=1: unimplemented (like box=0).
      • box=2: only the axes behind the surface are drawn.
      • box=3: a box surrounding the surface is drawn and captions are added.
      • box=4: a box surrounding the surface is drawn, captions and axes are added.

        Note that axes aspect can also be customized through the axes entity properties (see axes_properties ).

  • ebox : It specifies the boundaries of the plot as the vector [xmin,xmax,ymin,ymax,zmin,zmax] . This argument is used together with type in flag : if it is set to 1 , 3 or 5 (see above to see the corresponding behaviour). If flag is missing, ebox is not taken into acoount. Note that, when specified, the ebox argument acts on the data_bounds field that can also be reset through the axes entity properties (see axes_properties ).

Description

plot3d3 performs a mesh plot of a surface defined by rectangular facets. (X,Y,Z) are three matrices which describe a surface. The surface is composed of four sided polygons.

The X-coordinates of a facet are given by X(i,j),X(i+1,j),X(i,j+1),X(i+1,j+1). And similarly Y and Z are Y and Z coordinates.

The vect vector is used when multiple surfaces are coded in the same (X,Y,Z) matrices. vect(j) gives the line at which the coding of the jth surface begins. See plot3d2 for a full description. As a mesh plot, the only available property you can edit is the visible option (see axes_properties ).

Examples

u = linspace(-%pi/2,%pi/2,40);
v = linspace(0,2*%pi,20);
X = cos(u)'*cos(v);
Y = cos(u)'*sin(v);
Z = sin(u)'*ones(v);
plot3d3(X,Y,Z);
 // New Graphic mode only
e=gce(); // get the current entity
e.visible='off';
e.visible='on'; // back to the mesh view

See Also

plot3d2 , plot3d , param3d ,


plot3d_old_version

Scilab Function
Last update : 08/06/2005

plot3d_old_version - 3D plot of a surface

Calling Sequence

plot3d(x,y,z,[theta,alpha,leg,flag,ebox])
plot3d(x,y,z,<opt_args>)
plot3d(xf,yf,zf,[theta,alpha,leg,flag,ebox])
plot3d(xf,yf,zf,<opt_args>)
plot3d(xf,yf,list(zf,colors),[theta,alpha,leg,flag,ebox])
plot3d(xf,yf,list(zf,colors),<opt_args>)

Parameters

  • x,y : row vectors of sizes n1 and n2 (x-axis and y-axis coordinates). These coordinates must be monotone.
  • z : matrix of size (n1,n2). z(i,j) is the value of the surface at the point (x(i),y(j)).
  • xf,yf,zf : matrices of size (nf,n). They define the facets used to draw the surface. There are n facets. Each facet i is defined by a polygon with nf points. The x-axis, y-axis and z-axis coordinates of the points of the ith facet are given respectively by xf(:,i) , yf(:,i) and zf(:,i) .
  • colors : a vector of size n giving the color of each facets or a matrix of size (nf,n) giving color near each facet boundary (facet color is interpolated )
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following: theta, alpha ,leg,flag,ebox (see definition below)
  • theta, alpha : real values giving in degree the spherical coordinates of the observation point.
  • leg : string defining the captions for each axis with @ as a field separator, for example "X@Y@Z".
  • flag : a real vector of size three flag=[mode,type,box] .
    • mode : string (treatment of hidden parts).
      • mode>0 the hidden parts of the surface are removed and the surface is painted with color mode .
      • mode=0 the hidden parts of the surface are drawn.
      • mode<0 only the backward facing facets are painted with color or pattern id -mode . Use xset() to see the meaning of the ids.
    • type : an integer (scaling).
      • type=0 the plot is made using the current 3D scaling (set by a previous call to param3d , plot3d , contour or plot3d1 ).
      • type=1 rescales automatically 3d boxes with extreme aspect ratios, the boundaries are specified by the value of the optional argument ebox .
      • type=2 rescales automatically 3d boxes with extreme aspect ratios, the boundaries are computed using the given data.
      • type=3 3d isometric with box bounds given by optional ebox , similarily to type=1
      • type=4 3d isometric bounds derived from the data, to similarily type=2
      • type=5 3d expanded isometric bounds with box bounds given by optional ebox , similarily to type=1
      • type=6 3d expanded isometric bounds derived from the data, similarily to type=2
    • box : an integer (frame around the plot).
      • box=0 nothing is drawn around the plot.
      • box=1 unimplemented (like box=0).
      • box=2 only the axes behind the surface are drawn.
      • box=3 a box surrounding the surface is drawn and captions are added.
      • box=4 a box surrounding the surface is drawn, captions and axes are added.
  • ebox : used when type in flag is 1. It specifies the boundaries of the plot as the vector [xmin,xmax,ymin,ymax,zmin,zmax] .

Description

plot3d(x,y,z,[theta,alpha,leg,flag,ebox]) draws the parametric surface z=f(x,y) .

plot3d(xf,yf,zf,[theta,alpha,leg ,flag,ebox]) draws a surface defined by a set of facets. You can draw multiple plots by replacing xf , yf and zf by multiple matrices assembled by rows as [xf1 xf2 ...] , [yf1 yf2 ...] and [zf1 zf2 ...] .

You can give a specific color for each facet by using list(zf,colors) instead of zf , where colors is a vector of size n . If colors(i) is positive it gives the color of facet i and the boundary of the facet is drawn with current line style and color. If colors(i) is negative, color id -colors(i) is used and the boundary of the facet is not drawn. Use xset() to see the ids of the colors.

It is also possible to get interpolated color for facets. For that the color argument must be a matrix of size nfxn giving the color near each boundary of each facets. In this case positive values for colors mean that the boundary are not drawn.

The optional arguments theta,alpha,leg ,flag,ebox , can be passed by a sequence of statements key1=value1, key2=value2 , ... In this case, the order has no special meaning.

You can use the function genfac3d to compute four sided facets from the surface z=f(x,y) . eval3dp can also be used.

Enter the command plot3d() to see a demo.

Examples

// simple plot using z=f(x,y)
t=[0:0.3:2*%pi]'; z=sin(t)*cos(t');
plot3d(t,t,z)
// same plot using facets computed by genfac3d
[xx,yy,zz]=genfac3d(t,t,z);
xbasc()
plot3d(xx,yy,zz)
// multiple plots
xbasc()
plot3d([xx xx],[yy yy],[zz 4+zz])
// multiple plots using colors
xbasc()
plot3d([xx xx],[yy yy],list([zz zz+4],[4*ones(1,400) 5*ones(1,400)]))
// simple plot with viewpoint and captions
xbasc()
plot3d(1:10,1:20,10*rand(10,20),35,45,"X@Y@Z",[2,2,3])
// plot of a sphere using facets computed by eval3dp
deff("[x,y,z]=sph(alp,tet)",["x=r*cos(alp).*cos(tet)+orig(1)*ones(tet)";..
  "y=r*cos(alp).*sin(tet)+orig(2)*ones(tet)";..
  "z=r*sin(alp)+orig(3)*ones(tet)"]);
r=1; orig=[0 0 0];
[xx,yy,zz]=eval3dp(sph,linspace(-%pi/2,%pi/2,40),linspace(0,%pi*2,20));
xbasc();plot3d(xx,yy,zz)

xbasc();xset('colormap',hotcolormap(128));
r=0.3;orig=[1.5 0 0];
[xx1,yy1,zz1]=eval3dp(sph,linspace(-%pi/2,%pi/2,40),linspace(0,%pi*2,20));
cc=(xx+zz+2)*32;cc1=(xx1-orig(1)+zz1/r+2)*32;
xbasc();plot3d1([xx xx1],[yy yy1],list([zz,zz1],[cc cc1]),70,80)

xbasc();plot3d1([xx xx1],[yy yy1],list([zz,zz1],[cc cc1]),theta=70,alpha=80,flag=[5,6,3])

See Also

eval3dp , genfac3d , geom3d , param3d , plot3d1 , xset ,

Author

J.Ph.C.


plot3d

Scilab Function
Last update : 18/11/2005

plot3d - 3D plot of a surface

Calling Sequence

plot3d(x,y,z,[theta,alpha,leg,flag,ebox])
plot3d(x,y,z,<opt_args>)
plot3d(xf,yf,zf,[theta,alpha,leg,flag,ebox])
plot3d(xf,yf,zf,<opt_args>)
plot3d(xf,yf,list(zf,colors),[theta,alpha,leg,flag,ebox])
plot3d(xf,yf,list(zf,colors),<opt_args>)

Parameters

  • x,y : row vectors of sizes n1 and n2 (x-axis and y-axis coordinates). These coordinates must be monotone.
  • z : matrix of size (n1,n2). z(i,j) is the value of the surface at the point (x(i),y(j)).
  • xf,yf,zf : matrices of size (nf,n). They define the facets used to draw the surface. There are n facets. Each facet i is defined by a polygon with nf points. The x-axis, y-axis and z-axis coordinates of the points of the ith facet are given respectively by xf(:,i) , yf(:,i) and zf(:,i) .
  • colors : a vector of size n giving the color of each facets or a matrix of size (nf,n) giving color near each facet boundary (facet color is interpolated ).
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following: theta, alpha ,leg,flag,ebox (see definition below).
  • theta, alpha : real values giving in degree the spherical coordinates of the observation point.
  • leg : string defining the labels for each axis with @ as a field separator, for example "X@Y@Z".
  • flag : a real vector of size three. flag=[mode,type,box] .
    • mode : an integer (surface color).
      • mode>0 : the surface is painted with color "mode" ; the boundary of the facet is drawn with current line style and color.
      • mode=0: a mesh of the surface is drawn.
      • mode<0: the surface is painted with color "-mode" ; the boundary of the facet is not drawn.

        Note that the surface color treatement can be done using color_mode and color_flag options through the surface entity properties (see surface_properties ).

    • type : an integer (scaling).
      • type=0: the plot is made using the current 3D scaling (set by a previous call to param3d , plot3d , contour or plot3d1 ).
      • type=1: rescales automatically 3d boxes with extreme aspect ratios, the boundaries are specified by the value of the optional argument ebox .
      • type=2: rescales automatically 3d boxes with extreme aspect ratios, the boundaries are computed using the given data.
      • type=3: 3d isometric with box bounds given by optional ebox , similarily to type=1 .
      • type=4: 3d isometric bounds derived from the data, to similarily type=2 .
      • type=5: 3d expanded isometric bounds with box bounds given by optional ebox , similarily to type=1 .
      • type=6: 3d expanded isometric bounds derived from the data, similarily to type=2 .

        Note that axes boundaries can be customized through the axes entity properties (see axes_properties ).

    • box : an integer (frame around the plot).
      • box=0: nothing is drawn around the plot.
      • box=1: unimplemented (like box=0).
      • box=2: only the axes behind the surface are drawn.
      • box=3: a box surrounding the surface is drawn and captions are added.
      • box=4: a box surrounding the surface is drawn, captions and axes are added.

        Note that axes aspect can also be customized through the axes entity properties (see axes_properties ).

  • ebox : It specifies the boundaries of the plot as the vector [xmin,xmax,ymin,ymax,zmin,zmax] . This argument is used together with type in flag : if it is set to 1 , 3 or 5 (see above to see the corresponding behaviour). If flag is missing, ebox is not taken into acoount.

    Note that, when specified, the ebox argument acts on the data_bounds field that can also be reset through the axes entity properties (see axes_properties ).

Description

plot3d(x,y,z,[theta,alpha,leg,flag,ebox]) draws the parametric surface z=f(x,y) .

plot3d(xf,yf,zf,[theta,alpha,leg ,flag,ebox]) draws a surface defined by a set of facets. You can draw multiple plots by replacing xf , yf and zf by multiple matrices assembled by rows as [xf1 xf2 ...] , [yf1 yf2 ...] and [zf1 zf2 ...] . Note that data can also be set or get through the surface entity properties (see surface_properties ).

You can give a specific color for each facet by using list(zf,colors) instead of zf , where colors is a vector of size n . If colors(i) is positive it gives the color of facet i and the boundary of the facet is drawn with current line style and color. If colors(i) is negative, color id -colors(i) is used and the boundary of the facet is not drawn.

It is also possible to get interpolated color for facets. For that the color argument must be a matrix of size nfxn giving the color near each boundary of each facets. In this case positive values for colors mean that the boundary are not drawn. Note that colors can also be set through the surface entity properties (via tlist affectations) and edited using color_flag option (see surface_properties ).

The optional arguments theta, alpha, leg ,flag, ebox , can be passed by a sequence of statements key1=value1, key2=value2 , ... In this case, the order has no special meaning. Note that all these optional arguments except flag can be customized through the axes entity properties (see axes_properties ). As described before, the flag option deals with surface entity properties for mode (see surface_properties ) and axes properties for type and box (see axes_properties ).

You can use the function genfac3d to compute four sided facets from the surface z=f(x,y) . eval3dp can also be used.

Enter the command plot3d() to see a demo.

More information

To get more information on the plot3d old syntax , use the plot3d_old_version help document.

Examples

// simple plot using z=f(x,y)
t=[0:0.3:2*%pi]';
z=sin(t)*cos(t');
plot3d(t,t,z)
// same plot using facets computed by genfac3d
[xx,yy,zz]=genfac3d(t,t,z);
clf()
plot3d(xx,yy,zz)
// multiple plots
clf()
plot3d([xx xx],[yy yy],[zz 4+zz])
// multiple plots using colors
clf()
plot3d([xx xx],[yy yy],list([zz zz+4],[4*ones(1,400) 5*ones(1,400)]))
// simple plot with viewpoint and captions
clf()
plot3d(1:10,1:20,10*rand(10,20),alpha=35,theta=45,flag=[2,2,3])
// plot of a sphere using facets computed by eval3dp
deff("[x,y,z]=sph(alp,tet)",["x=r*cos(alp).*cos(tet)+orig(1)*ones(tet)";..
 "y=r*cos(alp).*sin(tet)+orig(2)*ones(tet)";..
 "z=r*sin(alp)+orig(3)*ones(tet)"]);
r=1; orig=[0 0 0];
[xx,yy,zz]=eval3dp(sph,linspace(-%pi/2,%pi/2,40),linspace(0,%pi*2,20));
clf();plot3d(xx,yy,zz)
clf();
f=gcf();
f.color_map = hotcolormap(128);
r=0.3;orig=[1.5 0 0];
[xx1,yy1,zz1]=eval3dp(sph,linspace(-%pi/2,%pi/2,40),linspace(0,%pi*2,20));
cc=(xx+zz+2)*32;cc1=(xx1-orig(1)+zz1/r+2)*32;
clf();plot3d1([xx xx1],[yy yy1],list([zz,zz1],[cc cc1]),theta=70,alpha=80,flag=[5,6,3])

//Available operations using only New Graphics...
delete(gcf());
t=[0:0.3:2*%pi]'; z=sin(t)*cos(t');
[xx,yy,zz]=genfac3d(t,t,z);
plot3d([xx xx],[yy yy],list([zz zz+4],[4*ones(1,400) 5*ones(1,400)]))
e=gce();
f=e.data;
TL = tlist(["3d" "x" "y" "z" "color"],f.x,f.y,f.z,6*rand(f.z)); // random color matrix
e.data = TL;
TL2 = tlist(["3d" "x" "y" "z" "color"],f.x,f.y,f.z,4*rand(1,800)); // random color vector
e.data = TL2;
TL3 = tlist(["3d" "x" "y" "z" "color"],f.x,f.y,f.z,[20*ones(1,400) 6*ones(1,400)]);
e.data = TL3;
TL4 = tlist(["3d" "x" "y" "z"],f.x,f.y,f.z); // no color
e.data = TL4;
e.color_flag=1 // color index proportional to altitude (z coord.)
e.color_flag=2; // back to default mode
e.color_flag= 3; // interpolated shading mode (based on blue default color)
clf()
plot3d([xx xx],[yy yy],list([zz zz+4],[4*ones(1,400) 5*ones(1,400)]))
h=gce(); //get handle on current entity (here the surface)
a=gca(); //get current axes
a.rotation_angles=[40,70];
a.grid=[1 1 1]; //make grids
a.data_bounds=[-6,0,-1;6,6,5];
a.axes_visible="off"; //axes are hidden
a.axes_bounds=[.2 0 1 1];
h.color_flag=1; //color according to z
h.color_mode=-2;  //remove the facets boundary by setting color_mode to white color
h.color_flag=2; //color according to given colors
h.color_mode = -1; // put the facets boundary back by setting color_mode to black color
f=gcf();//get the handle of the parent figure
f.color_map=hotcolormap(512);
c=[1:400,1:400];
TL.color = [c;c+1;c+2;c+3];
h.data = TL;
h.color_flag=3; // interpolated shading mode

See Also

eval3dp , genfac3d , geom3d , param3d , plot3d1 , clf , gca , gcf , xdel , delete ,

Author

J.Ph.C.


plotframe

Last update : 24/10/2006

plotframe - dessine un cadre avec graduations et définition de l'échelle

Calling Sequence

plotframe(rect,tics,[arg_opt1,arg_opt2,arg_opt3])
plotframe( rect, <opt_args> )

Parameters

  • rect : vecteur du type [xmin,ymin,xmax,ymax] .
  • tics : vecteur du type [nx,mx,ny,my] où mx, nx (resp. my, ny ) sont le nombre d'intervalles et de sous-intervalle pour les graduations de l'axe Ox (resp. Oy).
  • arg_optX : arguments optionnels choisi parmi :
    • flags : vecteur booléen [wantgrids,findbounds] ( %t ou %f ) indiquant si l'on désire une grille. Si findbounds vaut %t , les bornes données dans rect sont éventuellement modifiées (en fait légèrement augmentées) pour simplifier les graduations : dans ce cas tics(2) et tics(4) sont ignorés.
    • captions : vecteur de 3 chaînes de caractères [title,x-leg,y-leg] correspondant au titre du dessin et aux légendes des axes x et y.
    • subwin : vecteur de taille 4 définissant la sous-fenêtre. La sous-fenêtre est spécifiée avec le paramètre subwin=[x,y,w,h] (point en haut à gauche, largeur, hauteur). Les valeurs dans subwin sont spécifiées sous la forme d'une proportion de la largeur ou de la hauteur de la fenêtre graphique courante (voir xsetech ).
  • <opts_args> : Représente une séquence de la forme clé1=valeur1, clé2=valeur2,... where clé1, clé2,... peuvent être n'importe quel paramètres parmis: tics, flags, captions ou subwin. Ces arguments ont la même signification que ceux utilisés dans la première forme de la routine.

Description

lotframe est utilisée avec les fonctions de dessin 2D plot2d ,... pour dessiner le cadre. Elle doit être utilisée avant plot2d qui doit être ensuite appelée avec le mode de superposition "000".

Examples

    x=[-0.3:0.8:27.3]';
    y=rand(x);
    rect=[min(x),min(y),max(x),max(y)];
    tics=[4,10,2,5];    // 4 x-intervalles et 2 y-intervalles
    plotframe(rect,tics,[%f,%f],["My plot","x","y"],[0,0,0.5,0.5])
    plot2d(x,y,2,"000")
    plotframe(rect,tics,[%t,%f],["My plot avec grille","x","y"],[0.5,0,0.5,0.5])
    plot2d(x,y,3,"000")
    plotframe(rect,tics,[%t,%t],..
    ["plot avec grille et bornes automatiques","x","y"],[0,0.5,0.5,0.5])
    plot2d(x,y,4,"000")
    plotframe(rect,flags=[%f,%t],tics=tics,..
       captions=["plot sans grille mais avec bornes automatiques ","x","y"],..
       subwin=[0.5,0.5,0.5,0.5])
    plot2d(x,y,5,"000")
    xset("default")

See Also

plot2d , graduate , xsetech ,


plot

Scilab Function
Last update : 09/02/2006

plot - 2D plot

Calling Sequence

plot(y,<LineSpec>,<GlobalProperty>)
plot(x,y,<LineSpec>,<GlobalProperty>)
plot(x1,y1,<LineSpec1>,x2,y2,<LineSpec2>,...xN,yN,<LineSpecN>,<GlobalProperty1>,<GlobalProperty2>,..<GlobalPropertyM>)
plot(<axes_handle>,...)

Parameters

  • x : a real matrice or vector. If omitted, it is assumed to be the vector 1:n where n is the number of curve points given by the y parameter.
  • y : a real matrice or vector. y can also be a function defined as a macro or a primitive.
  • <LineSpec> : This optional argument must be a string that will be used as a shortcut to specify a way of drawing a line. We can have one LineSpec per y or {x,y} previously entered. LineSpec options deals with LineStyle, Marker and Color specifiers (see LineSpec ). Those specifiers determine the line style, mark style and color of the plotted lines.
  • <GlobalProperty> : This optional argument represents a sequence of couple statements {PropertyName,PropertyValue} that defines global objects' properties applied to all the curves created by this plot. For a complete view of the available properties (see GlobalProperty ).
  • <axes_handle> : This optional argument forces the plot to appear inside the selected axes given by axes_handle rather than the current axes (see gca ).

Description

plot plots a set of 2D curves. plot has been rebuild to better handle Matlab syntax. To improve graphical compatibility, Matlab users should use plot (rather than plot2d ).

Data entry specification :

In this paragraph and to be more clear, we won't mention LineSpec nor GlobalProperty optional arguments as they do not interfer with entry data (except for "Xdata" , "Ydata" and "Zdata" property, see GlobalProperty ). It is assumed that all those optional arguments could be present too.

If y is a vector, plot(y) plots vector y versus vector 1:size(y,'*') .

If y is a matrix, plot(y) plots each columns of y versus vector 1:size(y,1) .

If x and y are vectors, plot(x,y) plots vector y versus vector x . x and y vectors should have the same number of entries.

If x is a vector and y a matrix plot(x,y) plots each columns of y versus vector x . In this case the number of columns of y should be equal to the number of x entries.

If x and y are matrices, plot(x,y) plots each columns of y versus corresponding column of x . In this case the x and y sizes should be the same.

Finally, if only x or y is a matrix, the vector is plotted versus the rows or columns of the matrix. The choice is made depending on whether the vector's row or column dimension matches the matrix row or column dimension. In case of a square matrix (on x or y only), priority is given to columns rather than lines (see examples below).

y can also be a function defined as a macro or a primitive. In this case, x data must be given (as a vector or matrix) and the corresponding computation y(x) is done implicitly.

The LineSpec and GlobalProperty arguments sould be used to customize the plot. Here is a complete list of the available options.

LineSpec: This option may be used to specify, in a short and easy manner, how the curves are drawn. It must always be a string containing references to LineStyle, Marker and Color specifiers.These references must be set inside the string (order is not important) in an unambiguous way. For example, to specify a red long-dashed line with the diamond mark enabled, you can write : 'r--d' or '--dire' or '--reddiam' or another unambiguous statement... or to be totally complete 'diamondred--' (see LineSpec ).

Note that the line style and color, marks color (and sizes) can also be (re-)set throught the polyline entity properties (see polyline_properties ).

GlobalProperty: This option may be used to specify how all the curves are plotted using more option than via LineSpec . It must always be a couple statement constituted of a string defining the PropertyName , and its associated value PropertyValue (which can be a string or an integer or... as well depending on the type of the PropertyName ). Using GlobalProperty , you can set multiple properties : every properties available via LineSpec and more : the marker color (foreground and background), the visibility, clipping and thickness of the curves. (see GlobalProperty )

Note that all these properties can be (re-)set throught the polyline entity properties (see polyline_properties ).

Remarks

By default, successive plots are superposed. To clear the previous plot, use clf() . To enable auto_clear mode as the default mode, edit your default axes doing:

da=gda();

da.auto_clear = 'on'

A default color table is used to color plotted curves if you do not specify a color. When drawing multiple lines, the plot command automatically cycles through this table. Here are the used colors:

R | G | B
0. | 0. | 1.
0. | 0.5 | 0.
1. | 0. | 0.
0. | 0.75 | 0.75
0.75 | 0. | 0.75
0.75 | 0.75 | 0.
0.25 | 0.25 | 0.25

Enter the command plot to see a demo.

Examples

// x initialisation
x=[0:0.1:2*%pi]';
//simple plot
plot(sin(x))
clf()
plot(x,sin(x))
//multiple plot
clf()
plot(x,[sin(x) sin(2*x) sin(3*x)])
clf()

// axis on the right
plot(x,sin(x))
a=gca(); // Handle on current axes entity
a.y_location ="right";
clf()

// axis centered at (0,0)
plot(x-4,sin(x),x+2,cos(x))
a=gca(); // Handle on axes entity
a.x_location = "middle";
a.y_location = "middle";

// Some operations on entities created by plot ...
a=gca();
a.isoview='on';
a.children // list the children of the axes : here it is an Compound child composed of 2 entities
poly1= a.children.children(2); //store polyline handle into poly1
poly1.foreground = 4; // another way to change the style...
poly1.thickness = 3;  // ...and the tickness of a curve.
poly1.clip_state='off' // clipping control
a.isoview='off';

//LineSpec and GlobalProperty examples:
clf();
t=0:%pi/20:2*%pi;
plot(t,sin(t),'ro-.',t,cos(t),'cya+',t,abs(sin(t)),'--mo')
scf(2)
plot([t ;t],[sin(t) ;cos(t)],'xdat',[1:2])
scf(3)
axfig3 = gca();
scf(4) // should remain blank
plot(axfig3,[t ;t],[sin(t) ;cos(t)],'zdat',[1:2],'marker','d','markerfac','green','markeredg','yel')
xdel(winsid())

//Data specification
t=-%pi:0.1:%pi;
size(t)
plot(t) // simply plots y versus t vector size
clf(); // clear figure

plot(t,sin(t)); // plots sin(t) versus t
clf();

t=[1     1     1     1
   2     3     4     5
   3     4     5     6
   4     5     6     7];

plot(t) // plots each t column versus row size
clf();

subplot(221)
plot(t,sin(t)); // plots sin(t) versus t column by column this time
xtitle("sin(t) versus t")
subplot(222)
plot(t,sin(t)')
xtitle("sin(t)'' versus t")
subplot(223)
plot(t',sin(t))
a=gca();
a.data_bounds=[0 -1;7 1]; // to see the vertical line hiddden by the y axis
xtitle("sin(t) versus t''")
subplot(224)
plot(t',sin(t)')
xtitle("sin(t)'' versus t''")

clf();

//Special case 1
//x : vector ([5 6 7 8]) and y : matrix (t)
x=[5 6 7 8]
plot(x,t);
plot(x',t); // idem, x is automatically transposed to match t (here the columns)
clf()

// Only one matching possibility case : how to make 4 identical plots in 4 manners...
// x is 1x4 (vector) and y is 4x5 (non square matrix)
subplot(221);
plot(x,[t [8;9;10;12]]');
subplot(222);
plot(x',[t [8;9;10;12]]');
subplot(223);
plot(x,[t [8;9;10;12]]');
subplot(224);
plot(x',[t [8;9;10;12]]');
clf()

//Special case 2
// Case where only x or y is a square matrix
//x : matrix (t) and y  : vector ([1 2 3 4])
plot(t,[1 2 3 4]) // equivalent to plot(t,[1 1 1 1;2 2 2 2;3 3 3 3;4 4 4 4])
plot(t,[1;2;3;4]) // the same plot
clf();

// t is transposed : notice the priority given to the columns treatment
plot(t',[1 2 3 4]) // equivalent to plot(t',[1 1 1 1;2 2 2 2;3 3 3 3;4 4 4 4])
plot(t',[1 2 3 4]') // the same plot
clf();

// y is a function defined by..
// ..a primitive
plot(1:0.1:10,sin) // equivalent to plot(1:0.1:10,sin(1:0.1:10))
clf();

// ..a macro:
deff('[y]=toto(x)','y=x.*x')
plot(1:10,toto)

See Also

plot2d , surf , scf , clf , xdel , delete , LineSpec , GlobalProperty ,

Author

F.Leray


plzr

Scilab Function
Last update : 12/01/2004

plzr - pole-zero plot

Calling Sequence

plzr(sl)

Parameters

  • sl : list ( syslin )

Description

produces a pole-zero plot of the linear system sl ( syslin list)

Examples

s=poly(0,'s');
n=[1+s   2+3*s+4*s^2        5; 0        1-s             s];
d=[1+3*s   5-s^3           s+1;1+s     1+s+s^2      3*s-1];
h=syslin('c',n./d);
plzr(h);

See Also

trzeros , roots , syslin ,


polarplot

Scilab Function
Last update : 08/06/2005

polarplot - Plot polar coordinates

Calling Sequence

polarplot(theta,rho,[style,strf,leg,rect])
polarplot(theta,rho,<opt_args>)

Parameters

  • rho : a vector, the radius values
  • theta : a vector with same size than rho, the angle values.
  • <opt_args> : a sequence of statements key1=value1, key2=value2 , ... where keys may be style , leg , rect , strf or frameflag
  • style : is a real row vector of size nc. The style to use for curve i is defined by style(i) . The default style is 1:nc (1 for the first curve, 2 for the second, etc.).
    • - if style(i) is negative, the curve is plotted using the mark with id abs(style(i))+1 ; use xset() to see the mark ids.
    • - if style(i) is strictly positive, a plain line with color id style(i) or a dashed line with dash id style(i) is used; use xset() to see the color ids.
    • - When only one curve is drawn, style can be the row vector of size 2 [sty,pos] where sty is used to specify the style and pos is an integer ranging from 1 to 6 which specifies a position to use for the caption. This can be useful when a user wants to draw multiple curves on a plot by calling the function plot2d several times and wants to give a caption for each curve.
  • strf : is a string of length 3 "xy0" .
    • default The default is "030" .
    • x : controls the display of captions,
      • x=0 : no captions.
      • x=1 : captions are displayed. They are given by the optional argument leg .
    • y : controls the computation of the frame. same as frameflag
      • y=0 : the current boundaries (set by a previous call to another high level plotting function) are used. Useful when superposing multiple plots.
      • y=1 : the optional argument rect is used to specify the boundaries of the plot.
      • y=2 : the boundaries of the plot are computed using min and max values of x and y .
      • y=3 : like y=1 but produces isoview scaling.
      • y=4 : like y=2 but produces isoview scaling.
      • y=5 : like y=1 but plot2d can change the boundaries of the plot and the ticks of the axes to produce pretty graduations. When the zoom button is activated, this mode is used.
      • y=6 : like y=2 but plot2d can change the boundaries of the plot and the ticks of the axes to produce pretty graduations. When the zoom button is activated, this mode is used.
      • y=7 : like y=5 but the scale of the new plot is merged with the current scale.
      • y=8 : like y=6 but the scale of the new plot is merged with the current scale.
  • leg : a string. It is used when the first character x of argument strf is 1. leg has the form "leg1@leg2@...." where leg1 , leg2 , etc. are respectively the captions of the first curve, of the second curve, etc. The default is " " .
  • rect : This argument is used when the second character y of argument strf is 1, 3 or 5. It is a row vector of size 4 and gives the dimension of the frame: rect=[xmin,ymin,xmax,ymax] .

Description

polarplot creates a polar coordinate plot of the angle theta versus the radius rho. theta is the angle from the x-axis to the radius vector specified in radians; rho is the length of the radius vector specified in dataspace units.

Examples

t= 0:.01:2*%pi;
clf();polarplot(sin(7*t),cos(8*t))

clf();polarplot([sin(7*t') sin(6*t')],[cos(8*t') cos(8*t')],[1,2])


polyline_properties

Scilab Data type
Last update : 06/01/2006

polyline_properties - description of the Polyline entity properties

Description

The Polyline entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for polylines.

parent: This field contains the handle of the parent. The parent of the polyline entity should be of the type "Axes" or "Compound" .
children: This property contains a vector with the children of the handle. However, polyline handles currently do not have any children .
visible: This field contains the visible property value for the entity . It should be "on" or "off" . By default, the polyline is visible, the value's property is "on" . If "off" the polyline is not drawn on the screen.
data: This field contains the values for the x and y coordinates. Component Z is to be added in the case of three-dimensional axes. It is a two (three) column matrix [x,y,[z]] of points.
closed: This field determines wether the polyline is closed or not: its value can be "on" or "off" (no default value, it depends on the primitive used to create the polyline).
line_mode: This field contains the default line_mode property value for the polyline. Its value should be "on" (line drawn) or "off" (no line drawn).
fill_mode: If the polyline_style field is different of 5, fill the background of the curve with color defined by the background property.
line_style: The line_style property value should be an integer in [1 6]. 1 stands for solid the other value stands for a selection of dashes (see getlinestyle ).
thickness: This field contains the line thickness property. It's value should be positive integer.
arrow_size_factor: This integer allows to set the size of arrows drawn on the polyline. The actual size of arrows is the product of the thickness and the the size factor.
polyline_style: This property sets several polyline drawing mode:
If the value is 0 or 1 lines are drawn between two consecutives points.
If the value is 2 the polyline produces a staircase plot. Two consecutives points are linked by an horizontal line followed by a vertical line.
If the value is 3 the polyline produces a bar plot. For each given point (x,y) a vertical line is drawn from (x,y) to (x,0).
If the value is 4 arrows are drawn between two consecutives points.
If the value is 5 the polyline is filled (patch).
If the value is 6 the polyline is a Matlab-like bar object. The properties bar_shift and bar_width command its appearance.
foreground: This field contains the default foreground property used to draw the polyline. Its value should be a color index (relative to the current colormap).
background: This field contains the color used to fill the background of the polyline. Its value should be a color index (relative to the current colormap).
interp_color_vector: This field contains the vector of color indices used to fill in the polyline when the interp_color_mode property is set to "on" . It defines the intervals of colormap indices used to fill each segment. For instance, the first segment will be filled by every colors whose index is between the first two elements of the vecor. It is only applicable if the polyline is defined by 3 or 4 points. Therefore, the size of the vector must match this dimension.
interp_color_mode: This field determines if we are using the interpolated shading mode to fill the polyline : its value can be "on" or "off" . Note that an interp_color_vector must be defined before switching to "on" value (see above).
mark_mode: This field contains the default mark_mode property value for the polyline. Its value should be "on" (marks drawn) or "off" (no marks drawn).
mark_style: The mark_style property value is used to select the type of mark to use when mark_mode property is "on" . The value should be an integer in [0 14] which stands for: dot, plus, cross, star, filled diamond, diamond, triangle up, triangle down, diamond plus, circle, asterisk, square, triangle right, triangle left and pentagram.
mark_size_unit: This field contains the default mark_size_unit property value. If mark_size_unit is set to "point" , then the mark_size value is directly given in points. When mark_size_unit is set to "tabulated" , mark_size is computed relative to the font size array: therefore, its value should be an integer in [0 5] which stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt. Note that plot2d and pure scilab functions use tabulated mode as default ; when using plot function, the point mode is automatically enabled.
mark_size: The mark_size property is used to select the type of size of the marks when mark_mode property is "on" . Its value should be an integer between 0 and 5 whith stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt.
mark_foreground: This field contains the mark_foreground property value which is the marks' edge color. Its value should be a color index (relative to the current color_map).
mark_background: This field contains the mark_background property value which is the marks' face color. Its value should be a color index (relative to the current color_map).
x_shift: This field contains the offset computed by a call to the bar function (or re-computed by a call to barhomogenize ) and is used to perform a nice vertical bar representation. Note that this offset is also taken into account for all the other polyline_style . The unit is expressed in user coordinates.
y_shift: This field contains the offset computed by a call to the bar function (or re-computed by a call to barhomogenize ) and is used to perform a nice horizontal bar representation. Note that this offset is also taken into account for all the other polyline_style . The unit is expressed in user coordinates.
z_shift: This field contains the offset the user may specify. Note that this offset is taken into account for all the polyline_style . The unit is expressed in user coordinates.
bar_width: This field determines the width of the selected polyline when its polyline_style is set to bar mode (case 6) : the unit is expressed in user coordinates.
clip_state: This field contains the clip_state property value for the polyline. It should be :
"off" this means that the polyline is not clipped.
"clipgrf" this means that the polyline is clipped outside the Axes box.
"on" this means that the polyline is clipped outside the rectangle given by property clip_box.
clip_box: This field is to determinate the clip_box property. By Default its value should be an empty matrix if clip_state is "off". Other cases the vector [x,y,w,h] (upper-left point width height) defines the portions of the polyline to display, however clip_state property value will be changed.
user_data: This field can be use to store any scilab variable in the polyline data structure, and to retrieve it.

Examples

   set("figure_style","new") //create a figure
   a=get("current_axes")//get the handle of the newly created axes
   a.data_bounds=[-2,-2;2,2];

   xpoly(sin(2*%pi*(0:5)/5),cos(2*%pi*(0:5)/5),"lines",0)
   p=get("hdl"); //get handle on current entity (here the polyline entity)
   p.foreground=2;
   p.thickness=3;
   p.mark_style=9;
   d=p.data;d(1,:)=[0 0];p.data=d;
   a.rotation_angles=[0 45];

   p.data=[(-2:0.1:2)' sin((-2:0.1:2)*%pi)']
   p.mark_mode="off";
   p.polyline_style=3;
   p.line_style=4;

See Also

set , get , delete , xpoly , xfpoly , xpolys , xfpolys , graphics_entities ,

Author

Djalel ABDEMOUCHE


printing

Scilab Function
Last update : 16/06/2004

printing - impression des graphiques Scilab

Calling Sequence

Blatexpr xscale yscale filename.ps
BEpsf filename.ps
Blpr "Title" filename1.ps filename2.ps ... filenamen.ps | lpr

Description

Les graphiques peuvent être sauvegardés avec la commande xbasimp . La commande :

      xbasimp(xx,'des.ps',0)

sauve les graphiques enregistrés dans la fenêtre xx dans le fichier des.ps.xx . Ce fichier ne peut pas être envoyé directement vers une imprimante Postscript mais un ensemble de programmes Scilab ( dans le répertoire bin de Scilab ) sont à utiliser pour cela :

BEpsf: La commande BEpsf crée un fichier epsf (PostScript encapsulé) à partir du fichier des.ps.xx sous le nom des.epsf , ce fichier epsf peut être imprimé directement ou inclus dans un fichier PostScript.
Blatexpr: La commande Blatexpr crée un fichier epsf à partir du fichier des.ps.xx des.ps.xx
      mv des.ps.xx des.ps
      Blatexpr 1.0 1.0 des.ps

sous le nom des.epsf et un fichier LaTeX des.tex . Le fichier des.tex peut être inséré dans un document LaTeX pour inclure le fichier epsf ( le fichier postscript est inclus avec la commande special de TeX )

      \input des.tex
      \dessin{caption}{label}
Blpr: La commande Blpr est utilisée pour imprimer un ensemble de graphiques sur une même feuille de papier. Par exemple pour imprimer deux graphiques sur une seule page :
    Blpr "Deux graphiques" file1.ps.0 file2.ps.1 | lpr
Blatexprs: La commande Blatexprs utilisée pour insérer dans une figure LaTeX un ensemble de graphiques Scilab
    Blatexprs res file1.ps.0 file2.ps.1

crée deux fichiers res.ps et res.tex . Le fichier res.tex est utilisé comme pour Blatexpr pour lire la figure.

See Also

xbasimp ,


rectangle_properties

Scilab Data type
Last update : 16/12/2005

rectangle_properties - description of the Rectangle entity properties

Description

The Rectangle entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for rectangles and filled rectangles.

parent: This field contains the handle of the parent. The parent of the rectancle entity should be of the type "Axes" or "Compound" .
children: This property contains a vector with the children of the handle. However, rectangle handles currently do not have any children .
mark_mode: This field contains the default mark_mode property value for the polyline. Its value should be "on" (marks drawn) or "off" (no marks drawn).
mark_style: The mark_style property value is used to select the type of mark to use when mark_mode property is "on" . The value should be an integer in [0 14] which stands for: dot, plus, cross, star, filled diamond, diamond, triangle up, triangle down, diamond plus, circle, asterisk, square, triangle right, triangle left and pentagram.
mark_size_unit: This field contains the default mark_size_unit property value. If mark_size_unit is set to "point" , then the mark_size value is directly given in points. When mark_size_unit is set to "tabulated" , mark_size is computed relative to the font size array: therefore, its value should be an integer in [0 5] whith stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt. Note that xrect and pure scilab functions use tabulated mode as default ; when using plot function, the point mode is automatically enabled.
mark_size: The mark_size property is used to select the type of size of the marks when mark_mode property is "on" . Its value should be an integer in [0 5] whith stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt.
mark_foreground: This field contains the mark_foreground property value which is the marks' edge color. Its value should be a color index (relative to the current color_map).
mark_background: This field contains the mark_background property value which is the marks' face color. Its value should be a color index (relative to the current color_map).
line_mode: This field contains the default line_mode property value for the rectangle. Its value should be "on" (line drawn) or "off" (no line drawn).
fill_mode: If fill_mode property value is "on" , the rectangle is filled with the foreground color, the mark_mode must also have the value "off" . if not and the value's property is "off" only the shape of the rectangle is drawn using the foreground color.
line_style: The line_style property value should be an integer in [1 6]. 1 stands for solid the other value stands for a selection of dashes.
thickness: This field contains the line thickness property. Its value should be a positif integer.
foreground: This field contains the color used to draw the outline of the rectangle. Its value should be a color index (relative to the current colormap).
background: This field contains the color used to fill the rectangle. Its value should be a color index (relative to the current colormap).
data: This property is to return the coordinates of the upper-left point of the rectangle and its width and height in the data units of the axes. The result is the matrix [xleft,yup,[zup],width,height]
visible: This field contains the visible property value for the entity . It should be "on" or "off" . By default, the rectangle is visible, the value's property is "on" . If "off" the rectangle is not drawn on the screen.
clip_state: This field contains the clip_state property value for the rectangle. It should be :
"off" this means that the rectangle is not clipped.
"clipgrf" this means that the rectangle is clipped outside the Axes box.
"on" this means that the rectangle is clipped outside the rectangle given by property clip_box.
clip_box: This field is to determinate the clip_box property. By Default its value should be an empty matrix if clip_state is "off". Other cases the vector [x,y,w,h] (upper-left point width height) defines the portions of the rectangle to display, however clip_state property value will be changed.
user_data: This field can be use to store any scilab variable in the rectangle data structure, and to retreive it.

Examples

   set("figure_style","new") //create a figure
   a=get("current_axes");//get the handle of the newly created axes
   a.data_bounds=[-2,-2;2,2];

   xrect(-1,1,2,2)

   r=get("hdl");//get handle on current entity (here the rectangle entity)
   r.type
   r.parent.type
   r.foreground=13;
   r.line_style=2;
   r.fill_mode="on";
   r.background=color('red');
   r.clip_box=[-1 1;1 1];
   r.data(:,[3 4])=[1/2 1/2];
   r.data(:,[1 2])=[1/2 1/2];
   r.clip_state="off"

See Also

set , get , delete , xrect , xfrect , xrects , graphics_entities ,

Author

Djalel ABDEMOUCHE


replot

Scilab Function
Last update : 08/06/2005

replot - redessine la fenêtre graphique courante en changeant les bornes

Calling Sequence

replot(rect)

Parameters

  • rect : vecteur ligne de taille 4.
  • handle : argument optionnel. Handle(s) graphiques de type Axes définissant le(s) axe(s) auxquels les nouvelles bornes s'appliquent. Option uniquement disponible en nouveau mode graphique.

Description

replot est utilisée pour redessiner la fenêtre graphique courante en changeant les bornes, données sous la forme rect=[xmin,ymin,xmax,ymax] . En ancien mode graphique, fonctionne uniquement avec le pilote "Rec" .

En nouveau mode graphique, cette transformation s'applique aux axes spécifiés par handle Si handle n'est pas renseigné, la transformation s'applique à l'axe courant de la figure courante. La transformation change les valeurs data_bounds des axes. A noter que la propriété tight_limits de l'axe doit être mise à "on" pour selectionner strictement ces bornes (voir axes_properties ).

Examples

backupstyle='?'
if (get('old_style')=='off') then
  set('old_style','on');
  backupstyle='off'
end

// under old graphics mode
x=[0:0.1:2*%pi]';
plot2d(x,sin(x))
replot([-1,-1,10,2])

// under new graphics mode
set old_style off
xdel(winsid());
plot() // plot demo
f=gcf();
replot([-1,-1,10,2],f.children(1)) // specify axes handle's value
replot([-3,-2,8,4],f.children(2))
if (backupstyle =='off') then set('old_style',backupstyle);end;

See Also

xbasr , xbasc , clf ,

Author

J.Ph.C.


rgb2name

Scilab Function
Last update : 07/07/2004

rgb2name - returns the name of a color

Calling Sequence

names=rgb2name(r,g,b)
names=rgb2name(rgb)

Parameters

  • r,g,b : RGB integer values of a color.
  • rgb : vector of RGB integer values of a color.
  • names : names of the color.

Description

rgb2name returns the color name corresponding to the RGB values given by its argument. A vector of color names can also be returned if the color has more than 1 name. r , g and b must be integers between 0 and 255 corresponding to colors components red, green and blue. As usual 0 means no intensity and 255 means all the intensity of the color. RGB values can also be given by a vector [r,g,b] .

If no color is found [] is returned.

The list of all known colors is given by color_list .

Examples

rgb2name(255,128,128)
rgb2name([255 215 0])
// get color #10 of the current colormap and find its name
cmap=get(gcf(),"color_map");
rgb2name(cmap(10,:)*255)

See Also

color , color_list , name2rgb ,


rotate

Scilab Function
Last update : 16/06/2004

rotate - rotation d'un ensemble de points dans le plan

Calling Sequence

xy1=rotate(xy,[theta,orig])

Parameters

  • xy : matrice de taille (2,n).
  • xy1 : matrice de taille (2,n).
  • theta : réel, angle en radian (0 par défaut).
  • orig : centre de la rotation ([0;0] par défaut)

Description

rotate effectue une rotation d'angle theta theta :

xy1(:,i) = M(theta) *xy (:,i) + yesg

où M représente la matrice de rotation correspondante.

Examples

xsetech([0,0,1,1],[-1,-1,1,1])
xy=[(0:0.1:10);sin(0:0.1:10)]/10;
for i=2*%pi*(0:10)/10,
  [xy1]=rotate(xy,i);
  xpoly(xy1(1,:),xy1(2,:),"lines")
end


rubberbox

Scilab Function
Last update : 12/01/2004

rubberbox - Rubberband box for rectangle selection

Calling Sequence

[final_rect,btn]=rubberbox(initial_rect)
[final_rect,btn]=rubberbox()

Parameters

  • initial_rect : vector with two or four entries. With four entries it gives the initial rectangle defined by [x_left, y_top, width, height], with two entries width and height are supposed to be 0. coordinates of the upper-left corner of
  • final_rect :a rectangle defined by [x_left, y_top, width, height]
  • btn :an integer, the number of the mouse button clicked

Description

rubberbox(initial_rect) tracks a rubberband box in the current graphic window, following the mouse. When a button is clicked rubberbox returns the final rectangles definition in final_Rect . If the argument initial_rect user has to click to fix the initial corner position.

Examples

xsetech(frect=[0,0,100,100])
[x,y]=xclick();r=rubberbox([x;y;30;10])
xrect(r)
r=rubberbox()

See Also

xrect , xrects , xclick , xgetmouse , dragrect ,


scaling

Scilab Function
Last update : 16/06/2004

scaling - transformation affine d'un ensemble de points

Calling Sequence

xy1=scaling(xy,factor,[orig])

Parameters

  • xy1 : matrice de taille (2,.).
  • xy : matrice de taille (2,.).
  • factor : réel, coefficient de la transformation linéaire
  • orig : vecteur de décalage; [0;0] par défaut.

Description

scaling applique une transformation affine sur les points définis par les coordonnées xy :

xy1(:,i) = factor * xy(:,i) + orig .


sca

Scilab Function
Last update : 06/12/2005

sca - set the current axes entity

Calling Sequence

a=sca(a)

Parameters

  • a : a handle, the handle on the Axes entity

Description

sca(a) is used to set the current Axes entity (see graphics_entities ) to the one pointed to by the handle a . The drawing functions generaly use the current axes entity.

Examples

clf()
a1=newaxes();
a1.axes_bounds=[0,0,1.0,0.5];
t=0:0.1:20;
plot(t,acosh(t),'r')
a2=newaxes();
a2.axes_bounds=[0,0.5,1.0,0.5];
x=0:0.1:4;
plot(x,sinh(x))

sca(a1); //make first axes current
plot(t,asinh(t),'g')
legend(['acosh','asinh'])
sca(a2); //make secoçnd axes current
legend('sinh')

See Also

subplot , gda , newaxes ,

Author

S. Steer, INRIA


scf

Scilab Function
Last update : 08/06/2005

scf - set the current graphic figure (window)

Calling Sequence

f = scf()
f = scf(h)
f = scf(num)

Parameters

  • h : a handle, the figure handle
  • num : a number, the figure_id
  • f : the handle of the current figure

Description

The current figure is the destination of the graphic drawing. The scf function allows to change this current figure or to create it if it does not already exist.

scf(num) set the figure with figure_id==num as the current figure. If it does not already exist it is created.

scf(h) set the figure pointed to by the handle h as the current figure. If it does not already exist it is created.

scf() is equivalent to scf(max(winsid())+1) . It may be used to create a new graphic window.

Examples

   f4=scf(4); //creates figure with id==4 and make it the current one
   f0=scf(0); //creates figure with id==0 and make it the current one
   plot2d() //draw in current figure (id=0)
   scf(f4); // set first created figure as current one
   plot3d() //draw in current figure (id=4)

See Also

set , get , gcf , clf , graphics_entities ,

Author

S. Steer INRIA


sd2sci

Scilab Function
Last update : 16/06/2004

sd2sci - conversion des sorties de gr_menu vers des instructions Scilab

Calling Sequence

txt=sd2sci(sd [,sz [,orig]])

Parameters

  • sd : structure de données renvoyée par gr_menu.
  • sz : vecteur de nombres ou chaînes de caractères avec deux composantes, donnant les facteurs de zoom en x et y.
  • orig : vecteur de nombres ou chaînes de caractères avec deux composantes, donnant un vecteur de translation de l'origine

Description

Etant donné une liste sd générée par gr_menu sd2sci fabrique un vecteur d'instructions Scilab correspondant au graphique contenu dans sd.

Les paramètres optionnels sz et orig permettent de changer l'échelle ou de décaler le graphique initial.

Si sz ou orig sont donnés sous forme de chaînes de caractères, les instructions générées les utilisent de façon formelle.

See Also

gr_menu , execstr ,

Author

Serge Steer INRIA 1988


sda

Scilab Function
Last update : 15/01/2004

sda - Set default axes.

Calling Sequence

sda()
a = gda(); set(a,"default_values",1)

Parameters

  • a : handle, the handle of the default axes.

Description

This routine resets the axes' model to default values.

Examples

  x=[0:0.1:2*%pi]';
  set old_style off
  f=get("default_figure"); // get the handle of the model figure
  a=get("default_axes"); // get the handle of the model axes
    // setting its' properties
  f.figure_size=[1200 900];
  f.figure_position=[0 0];
  a.background=4;
  a.box="off";
  a. tics_color=5;
  a.labels_font_color=25;
  a.labels_font_size=4;
  a.sub_tics=[7 3];
  a.x_location="middle";
  a.y_location="middle";
  a.tight_limits="on";
  a.thickness=2;
  a.grid=[-1 24];
  subplot(221);
  plot2d(x-2,sin(x))
  subplot(222);
  plot2d(x-6,[2*cos(x)+.7 2*cos(x)+.9 cos(2*x) .2+sin(3*x)],[-1,-2,-3 -4])
  sda() // return to the  default values of the axes' model
  subplot(223);
  plot2d(x-2,sin(x))
  subplot(224);
  plot2d(x-6,[2*cos(x)+.7 2*cos(x)+.9 cos(2*x) .2+sin(3*x)],[-1,-2,-3 -4])
  xdel(0)
  plot2d(x-2,sin(x))

See Also

sdf , gda , gdf , set , graphics_entities ,

Author

Djalel ABDEMOUCHE


sdf

Scilab Function
Last update : 15/01/2004

sdf - Set default figure.

Calling Sequence

sdf()
f = gdf(); set(f,"default_values",1)

Parameters

  • f : handle, the handle of the default figure.

Description

This routine resets the figure's model to default values.

Examples

   x=[0:0.1:2*%pi]';
   set old_style off
   f=get("default_figure"); // get the handle of the model figure
   a=get("default_axes"); // get the handle of the model axes
     // setting its' properties
   f.background=4;
   f.auto_resize="off";
   f.figure_size=[400 300];
   f.axes_size=[600 400];
   f.figure_position=[0 -1];
   a.x_location="top";
   a.y_location="left";
   for (i=1:6)
     xset("window",i) // create a figure with the identifier i
     plot2d(x,[sin(x) cos(x)],[i -i])
     xclick();
     if i == 4, sdf(); end // return to the  default values of the figure's model
    end

See Also

sda , gdf , gda , set , graphics_entities ,

Author

Djalel ABDEMOUCHE


secto3d

Scilab Function
Last update : 16/06/2004

secto3d - conversion de surfaces 3D

Calling Sequence

[m[,x]]=secto3d(seclist,npas)
[m]=secto3d(seclist ,x)

Parameters

  • seclist : une liste dont les éléments sont des matrices (2,.)
  • npas : un entier
  • m : une matrice
  • x : un vecteur

Description

Considérant une surface donnée sous forme d'une liste seclist de sections dans le plan (x,z) la commande [m [,x]]=secto3d(seclist [,npas]) renvoie une matrice m contenant une discrétisation régulière de la surface.

-La i-ème ligne de la matrice m correspond à la ième section
-La j-ième colonne de m correspond aux x(j)

Chaque section seclist(i) est décrite par une matrice (2,.) donnant respectivement les coordonnées x et z des points.

[m]=secto3d(seclist ,x) : dans ce cas le vecteur x donne la discrétisation de l'axe des x pour toutes les sections

See Also

plot3d ,

Author

Steer S.; ;


segs_properties

Scilab Data type
Last update : 17/10/2006

segs_properties - description of the Segments entity properties

Description

The Segs entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for a set of colored segments or colored arrows.

parent: This property contains the handle of the parent. The parent of the segment entity should be of the type "Axes" or "Compound" .
children: This property contains a vector with the children of the handle. However, segs handles currently do not have any children .
visible: This field contains the visible property value for the entity . It should be "on" or "off" . By default, the segments are visibles, the value's property is "on" . If "off" the segments are not drawn on the screen.
data: This field is two column matrix [x,y,[z]] which gives the coordinates of the segments boundary. If xv=matrix(x,2,-1) and yv=matrix(y,2,-1) then xv(:,k) and yv(:,k) are the boundary coordinates of the segment numbered k .
line_mode: This field contains the default line_mode property value for the segs. Its value should be "on" (line drawn) or "off" (no line drawn).
line_style: The line_style property value should be an integer in [0 6]. 0 stands for solid the other value stands for a selection of dashes. This property applies to all segments.
thickness: This field contains the thickness property for all segments. Its value should be a non negative integer..
arrow_size: Factor that specify the size of a arrowheads. With a negative value, the size is also dependent of the arrows length. TO draw segment, the value must be set to 0.
segs_color: This field contains the vector of colors to use to draw each segment. Each element is a color index relative to the current colormap.
mark_mode: This field contains the default mark_mode property value for the polyline. Its value should be "on" (marks drawn) or "off" (no marks drawn).
mark_style: The mark_style property value is used to select the type of mark to use when mark_mode property is "on" . The value should be an integer in [0 14] which stands for: dot, plus, cross, star, filled diamond, diamond, triangle up, triangle down, diamond plus, circle, asterisk, square, triangle right, triangle left and pentagram.
mark_size_unit: This field contains the default mark_size_unit property value. If mark_size_unit is set to "point" , then the mark_size value is directly given in points. When mark_size_unit is set to "tabulated" , mark_size is computed relative to the font size array: therefore, its value should be an integer in [0 5] which stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt. Note that plot2d and pure scilab functions use tabulated mode as default ; when using plot function, the point mode is automatically enabled.
mark_size: The mark_size property is used to select the type of size of the marks when mark_mode property is "on" . Its value should be an integer between 0 and 5 whith stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt.
mark_foreground: This field contains the mark_foreground property value which is the marks' edge color. Its value should be a color index (relative to the current color_map).
mark_background: This field contains the mark_background property value which is the marks' face color. Its value should be a color index (relative to the current color_map).
clip_state: This field contains the clip_state property value for the segments. It should be :
"off" this means that the segments is not clipped.
"clipgrf" this means that the segments is clipped outside the Axes box.
"on" this means that the segments is clipped outside the rectangle given by the property clip_box .
clip_box: This field contains the clip_box property. By default segment are not clipped, clip_state is "off", so the value should be an empty matrix .Other cases the vector [x,y,w,h] (upper-left point width height) defines the portions of the segments to display, however clip_state property value will be changed.
user_data: This field can be use to store any scilab variable in the segs data structure, and to retreive it.

Examples

  set("figure_style","new") //create a figure
   a=get("current_axes");//get the handle of the newly created axes
   a.data_bounds=[-10,-10;10,10];
   x=2*%pi*(0:7)/8;
   xv=[2*sin(x);9*sin(x)];
   yv=[2*cos(x);9*cos(x)];
   xsegs(xv,yv,1:8)

   s=a.children
   s.arrow_size=1;
    s.segs_color=15:22;
    for j=1:2
      for i=1:8
        h=s.data(i*2,j);
        s.data(i*2,j)=s.data(i*2-1,j);
        s.data(i*2-1,j)=  h;
       end
    end

   s.segs_color=5; //set all the colors to 5

   s.clip_box=[-4,4,8,8];
   a.thickness=4;
   xrect(s.clip_box);

See Also

set , get , delete , xsegs , graphics_entities ,

Author

Djalel ABDMOUCHE


set_posfig_dim

Scilab Function
Last update : 08/06/2005

set_posfig_dim - change defaut transformation for exporting in postscript

Calling Sequence

set_posfig_dim(w,h)
set_posfig_dim(0,0)

Parameters

  • w : graphic figure width, number of pixels
  • h : graphic figure height, number of pixels

Description

set_posfig_dim(w,h) set the coordinates transformation to be used when exporting a graphic window in postscript. The graphic figure zoomed with ratios w/<graphic figure width> horizontally and h/<graphic figure height> vertically.

This function is particularily useful when one wants an export a graphic figure exactly as it is shown on the screen. For that w and h has to be set respectively to <graphic figure width> and <graphic figure height>

set_posfig_dim(0,0) resets the default values: w=600 , h=424 .

Examples

    // make a figure with a specific shape
    f=scf(0);f.figure_size=[800,300];
    plot2d()
    set_posfig_dim(f.figure_size(1),f.figure_size(2))
    filename='foo'; // ! no extension
    xs2ps(0,filename)
    //add the Postscript file header and create <filename>.eps file
    if MSDOS then
      unix_s(pathconvert('""'+WSCI+'/bin/BEpsf'+'""',%f)+' -p ' +filename)
    else
      unix_s(pathconvert('SCI/bin/BEpsf',%f)+' -p ' +filename)
    end

See Also

xs2ps ,

Author

Serge Steer INRIA


set

Scilab Function
Last update : 08/06/2005

set - set a property value of a graphic entity object or of a User Interface object.

Calling Sequence

set(prop,val)
set(h,prop,val)
h.prop=val
set(n,prop,val)

Parameters

  • h : a handle, the handle of the entity which to set the named property, h can be a vector of handles, in which case set sets the property's value for all objects identified by h(i).
  • n n : an integer, the handle of User Interface object which to set the named property.
  • prop : character string name of the property to set.
  • val

    : value to give to the property (see graphics_entities ).

Description

This routine can be used to set a graphics entity specified property. This graphics entity is identified by its handle h .If the handle is not specified, the current object is taken as the default handle. The type of the value to set property depends on the type of the graphics entity.

See graphics_entities for details about properties' names and values for graphics entities.

See uicontrol for details about properties' names and values for User Interface objects.

For graphics entities handle it is possible to use equivalently a dot notation like h.background instead of set .

Examples

   clf()
   set("figure_style","new") //create a figure
   set("auto_clear","off") ;
   // Exemple of a Plot 2D
   x=[-.2:0.1:2*%pi]';
   plot2d(x-.3,[sin(x-1) cos(2*x)],[1 2] );
   a=get("current_axes");
   p1=a.children.children(1);
   p2=a.children.children(2);
   // set the named properties to the specified values on the objects
   set(p2,"foreground",13);
   set(p2,"polyline_style",2);
   set(a,'tight_limits',"on");
   set(a,"box","off");
   set(a,"sub_tics",[ 7 0 ]);
   set(a,"y_location","middle")
   set(p2,'thickness',2);
   set(p1,'mark_mode',"on");
   set(p1,'mark_style',3);
   plot2d(x-2,x.^2/20);
   p3= a.children(1).children;
   set([a p1 p2 p3],"foreground",5)

See Also

get , delete , copy , move , graphics_entities , uicontrol ,

Author

Djalel ABDEMOUCHE


sgrid

Scilab Function
Last update : 12/01/2004

sgrid - s-plane grid lines.

Calling Sequence

sgrid()
sgrid('new')
sgrid(zeta,wn [,color])

Description

Used in conjonction with evans, plots lines of constant damping ratio ( zeta ) and natural frequency ( wn ).

sgrid(): add a grid over an existing continuous s-plane root with default values for zeta and wn .
sgrid('new'): clears the graphic screen and then plots a default s-plane grid
sgrid(zeta,wn [,color]): same as sgrid() but uses the provided damping ratio and natural frequency.

Examples

H=syslin('c',352*poly(-5,'s')/poly([0,0,2000,200,25,1],'s','c'));
evans(H,100)
sgrid()
sgrid(0.6,2,7)

See Also

evans ,


show_pixmap

Scilab Function
Last update : 08/06/2005

show_pixmap - send the pixmap buffer to the screen

Calling Sequence

show_pixmap()

Description

If a graphic window pixmap property is "on" the drawings are send to a pixmap memory instead of the screen display.The show_pixmap() instruction send the pixmap to the screen.The pixmap mode can be used to obtain smooth animations. This property can be found among the figure entity fields (see figure_properties ).

Examples

   set figure_style new
   f=gcf();f.pixmap='on'; //set the pixmap mode
   a=gca();a.data_bounds=[0 0; 10 10];
   //construct two rectangles
   xrects([0;10;1;1],5);r1=gce();r1=r1.children;
   xrects([0;1;1;1],13);r2=gce();r2=r2.children;
   //animation loop
   for k=1:1000
      //draw the rectangles in the pixmap buffer
      move(r1,[0.01,-0.01]);move(r2,[0.01,0.01])
      //show the pixmap buffer
      show_pixmap()
   end

See Also

figure_properties , clear_pixmap ,

Author

Serge Steer INRIA


square

Scilab Function
Last update : 16/06/2004

square - échelle isométrique 2D (change la taille de la fenêtre)

Calling Sequence

square(xmin,ymin,xmax,ymax)

Parameters

  • xmin,xmax,ymin,ymax : 4 valeurs réelles

Description

square est utilisée pour avoir une échelle identique sur les axes x et y. Les valeurs xmin, xmax, ymin, ymax sont les bornes du dessin et square change les dimensions de la fenêtre graphique pour que les échelles soient identiques. square change l'échelle graphique courante et peut être utilisée en conjonction avec les routines graphiques nécessitant que l'échelle soit définie au préalable (mode fstrf="x0z" dans plot2d ).

Examples

t=[0:0.1:2*%pi]';
plot2d(sin(t),cos(t))
xbasc()
square(-1,-1,1,1)
plot2d(sin(t),cos(t))
xset("default")

See Also

isoview , xsetech ,

Author

Steer S.


stringbox

Scilab Function
Last update : 13/12/2005

stringbox - Calcule le rectangle englobant d'un texte ou d'un label.

Calling Sequence

rect = stringbox( string, x, y, [angle, [fontStyle, [fontSize]]] )
rect = stringbox( handle )

Parameters

  • rect : matrice 2x4 contenant les coordonées des 4 sommets du rectangle englobant.
  • string : matrice de chaine de caractère à entourer.
  • x,y : scalaires réels, coordonnées du point en bas à gauche des chaînes de caractères.
  • angle : Angle de rotation de la chaîne en degrés autour du point (x,y) dans le sens des aiguilles d'une montre.
  • fonStyle : un entier specifiant le type de la fonte.
  • fontSize : un entier specifiant la taille de la fonte.
  • handle : un handle de type Text ou Label.

Description

stringbox renvoie les positions des quatres sommets du rectangle englobant d'un objet Text ou Label ou d'une chaine de caractère que l'on souhaite afficher. Les coordonnées sont données dans l'échelle graphique courante. Le premier sommet correspond à la coordonnées du texte, le point en bas à gauche sans rotations, les suivants sont donnés dans le sens des aiguilles d'une montre.

Le résultat est approximatif avec le pilote PostScript.

Examples

// show axes
axes = gca() ;
axes.axes_visible = 'on' ;
axes.data_bounds = [ 1, 1 ; 10, 10 ] ;

// display a labels for axes
xtitle( 'stringbox', 'X', 'Y' )  ;

// get the bounding box of X label
stringbox( axes.x_label )

// draw a string
str = [ "Scilab", "is" , "not", "Skylab" ] ;
xstring( 4, 9, str ) ;

//modify the text
e = gce() ;
e.font_angle = 90 ;
e.font_size    = 6  ;
e.font_style   = 7 ;
e.box = 'on' ;

// get its bounding box
stringbox( e )
// or
rect = stringbox( str, 4, 9, 90, 6, 5 )

// click and find if the text was hit
hit = xclick()  ;
hit = hit( 2 : 3 ) ;

if hit(1) >= rect(1,1)  & hit(1) <=  rect(1,2) & hit(2) <= rect(2,2) & hit(2) >= rect(2,3) then
  disp('You hit the text.') ;
else
  disp('You missed it.')
end;

See Also

xstring , xstringl , xstringb ,

Author

Jean-Baptiste Silvy


subplot

Scilab Function
Last update : 03/10/2005

subplot - divise une fenêtre graphique en sous-fenêtres

Calling Sequence

subplot(m,n,p)
subplot(mnp)

Parameters

  • m,n,p : entiers positifs
  • mnp : un entier avec mnp comme notation décimale

Description

subplot(m,n,p) ou subplot(mnp) divise la fenêtre graphique courante en une matrice m x n matrice de sous fenêtres et sélectionne la p-ième sous-fenêtre comme emplacement de dessin par défaut. Le numéro de la sous-fenêtre est compté ligne par ligne, c'est à dire que l'emplacement (i,j) de la matrice porte le numéro (i-1)*n + j.

Examples

subplot(221)
plot2d()
subplot(222)
plot3d()
subplot(2,2,3)
param3d()
subplot(2,2,4)
hist3d()

See Also

plot2d , plot3d , xstring , xtitle ,


surface_properties

Scilab Data type
Last update : 09/12/2005

surface_properties - description of the 3D entities properties

Description

The Surface entity is a leaf of the graphics entities hierarchy. Two classes appears under this type of entity : Plot3d and Fac3d according to the ploting function or the way data is entered. Fac3d and Plo3d entities are similar but Fac3d is more complete and accept more options than Plot3d . To always have Fac3d entities, simply use genfac3d to pre-build matrices before using plot3d or use the surf command.

Here are the properties contained in a surface entity:

parent: This property contains the handle of the parent. The parent of the surface entity should be of type "Axes" or "Compound" .
children: This property contains a vector with the children of the handle. However, surface handles currently do not have any children .
visible: This field contains the visible property value for the entity . It should be "on" or "off" . By default, surfaces are visibles, the value's property is "on" . If "off" the 3D graphics are not displayed on the screen.
surface_mode: This field contains the default surface_mode property value for the surface. Its value should be "on" (surface drawn) or "off" (no surface drawn).
foreground: If color_mode >= 0 , this field contains the color index used to draw the edges. If not, foreground is not used at all. The foreground value should be an integer color index (relative to the current colormap).
thickness: This field contains the default thickness value of the lines used to draw the facets contours. It should be a positive integer.
mark_mode: This field contains the default mark_mode property value for the surface. Its value should be "on" (marks drawn) or "off" (no marks drawn).
mark_style: The mark_style property value is used to select the type of mark to use when mark_mode property is "on" . The value should be an integer in [0 14] which stands for: dot, plus, cross, star, filled diamond, diamond, triangle up, triangle down, diamond plus, circle, asterisk, square, triangle right, triangle left and pentagram.
mark_size_unit: This field contains the default mark_size_unit property value. If mark_size_unit is set to "point" , then the mark_size value is directly given in points. When mark_size_unit is set to "tabulated" , mark_size is computed relative to the font size array: therefore, its value should be an integer in [0 5] whith stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt. Note that plot3d and pure scilab functions use tabulated mode as default ; when using the surf (or plot for 2D lines) function, the point mode is automatically enabled.
mark_size: The mark_size property is used to select the type of size of the marks when mark_mode property is "on" . Its value should be an integer between 0 and 5 whith stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt.
mark_foreground: This field contains the mark_foreground property value which is the marks' edge color. Its value should be a color index (relative to the current color_map).
mark_background: This field contains the mark_background property value which is the marks' face color. Its value should be a color index (relative to the current color_map).
data: This field defines a tlist data structure of type "3d" composed of a row and column indices of each element as the x-, y- and z-coordinates contained respectivly in data.x , data.y and data.z . The complementary field named data.color is available in case a real color vector or matrix is specified. If none, data.color is not listed. The surface is painted according to color_mode and color_flag properties.
color_mode: an integer between [-size(colormap) ; size(colormap)] defining the color of the facet when color_flag value is 0 . As stated before, if color_mode > 0 , edges are drawn using foreground color. If color_mode is set to 0 , a mesh of the surface is drawn: front faces have no colors. Finally, when color_mode < 0 , front faces are painted with color -color_mode but no edges are displayed.
color_flag: This field is used to specify the algorithm used to set facets' colors.Not that the rules on color_mode , foreground and hiddencolor are still applied to this case.

color_flag == 0

All facets are painted using the color index and method defined by color_mode (see above).

color_flag == 1

All facets are painted using one color index per facet proportional to z . The minimum z value is painted using the index 1 color while the maximum z value is painted using highest color index. The edges of the facets can be additionnaly drawn depending on the value of color_mode (see above).

The 3 remaining cases ( color_flag == 2,3 or 4 ) are only available only with Fac3d entity. Then, the data.color value is used to set colors for facets (indices in the current colormap) if it exists. If not, the current color_mode is used to paint the facets.

color_flag == 2 ('flat' shading)

All facets are painted using the color index given in the data.color property (one color per facet is needed). Two cases are then possible :

data.color contains a color vector : if color(i) is positive it gives the color of facet i and the boundary of the facet is drawn with current line style and color. If color(i) is negative, color id -color(i) is used and the boundary of the facet is not drawn.

data.color contains a color matrix of size (nf,n) where n stands for the number of facets and nf for the number of points defining the polygonal facet. For the nf vertices defining each facet, the algorithm computes an average value of the color index (from the matrix color index) : the nf vertices of the same facet will have the same color index value.

color_flag == 3 ('interpolated' shading)

Facets painting results of interpolation of vertices colors. The indices of vertices color are given in the data.color property (one color per vertex is needed). Two cases are possible :

data.color contains a colors vector : then, there are too few data to complete the interpolated shading mode. Indeed, a color matrix of size (nf,n) (where n stands for the number of facets and nf for the number of points defining the polygonal facet) is needed to perform this operation. For each facet, the algorithm copies the single color index value of the facet into the nf color indexes vertices defining the facet's boundary.

data.color contains a color matrix of size (nf,n) (see upper for nf and n definitions), the interpolated shading mode can be completed normally using those color indexes.

color_flag == 4 (Matlab-like 'flat' shading)

Same as color_flag==2 with a slight difference when data.color is a matrix. All facets are painted using the color index given in the data.color property (one color per facet is needed). Two cases are then possible :

data.color contains a color vector : if color(i) is positive it gives the color of facet i and the boundary of the facet is drawn with current line style and color. If color(i) is negative, color id -color(i) is used and the boundary of the facet is not drawn.

data.color contains a color matrix of size (nf,n) where n stands for the number of facets and nf for the number of points defining the polygonal facet. For the nf vertices defining each facet, the algorithm takes the color of the first vertex defining the patch (facet).

cdata_mapping: Specific to Fac3d handles . A string with value 'scaled' or 'direct' . If a data.color is set, each index color data specifies a single value for each vertex. cdata_mapping determines wether those indices are scaled to map linearly into the current colormap ( 'scaled' mode) or point directly into this colormap ( 'direct ' mode). This property is usefull when color_flag equals 2 , 3 or 4 .
hiddencolor: This field contains the color index used to draw the backward faces of a surface. Its value should be a positive integer (color index relative to the current colormap). If it is a negative integer,the same color than the "visible" face is applied to the rear face.
user_data: This field can be use to store any scilab variable in the surface data structure, and to retreive it.

Examples

set("figure_style","new")
//create a figure
t=[0:0.3:2*%pi]'; z=sin(t)*cos(t');
[xx,yy,zz]=genfac3d(t,t,z);
plot3d([xx xx],[yy yy],list([zz zz+4],[4*ones(1,400) 5*ones(1,400)]))
h=get("hdl") //get handle on current entity (here the surface)
a=gca(); //get current axes
a.rotation_angles=[40,70];
a.grid=[1 1 1];
//make grids
a.data_bounds=[-6,0,-1;6,6,5];
a.axes_visible="off";
//axes are hidden a.axes_bounds=[.2 0 1 1];
f=get("current_figure");
//get the handle of the parent figure
f.color_map=hotcolormap(64);
//change the figure colormap
h.color_flag=1;
//color according to z
h.color_mode=-2;
//remove the facets boundary
h.color_flag=2;
//color according to given colors
h.data.color=[1+modulo(1:400,64),1+modulo(1:400,64)];
//shaded
h.color_flag=3;

scf(2); // creates second window and use surf command
subplot(211)
surf(z,'cdata_mapping','direct','facecol','interp')

subplot(212)
surf(t,t,z,'edgeco','b','marker','d','markersiz',9,'markeredg','red','markerfac','k')
e=gce();
e.color_flag=1 // color index proportional to altitude (z coord.)
e.color_flag=2; // back to default mode
e.color_flag= 3; // interpolated shading mode (based on blue default color because field data.color is not filled)

See Also

set , get , delete , plot3d , plot3d1 , plot3d2 , surf , graphics_entities ,

Author

Djalel ABDEMOUCHE & F.Leray


surf

Scilab Function
Last update : 08/06/2005

surf - 3D surface plot

Calling Sequence

surf(Z,<GlobalProperty>)
surf(Z,color,<GlobalProperty>)
surf(X,Y,Z,<color>,<GlobalProperty>)
surf(<axes_handle>,...)

Parameters

  • Z : a real matrix defining the surface height. It can not be omitted. The Z data is a m x n matrix.
  • X,Y : two real matrices or vectors: always set together, these data defines a new standard grid. This new X and Y components of the grid must match Z dimensions (see description below).
  • color : an optional real matrix defining a color value for each (X(j),Y(i)) point of the grid (see description below).
  • <GlobalProperty> : This optional argument represents a sequence of couple statements {PropertyName,PropertyValue} that defines global objects' properties applied to all the curves created by this plot. For a complete view of the available properties (see GlobalProperty ).
  • <axes_handle> : This optional argument forces the plot to appear inside the selected axes given by axes_handle rather than the current axes (see gca ).

Description

surf draws a colored parametric surface using a rectangular grid defined by X and Y coordinates (if {X,Y} are not specified, this grid is determined using the dimensions of the Z matrix) ; at each point of this grid, a Z coordinate is given using the Z matrix (only obligatory data). surf has been created to better handle Matlab syntax. To improve graphical compatibility, Matlab users should use surf (rather than plot3d ).

Data entry specification :

In this paragraph and to be more clear, we won't mention GlobalProperty optional arguments as they do not interfer with entry data (except for "Xdata" , "Ydata" and "Zdata" property, see GlobalProperty ). It is assumed that all those optional arguments could be present too.

If Z is the only matrix specified, surf(Z) plots the matrix Z versus the grid defined by 1:size(Z,2) along the x axis and 1:size(Z,1) along the y axis.

If a {X,Y,Z} triplet is given, Z must be a matrix with size( Z )= [ m x n ], X or Y can be :

a) a vector : if X is a vector, length( X )= n . Respectively, if Y is a vector, length( Y )= m .

b) a matrix : in this case, size( X ) (or size( Y )) must equal size( Z ).

Color entry specification :

As stated before, the surface is created over a rectangular grid support. Let consider two independant variables i and j such as :

This imaginary rectangular grid is used to build the real surface support onto the XY plane. Indeed, X , Y and Z data have the same size (even if X or Y is vector, see below) and can be considered as 3 functions x(i,j) , y(i,j) and z(i,j) specifying the desired surface. If X or Y are vectors, they are internally treated to produce good matrices matching the Z matrix dimension (and the grid is forcibly a rectangular region).

Considering the 3 functions x(i,j) , y(i,j) and z(i,j) , the portion of surface defining between two consecutive i and j is called a patch.

By default, when no color matrix is added to a surf call, the color parameter is linked to the Z data. When a color matrix is given, it can be applied to the patch in two different ways : at the vertices or at the center of each patch.

That is why, if Z is a [ m x n ] matrix, the C color matrix dimension can be [ m x n ] (one color defined per vertex) or [ m-1 x n-1 ] (one color per patch).

Color representation also varies when specifying some GlobalPropery:

The FaceColor property sets the shading mode : it can be 'interp' or 'flat' (default mode). When 'interp' is selected, we perform a bilinear color interpolation onto the patch. If size( C ) equals size( Z )-1 (i.e. we provided only one color per patch) then the color of the vertices defining the patch is set to the given color of the patch.

When 'flat' (default mode) is enabled we use a color faceted representation (one color per patch). If size( C ) equals size( Z ) (i.e. we provided only one color per vertices), the last row and column of C are ignored.

The GlobalProperty arguments sould be used to customize the surface. Here is a brief description on how it works:

GlobalProperty: This option may be used to specify how all the surfaces are drawn. It must always be a couple statement constituted of a string defining the PropertyName , and its associated value PropertyValue (which can be a string or an integer or... as well depending on the type of the PropertyName ). Note that you can set multiple properties : the face & edge color, color data, color data mapping, marker color (foreground and background), the visibility, clipping and thickness of the edges of the surface... (see GlobalProperty )

Note that all these properties can be (re-)set throught the surface entity properties (see surface_properties ).

Remarks

By default, successive surface plots are superposed. To clear the previous plot, use clf() . To enable auto_clear mode as the default mode, edit your default axes doing:

da=gda();

da.auto_clear = 'on'

Enter the command surf to see a demo.

Examples

// Z initialisation

Z= [   0.0001    0.0013    0.0053   -0.0299   -0.1809   -0.2465   -0.1100   -0.0168   -0.0008   -0.0000
    0.0005    0.0089    0.0259   -0.3673   -1.8670   -2.4736   -1.0866   -0.1602   -0.0067    0.0000
    0.0004    0.0214    0.1739   -0.3147   -4.0919   -6.4101   -2.7589   -0.2779    0.0131    0.0020
   -0.0088   -0.0871    0.0364    1.8559    1.4995   -2.2171   -0.2729    0.8368    0.2016    0.0130
   -0.0308   -0.4313   -1.7334   -0.1148    3.0731    0.4444    2.6145    2.4410    0.4877    0.0301
   -0.0336   -0.4990   -2.3552   -2.1722    0.8856   -0.0531    2.6416    2.4064    0.4771    0.0294
   -0.0137   -0.1967   -0.8083    0.2289    3.3983    3.1955    2.4338    1.2129    0.2108    0.0125
   -0.0014   -0.0017    0.3189    2.7414    7.1622    7.1361    3.1242    0.6633    0.0674    0.0030
    0.0002    0.0104    0.1733    1.0852    2.6741    2.6725    1.1119    0.1973    0.0152    0.0005
    0.0000    0.0012    0.0183    0.1099    0.2684    0.2683    0.1107    0.0190    0.0014    0.0000];

//simple surface
surf(Z); // Note that X and Y are determined by Z dimensions

//same surface with red face color and blue edges
scf(2); // new figure number 2
surf(Z,'facecol','red','edgecol','blu")

// X and Y initialisation
// NB: here, X has the same lines and Y the same columns
X = [ -3.0000   -2.3333   -1.6667   -1.0000   -0.3333    0.3333    1.0000    1.6667    2.3333    3.0000
   -3.0000   -2.3333   -1.6667   -1.0000   -0.3333    0.3333    1.0000    1.6667    2.3333    3.0000
   -3.0000   -2.3333   -1.6667   -1.0000   -0.3333    0.3333    1.0000    1.6667    2.3333    3.0000
   -3.0000   -2.3333   -1.6667   -1.0000   -0.3333    0.3333    1.0000    1.6667    2.3333    3.0000
   -3.0000   -2.3333   -1.6667   -1.0000   -0.3333    0.3333    1.0000    1.6667    2.3333    3.0000
   -3.0000   -2.3333   -1.6667   -1.0000   -0.3333    0.3333    1.0000    1.6667    2.3333    3.0000
   -3.0000   -2.3333   -1.6667   -1.0000   -0.3333    0.3333    1.0000    1.6667    2.3333    3.0000
   -3.0000   -2.3333   -1.6667   -1.0000   -0.3333    0.3333    1.0000    1.6667    2.3333    3.0000
   -3.0000   -2.3333   -1.6667   -1.0000   -0.3333    0.3333    1.0000    1.6667    2.3333    3.0000
   -3.0000   -2.3333   -1.6667   -1.0000   -0.3333    0.3333    1.0000    1.6667    2.3333    3.0000];

Y= [   -3.0000   -3.0000   -3.0000   -3.0000   -3.0000   -3.0000   -3.0000   -3.0000   -3.0000   -3.0000
   -2.3333   -2.3333   -2.3333   -2.3333   -2.3333   -2.3333   -2.3333   -2.3333   -2.3333   -2.3333
   -1.6667   -1.6667   -1.6667   -1.6667   -1.6667   -1.6667   -1.6667   -1.6667   -1.6667   -1.6667
   -1.0000   -1.0000   -1.0000   -1.0000   -1.0000   -1.0000   -1.0000   -1.0000   -1.0000   -1.0000
   -0.3333   -0.3333   -0.3333   -0.3333   -0.3333   -0.3333   -0.3333   -0.3333   -0.3333   -0.3333
    0.3333    0.3333    0.3333    0.3333    0.3333    0.3333    0.3333    0.3333    0.3333    0.3333
    1.0000    1.0000    1.0000    1.0000    1.0000    1.0000    1.0000    1.0000    1.0000    1.0000
    1.6667    1.6667    1.6667    1.6667    1.6667    1.6667    1.6667    1.6667    1.6667    1.6667
    2.3333    2.3333    2.3333    2.3333    2.3333    2.3333    2.3333    2.3333    2.3333    2.3333
    3.0000    3.0000    3.0000    3.0000    3.0000    3.0000    3.0000    3.0000    3.0000    3.0000];

// example 1
scf(3)
surf(X,Y,Z)

//example 2
// As you can see, the grid is not necessary rectangular
scf(4)
X(1,4) = -1.5;
Y(1,4) = -3.5;
Z(1,4) = -2;
surf(X,Y,Z)

// example 3
// X and Y are vectors => same behavior as sample 1
// With vectors, the grid is inevitably rectangular
scf(5)// new figure number 5
X=[ -3.0000   -2.3333   -1.6667   -1.0000   -0.3333    0.3333    1.0000    1.6667    2.3333    3.0000];
Y=X;
surf(X,Y,Z)

//LineSpec and GlobalProperty examples:
xdel(winsid()) // destroy all existing figures
surf(Z,Z+5) // color array specified
e=gce();
e.cdata_mapping='direct' // default is 'scaled' relative to the colormap
e.color_flag=3; // interpolated shading mode. The default is 4 ('flat' mode) for surf

scf(2)
surf(X,Y,Z,'colorda',ones(10,10),'edgeco','cya','marker','penta','markersiz',20,'markeredg','yel','ydata',56:65)

scf(3)
surf(Z,'cdatamapping','direct')
scf(4)
surf(Z,'facecol','interp') // interpolated shading mode (color_flag == 3)

scf(10)
axfig10=gca();
scf(11);
surf(axfig10,Z,'ydat',[100:109],'marker','d','markerfac','green','markeredg','yel') // draw onto the axe of figure 10

xdel(winsid())

See Also

plot2d , clf , xdel , delete , LineSpec , GlobalProperty ,

Author

F.Leray


text_properties

Scilab Data type
Last update : 08/12/2006

text_properties - description of the Text entity properties

Description

The Text entity is a leaf of the graphics entities hierarchy. This entity defines the parameters for string drawing

parent: This property contains the handle of the parent. The parent of the text entity should be of the type "Axes" or "Compound" .
children: This property contains a vector with the children of the handle. However, text handles currently do not have any children .
visible: This field contains the visible property value for the entity . It should be "on" or "off" .By default, the text is visible, the value's property is "on" . If "off" the text is not displayed on the screen.
text: This field is the character string vector which contains the text.
data: This field is the vector [x,y,[z]] of the origin of the text in the data units of the axes.
box: This field takes the values "on" or "off" . If "on" a box is draw around the text with a line on its edge and a background.
line_mode: This boolean property allows to draw or not a line around the box when the box property is "on" . If line_mode is "off" , the line of the box is not drawn.
fill_mode: This boolean property allows to draw or not the background of the box when the box property is "on" . If fill_mode is "off" , the background of the box is not transparent.
font_foreground: This field contains the color used to display the characters of the text. Its value should be a color index (relative to the current colormap).
foreground: This field contains the color used to display the line on the edge of the box. Its value should be a color index (relative to the current colormap).
background: This field contains the color used to fill the box around of the text. Its value should be a color index (relative to the current colormap).
font_size: The font_size property is used to select the type of size of the text. Its value should be an integer in between 0 and 5 which stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt.
font_style: Seven differents fonts are available : "Courrier", "Symbol", "Times", "Times Italic", "Times Bold", "User defined". The font_style property is an index in [0 6] which is associated to the previous font names.
font_angle: This property determines the orientation of the text string. Specify value of rotation in degrees.
clip_state: This field contains the clip_state property value for the text. Its value should be :
"off" this means that the text is not clipped.
"cliprf" this means that the text is clipped outside the Axes box.
"on" this means that the text is clipped outside the rectangle given by the property clip_box .
clip_box: This field contains the clip_box property. Its value should be an empty matrix if clip_state is "off" or the vector [x,y,w,h ] (upper-left point width height).
user_data: This field can be use to store any scilab variable in the text data structure, and to retreive it.

Examples

  set("figure_style","new") //create a figure
   a=get("current_axes");
   a.data_bounds=[0,0;1,1];

   xstring(0.5,0.6,"Scilab is not esilaB",0,0)

   t=get("hdl")   //get the handle of the newly created object

   t.font_foreground=6;
   t.font_size=5;
   t.font_style=5;
   t.text="SCILAB";
   t.font_angle=90;

See Also

set , get , delete , xtitle , graphics_entities ,

Author

Djalel ABDEMOUCHE


titlepage

Scilab Function
Last update : 16/06/2004

titlepage - ajoute un titre au milieu d'une fenêtre graphique

Calling Sequence

titlepage(str)

Parameters

  • str : matrice de chaînes de caractères

Description

titlepage affiche la matrice de chaînes de caractères str au milieu de la fenêtre graphique courante, avec la police la plus grande possible.

See Also

xtitle ,

Author

S. S.


title

Scilab Function
Last update : 04/05/2006

title - display a title on a graphic window

Calling Sequence

title(my_title)
title(my_title,<Property>)
title(<axes_handle>,<my_title>,<Property>)

Parameters

  • my_title : a string, it's the title to display
  • <Property> : This optional argument represents a sequence of couple statements {PropertyName,PropertyValue} that defines global objects' properties applied to the created title.
  • <axes_handle> : This optional argument forces the title to appear inside the selected axes given by axes_handle rather than the current axes (see gca ).

Description

title displays a title on a graphic window.

The Property arguments should be used to customize the title. Here is a complete list of the available options.

Property :

backgroundcolor : this field contains the color used to fill the box if any. Its value should be a color index (relative to the current colormap).

color : this field contains the color used to display the title text. Its value should be a color index (relative to the current colormap).

edgecolor : this field contains the color used to display the line around the box if any. Its value should be a color index (relative to the current colormap).

fontname : Seven differents fonts are available : "Courrier", "Symbol", "Times", "Times Italic", "Times Bold", "User defined". The font_size property is an index in [0 6] which is associated to the previous font names.

fontsize : The fontsize property is used to select the type of size of the title. Its value should be an integer in between 0 and 5 which stands for 8pt, 10pt, 12pt, 14pt, 18pt and 24pt.

position : This 2d vector allows you to place manually the title on the screen. The position is stored in the data units of the axes.

rotation : This scalar allows you to turn the title. The font is turned inverse clockise with the angle given in degrees.

visible : this field contains the visible property value for the title. It should be "on" or "off". By default, the label is visible, the value's property is "on" . If "off" the title is not displayed on the screen.

Examples

// display a title with several properties
title('my title');
// change the color for the font
title('my title','color','blue');
// change the color for the around the box
title('my title','edgecolor','red');
// change the position of the title
title('my title','position',[0.3 0.8]);
// change the size of the font
title('my title','fontsize',3);
// a rotation
title('my title','rotation',90);

// We can do all these modifications with just the below instruction:
title('my title','color','blue','edgecolor','red','fontsize',3,'rotation',90,'position',[0.3 0.8]);

See Also

label_properties , titlepage , xtitle ,

Author

F.Belahcene


twinkle

Scilab Function
Last update : 07/07/2004

twinkle - is used to have a graphics entity twinkle

Calling Sequence

twinkle(h,[n])

Parameters

  • h : handle of a graphics entity.
  • n : integer.

Description

twinkle let the graphics entity given by its handle h twinkle. It can be used to find the graphics object corresponding to a graphics handle in the graphics window. By default the graphics entity twinkles 5 times, but you can change this by using optional argument n .

Examples

x=linspace(-2*%pi,2*%pi,100)';
plot2d(x,[sin(x),cos(x)]);
e=gce(); p1=e.children(1); p2=e.children(2);
// cos plot twinkle
twinkle(p1)
// sin plot twinkle 10 times
twinkle(p2,10)
// axes twinkle
twinkle(gca())

See Also

graphics_entities ,


unglue

Scilab Function
Last update : 10/10/2005

unglue - unglue an agragation and replace it by individual children.

Calling Sequence

unglue(h)
H=unglue(h)

Parameters

  • h : a handle on an Compound.
  • H : a vector of handle on the resulting entities after unCompound.

Description

Given a handle on an Compound entity, this function destroies the Compound and unpacks the elementary entities to associated them to its parent. glue returns a vector of handles on these individual children.

See Also

get , set , copy , glue , graphics_entities ,

Author

Djalel ABDEMOUCHE


unzoom

Scilab Function
Last update : 16/11/2004

unzoom - unzoom graphics

Calling Sequence

unzoom()
unzoom(H)

Parameters

  • H : A handle on an axes or a vector of handle on axes.

Description

unzoom() is used to remove the zoom effect for all the axes of the current graphic figure:

unzoom(H) is used to remove the zoom effect for all the axes given by the vector of handles on axes H .

Examples

    clf()
    x=0:0.01:6*%pi;
    plot2d(x,sin(x^2))
    zoom_rect([16,-1,18,1])
    unzoom()

    //subplots accordingly
    clf()
    x=0:0.01:6*%pi;
    subplot(211)
    plot2d(x,cos(x))
    a1=gca();
    subplot(212)
    plot2d(x,cos(2*x))
    a2=gca();
    rect=[3 -2 7 10]; //a rectangle specified in the current axes (last one) coordinates
    zoom_rect(rect)
    unzoom(a1) //unzoom first plot only
    unzoom(a2) //unzoom second plot only
    zoom_rect(rect) //zoom again
    unzoom() //unzoom all the axes

See Also

zoom_rect , axes_properties ,

Author

Serge Steer INRIA


winsid

Scilab Function
Last update : 16/06/2004

winsid - renvoie la liste des fenêtre graphiques ouvertes

Calling Sequence

x=winsid()

Parameters

  • x : vecteur ligne.

Description

winsid est utilisée pour obtenir la liste des fenêtre graphiques ouvertes, sous forme d'un vecteur ligne.


xarcs

Scilab Function
Last update : 16/06/2004

xarcs - dessine des arcs d'ellipses

Calling Sequence

xarcs(arcs,[style])

Parameters

  • arcs : matrice de taille (6,n) décrivant les ellipses.
  • style : vecteur ligne de taille n donnant les couleurs à utiliser

Description

xarcs dessine des arcs d'un ensemble d'ellipses décrites par arcs : arcs=[x y w h a1 a2;x y w h a1 a2;...]' où chaque ellipse est définie par les 6 paramètres (x,y,w,h,a1,a2) (voir xarc ).

style(i) donne la couleur utilisée pour dessiner l'ellipse i .

Examples

plot2d(0,0,-1,"031"," ",[-1,-1,1,1])
arcs=[-1.0 0.0 0.5; // x du point en haut à gauche
       1.0 0.0 0.5; // y du point en haut à gauche
       0.5 1.0 0.5; // largeur
       0.5 0.5 1.0; // hauteur
       0.0 0.0 0.0; // angle 1
       180*64 360*64 90*64]; // angle 2
xarcs(arcs,[1,2,3])

See Also

xarc , xfarc , xfarcs ,

Author

J.Ph.C.;


xarc

Scilab Function
Last update : 16/06/2004

xarc - dessine un arc d'ellipse

Calling Sequence

xarc(x,y,w,h,a1,a2)

Parameters

  • x,y,w,h : 4 valeurs réelles définissant un rectangle.
  • a1,a2 : valeurs réelles définissant un secteur

Description

xarc dessine un arc d'ellipse contenu dans le rectangle (x,y,w,h) (point en haut à gauche, largeur, hauteur), et dans le secteur défini par l'angle alpha1 et l'angle alpha1+alpha2 . alpha1 et alpha2 sont donnés respectivement par a1/64 degrés et a2/64 degrés. Cette fonction utilise la couleur et l'échelle graphique courantes.

Examples

// échelle isométrique
plot2d(0,0,-1,"031"," ",[-2,-2,2,2])
xset("color",3)
xarc(-1,1,2,2,0,90*64)
xarc(-1.5,1.5,3,3,0,360*64)

See Also

xarcs , xfarc , xfarcs ,

Author

J.Ph.C.


xarrows

Scilab Function
Last update : 16/06/2004

xarrows - dessine un ensemble de flèches

Calling Sequence

xarrows(nx,ny,[arsize,style])

Parameters

  • nx,ny : valeurs réelles ou matrices de même taille.
  • arsize : réel, taille des têtes des flèches. La valeur par défaut peut être obtenue en prenant arsize = -1.
  • style : matrice ou scalaire. Si style est positif il donne la couleur de ligne pour toutes les flèches. S'il est négatif la couleur courante est utilisé. S'il est un vecteur, style(i) donne la couleur pour la flèche i .

Description

xarrows dessine un ensemble de flèches données par nx et ny . Si nx et ny sont des vecteurs, la flèche numéro i est définie par (nx(i),ny(i))-->(nx(i+1),ny(i+1)) . Si nx et ny sont des matrices :

nx=[xi_1 x1_2 ...; xf_1 xf_2 ...]
ny=[yi_1 y1_2 ...; yf_1 yf_2 ...]

la flèche numéro k est définie par (xi_k,yi_k)-->(xf_k,yf_k) .

xarrows utilise l'échelle graphique courante, qui peut être définie par appel préalable d'une fonction graphique de haut niveau comme plot2d .

Examples

x=2*%pi*(0:9)/8;
x1=[sin(x);9*sin(x)];
y1=[cos(x);9*cos(x)];
plot2d([-10,10],[-10,10],[-1,-1],"022")
xset("clipgrf")
xarrows(x1,y1,1,1:10)
xset("clipoff")

Author

J.Ph.C.


xaxis

Scilab Function
Last update : 16/06/2004

xaxis - dessine un axe

Calling Sequence

xaxis(alpha,nsteps,size,init)

Parameters

  • alpha : réel, angle en degrés de l'axe
  • nsteps : vecteur réel de taille 2, nombre d'intervalles et de sous-intervalles
  • size : vecteur réel de taille 3, taille des sous-intervalles, des petites et grandes graduations
  • init : vecteur réel de taille 2, origine de l'axe.

Description

xaxis dessine un axe.

La direction de l'axe est donnée par alpha en degrés.

init=[x0 y0] est l'origine de l'axe.

nsteps=[n1,n2] donne le nombre d'intervalles et de sous-intervalles séparés par des graduations.

size=[s1,s2,c1] où s1 donne la taille des sous-intervalles, s2 donne la taille des sous-graduations et s2*c1 donne la taille des grandes graduations. Les tailles sont données dans l'échelle courante du dessin.

            exemple : n1=3, n2=2, alpha=0
                    (s2*c1)
            |     (s2)   |            |           |
            |______|_____|_____|______|_____|_____|
               s1

Examples

x=[-%pi:0.1:%pi]';
// dessin avec axe
plot2d(x,sin(x),1,"010"," ",[-4 -1 4 1])
// l'axe des x
xpoly([-4 4],[0 0],"lines")
xaxis(0,[2 2],[2 0.1 3],[-4 0])
xstring(-4.1,-0.25,"-4"); xstring(-0.2,-0.1,"0"); xstring(4,-0.25,"4")
//  l'axe des y
xpoly([0 0],[-1 1],"lines")
xaxis(90,[2 2],[0.5 0.025 3],[0 1])
xstring(-0.5,-1.05,"-1"); xstring(-0.35,0.95,"1")

Author

J.Ph.C.


xbasc

Scilab Function
Last update : 28/06/2004

xbasc - efface une fenêtre graphique et efface les graphiques enregistrés

Calling Sequence

xbasc([window-id])

Parameters

  • window-id : entier ou vecteur d'entiers

Description

Sans argument, cette fonction efface la fenêtre graphique courante et les graphiques enregistrés. Sinon elle efface les fenêtres graphiques dont les numéros sont donnés dans le vecteur window-id , et efface les graphiques enregistrés. Par exemple xbasc(1:3) efface les fenêtres 1, 2 et 3. Si une des fenêtres n'existe pas, elle est automatiquement créée.

Avec le nouveau mode graphique, utilisez clf au lieu de xbasc .

See Also

clf , xclear ,


xbasimp

Scilab Function
Last update : 12/01/2006

xbasimp - envoie des graphiques vers une imprimante ou un fichier Postscript

Calling Sequence

xbasimp(win_num,[filen,printer])

Parameters

  • win_num : entier ou vecteur d'entiers
  • filen : chaîne de caractères, nom du fichier Postscript (la valeur par défaut est "file"). Le numéro de fenêtre est ajouté à filen .
  • printer : chaîne de caractères, nom de l'imprimante. Si printer est présent ou s'il n'y a qu'un seul argument d'entrée dans la séquence d'appel, le fichier est directement imprimé sur l'imprimante printer .

Description

xbasimp envoie les graphiques enregistrés dans la fenêtre win_num dans le fichier Postscript filen. Le fichier créé ne contient pas d'entête. Pour le visualiser, il est nécessaire d'ajouter l'entête, par exemple avec les commandes Blpr ou BEpsf ou d'utiliser directement la fonction xs2eps . Si une imprimante est spécifiée, le fichier Postscript est imprimé avec la commande Blpr . Cette fonction n'est utilisable qu'avec le pilote "Rec" .

Si win_num est un vecteur, plusieurs fichiers sont générés, un pour chaque fenêtre (avec les noms filenxx ), et les fichiers sont imprimés sur une seule page avec la commande Blpr .

See Also

printing , xs2fig , xs2ppm , xs2eps , xs2ps ,


xbasr

Scilab Function
Last update : 16/06/2004

xbasr - redessine une fenêtre graphique

Calling Sequence

xbasr(win_num)

Description

xbasr est utilisée pour redessiner le contenu de la fenêtre graphique win_num . Fonctionne uniquement avec le pilote "Rec" .

See Also

driver , replot , xtape ,

Author

J.Ph.C.


xchange

Scilab Function
Last update : 16/06/2004

xchange - transformation de coordonnées de l'échelle courante en pixels et inversement

Calling Sequence

[x1,y1,rect]=xchange(x,y,dir)

Parameters

  • x,y : deux matrices de taille (n1,n2) (coordonnées d'un ensemble de points).
  • x1,y1 : deux matrices de taille (n1,n2) (coordonnées transformées).
  • rect : un vecteur de taille 4.

Description

Après l'appel à une fonction graphique de haut niveau, xchange calcule des coordonnées en pixels à partir des coordonnées "réelles" à l'échelle du dessin courant, et inversement, suivant la valeur du paramètre dir : "f2i" (float to int) signifie réel vers pixel et "i2f" (int to float) signifie pixel vers réel. x1 et y1 sont les nouvelles coordonnées de l'ensemble de points définis par les anciennes coordonnées x et y .

rect sont les coordonnées en pixels du rectangle du cadre courant : [point en haut à gauche, largeur, hauteur].

Examples

t=[0:0.1:2*%pi]';
plot2d(t,sin(t))
[x,y,rect]=xchange(1,1,"f2i")
[x,y,rect]=xchange(0,0,"i2f")

Author

J.Ph.C.


xclear

Scilab Function
Last update : 16/06/2004

xclear - efface une fenêtre graphique

Calling Sequence

xclear([window-id])

Parameters

  • window-id : entier ou vecteur d'entiers

Description

Sans argument, cette fonction efface la fenêtre courante. Sinon elle efface les fenêtres graphiques dont les numéros sont donnés dans le vecteur window-id . Par exemple xclear(1:3) efface les fenêtres 1, 2 et 3. Si une des fenêtres n'existe pas, elle est automatiquement créée.

Attention : xclear efface la fenêtre, mais n'efface pas les ordres graphiques enregistrés. Pour cela utiliser plutôt xbasc .

See Also

xbasc ,

Author

J.Ph.C.


xclea

Scilab Function
Last update : 16/06/2004

xclea - efface un rectangle

Calling Sequence

xclea(x,y,w,h)

Parameters

  • x,y,w,h : valeurs réelles définissant le rectangle.

Description

xclea efface le rectangle [x,y,w,h] (point en haut à gauche, largeur, hauteur) dans l'échelle graphique courante.

Examples

x=[0:0.1:2*%pi]';
plot2d(x,sin(x))
xclea(1,1,1,1)

Author

J.Ph.C.


xclick

Scilab Function
Last update : 14/12/2005

xclick - attend un appui sur un bouton de la souris

Calling Sequence

[c_i,c_x,c_y,c_w,c_m]=xclick([flag])

Parameters

  • c_i : entier, numéro de bouton
  • c_x,c_y : scalaire réel, position du pointeur de la souris
  • c_w : entier, numéro de fenêtre.
  • c_m : chaîne de caractères, callback de menu
  • flag : entier. S'il est présent, la queue d'évènements des clics de souris n'est pas vidée préalablement.

Description

xclick attend l'appui sur un bouton de la souris.

Appelée avec 3 arguments en sortie, cette fonction attend qu'un bouton de la souris soit pressé avec le pointeur dans la fenêtre graphique courante.

Avec 4 ou 5 arguments en sortie, l'appui sur un bouton de la souris est attendu dans toutes les fenêtres graphiques.

Les valeurs renvoyées par xclick sont décrites ci-dessous :

c_i: un entier donnant le numéro du bouton ou de la touche pressé.
c_i==0:Le bouton gauche a été pressé
c_i==1: Le bouton central a été pressé
c_i==2: Le bouton droit a été pressé

c_i==3: Le bouton gauche a été cliqué
c_i==4: Le bouton central a été cliqué
c_i==5: Le bouton droit a été cliqué

c_i==10: Le bouton gauche a été double-cliqué
c_i==11: Le bouton central a été double-cliqué
c_i==12: Le bouton droit a été double-cliqué

c_i > =32: La touche de code ascii ascii(c_i) a été cliqué
c_i > =1000+32: La touche de code ascii ascii(c_i-1000) a été cliqué avec la touche CTRL enfoncée.
c_i==-100: La fenêtre graphique
c_i==-2: Un menu dynamique a été selectionné
c_x,c_y: les coordonnées de la position du curseur au moment du clic, à l'échelle graphique courante.
c_w: le numéro de la fenêtre ou le clic s'est produit.
c_m: chaîne de caractères associée à un menu dynamique. Si xclick se termine à cause d'un clic sur l'article d'un menu, c_i , c_x , c_y, et c_w prennent des valeurs arbitraires

PROBLÈMES CONNUS

xclick peut renvoyer le message "Can't grab the pointer" si la fenêtre graphique courante est iconifiée au moment de l'appel.

See Also

locate , xgetmouse ,

Author

J.Ph.C.


xclip

Scilab Function
Last update : 13/12/2005

xclip - définit une zone de "clipping"

Calling Sequence

xclip([x,y,w,h])
xclip(rect)
xclip("clipgrf")

Parameters

  • x,y,w,h : valeurs réelles.
  • rect : vecteur ligne de taille 4.

Description

xclip définit une zone de "clipping" définie par les coordonnées, dans l'échelle courante, du rectangle x,y,w,h (point en haut à gauche, largeur, hauteur) : les opérations graphiques sont restreintes à ce rectangle.

Si un seul argument est donné, il est considéré comme une spécification de rectangle rect=[x,y,w,h] .

xclip("clipgrf") est utilisé pour utiliser la zone de clipping égale au cadre du dessin courant.

Pour supprimer l'effet d'une commande xclip précédente, utiliser xclip() .

Examples

x=0:0.2:2*%pi;
x1=[sin(x);100*sin(x)];
y1=[cos(x);100*cos(x)];
y1=y1+20*ones(y1);

// set the frame
clf();a=gca();a.data_bounds=[-100 -100;500 600];

// No clipping
xsegs(10*x1+200*ones(x1),10*y1+200*ones(y1))
e=gce(); //handle on the Segs entity

// draw rectangle clipping zone
xrect(150,460,100,150)
// set clip_box for  Segs entity
e.clip_box=[150,460,100,150];

// Set usual rectangle boundaries clipping zone
e.clip_state='clipgrf';
xclip("clipgrf")
// remove clipping
e.clip_state='off';

Author

J.Ph.C.


xdel

Scilab Function
Last update : 16/06/2004

xdel - supprime des fenêtres graphiques

Calling Sequence

xdel([win-nums])

Parameters

  • win-nums : entier ou vecteur d'entiers

Description

xdel supprime les fenêtres graphiques dont les numéros sont donnés dans le vecteur win-nums ou supprime la fenêtre graphique courante si aucun argument n'est donné.

Author

J.Ph.C.


xend

Scilab Function
Last update : 16/06/2004

xend - termine la session graphique courante

Calling Sequence

xend()

Description

xend est utilisée pour terminer une session graphique. Avec les pilotes PostScript, XFig ou Gif, xend ferme le fichier qui a été ouvert par xinit .

Examples

driver("Pos")
xinit("foo.ps")
plot2d()
xend()
driver("X11")

See Also

xbasimp , xend ,

Author

J.Ph.C.


xfarcs

Scilab Function
Last update : 16/06/2004

xfarcs - remplit des secteurs angulaires d'ellipses

Calling Sequence

xfarcs(arcs,[style])

Parameters

  • arcs : matrice de taille (6,n) décrivant les ellipses.
  • style : vecteur ligne de taille n donnant les couleurs à utiliser

Description

xarcs remplit des secteurs angulaires d'un ensemble d'ellipses décrites par arcs : arcs=[x y w h a1 a2;x y w h a1 a2;...]' où chaque ellipse est définie par les 6 paramètres (x,y,w,h,a1,a2) (voir xarc ).

style(i) donne la couleur utilisée pour remplir l'ellipse i .

Examples

plot2d(0,0,-1,"031"," ",[-1,-1,1,1])
arcs=[-1.0 0.0 0.5; // abscisse du coin superieur gauche
       1.0 0.0 0.5; // ordonnée du coin superieur gauche
       0.5 1.0 0.5; // longueur
       0.5 0.5 1.0; // hauteur
       0.0 0.0 0.0; // angle 1
       180*64 360*64 90*64]; // angle 2
xfarcs(arcs,[1,2,3])

See Also

xarc , xfarc , xfarc ,

Author

J.Ph.C.


xfarc

Scilab Function
Last update : 16/06/2004

xfarc - remplit un secteur angulaire d'ellipse

Calling Sequence

xfarc(x,y,w,h,a1,a2)

Parameters

  • x,y,w,h : 4 valeurs réelles définissant un rectangle.
  • a1,a2 : valeurs réelles définissant un secteur

Description

xfarc remplit un arc d'ellipse contenu dans le rectangle (x,y,w,h) (point en haut à gauche, largeur, hauteur), et dans le secteur défini par l'angle alpha1 et l'angle alpha1+alpha2 . alpha1 et alpha2 sont donnés respectivement par a1/64 degrés et a2/64 degrés. Cette fonction utilise l'échelle et la couleur courantes.

Examples

// échelle isométrique
plot2d(0,0,-1,"031"," ",[-2,-2,2,2])
xfarc(-0.5,0.5,1,1,0,90*64)
xset("color",2)
xfarc(0.5,0.5,1,1,0,360*64)

See Also

xarc , xarcs , xfarcs ,

Author

J.Ph.C.;


xfpolys

Scilab Function
Last update : 28/07/2004

xfpolys - fill a set of polygons

Calling Sequence

xfpolys(xpols,ypols,[fill])

Parameters

  • xpols,ypols : matrices of the same size (p,n) (points of the polygons).
  • fill : vector of size n or of size (p,n)

Description

xfpolys fills a set of polygons of the same size defined by the two matrices xpols and ypols . The coordinates of each polygon are stored in a column of xpols and ypols .

The polygons may be filled with a given color (flat) or painted with interpolated (shaded) colors.

flat color paintingIn this case fill should be a vector of size n . The pattern for filling polygon number i is given by fill(i) :
-if fill(i)<0 , the polygon is filled with pattern id -fill(i) .
-if fill(i)=0 , the polygon is drawn with the current dash style (or current color) and not filled.
-if fill(i)>0 , the polygon is filled with pattern id fill(i) . Then its contour is drawn with the current dash (or color) and closed if necessary.
interpolated color painting

In this case fill should be a matrix with same sizes as xpols and ypols . Note that p must be equal to 3 or 4.

fill(k,i) gives the color at the k th edge of polygon i .

Examples

    set('figure_style','new')
    a=gca();a.data_bounds=[0,-10;210,40];a.foreground=color('red');
    x1=[0,10,20,30,20,10,0]';
    y1=[15,30,30,15,0,0,15]';
    xpols=[x1 x1 x1 x1]; xpols=xpols+[0,60,120,180].*.ones(x1);
    ypols=[y1 y1 y1 y1];
    xfpolys(xpols,ypols,[-1,0,1,2])

    // interpolated colors
    clf()
    f=gcf();
    a=gca();a.data_bounds=[0,-10;40,30];a.isoview='on';
    x1=[0,10,20,10]';
    y1=[10,0,10,20]';
    c=linspace(2,100,4)';
    xpols=[x1 x1+20 x1+10 x1+10];
    ypols=[y1 y1    y1+10 y1-10];
    cols= [c c($:-1:1) c([3 4 1 2]) c]
    f.color_map=jetcolormap(max(cols));
    xfpolys(xpols,ypols,cols)

    // interpolated colors
    clf()
    f=gcf();
    x11=[0;20;20;0];y11=[10;10;30;30];c11=[10;10;30;30];
    x12=x11;y12=y11+20;c12=[20;20;1;1];c12=[30;30;10;10];
    x21=[0;30;30;0]+22;y21=[20;20;30;30];c21=[20;20;30;30];
    x22=x21;y22=y21+10;c22=[30;30;20;20];
    x31=[0;40;40;0]+55;y31=[0;0;30;30];c31=[0;0;30;30];
    x32=x31;y32=y31+30;c32=[30;30;0;0];
    X=[x11 x12 x21 x22 x31 x32];Y=[y11 y12 y21 y22 y31 y32];C=([c11 c12 c21 c22  c31 c32]+1)*5;
    a=gca();a.isoview='on';
    a.data_bounds=[min(X),min(Y);max(X),max(Y)];
    f=gcf();f.color_map=graycolormap(max(C));
    xfpolys(X,Y,C)

See Also

xfpoly , xpoly , xpolys ,

Author

J.Ph.C.


xfpoly

Scilab Function
Last update : 06/10/2005

xfpoly - remplit un polygone

Calling Sequence

xfpoly(xv,yv,[close])

Parameters

  • xv,yv : deux vecteurs de même taille (les points du polygone).
  • close : entier. Si close=1, la ligne brisée est fermée (valeur par défaut : 0).

Description

xfpoly remplit un polygone avec la couleur courante. Si close est égal à 1, un point est ajouté à la ligne brisée xv,yv pour définir un polygone.

Examples

x=sin(2*%pi*(0:4)/5);
y=cos(2*%pi*(0:4)/5);
plot2d(0,0,-1,"010"," ",[-2,-2,2,2])
xset("color",5)
xfpoly(x,y)

// News graphics only
e=gce(); // get the current entity (the last created: here the polyline)
e.fill_mode='off';
e.closed = 'off' // the polyline is now open
xset("default")

See Also

xfpolys , xpoly , xpolys ,

Author

J.Ph.C.


xfrect

Scilab Function
Last update : 16/06/2004

xfrect - remplit un rectangle

Calling Sequence

xfrect(x,y,w,h)
xfrect(rect) // rect =[x,y,w,h]

Parameters

  • x,y,w,h : 4 valeurs réelles définissant le rectangle.

Description

xrect remplit un rectangle défini par [x,y,w,h] (point en haut à gauche, largeur, hauteur) en utilisant l'échelle courante et la couleur courante.

Examples

plot2d(0,0,-1,"010"," ",[-2,-2,2,2])
xset("color",5)
xfrect(-1,1,2,2)
xset("default")

See Also

xrect , xrects ,

Author

J.Ph.C.


xgetech

Scilab Function
Last update : 16/06/2004

xgetech - récupération de l'échelle graphique courante

Calling Sequence

[wrect,frect,logflag,arect]=xgetech()

Parameters

  • wrect,frect : valeurs réelles.
  • logflag : chaîne de caractères de taille 2 "xy".

Description

xgetech renvoie l'échelle graphique de la fenêtre courante. Le rectangle [xmin,ymin,xmax,ymax] donné par frect est la taille de toute la fenêtre graphique. Le dessin est fait dans la région définie par wrect .

wrect=[x,y,w,h] (point en haut à gauche, largeur, hauteur) décrit la région de la fenêtre graphique.

wrect=[0,0,1,1] signifie que toute la fenêtre graphique est utilisée, et wrect=[0.5,0,0.5,1] signifie que seule la moitié droite de la fenêtre graphique est utilisée.

logflag : chaîne de caractères de taille 2 "xy", où x et y peuvent être "n" ou "l". "n" pour échelle normale et "l" pour échelle logarithmique. x pour axe des x et y pour axe des y.

arect=[x_gauche, x_droite,y_haut,y_bas] définit le cadre dans la sous-fenêtre. Le cadre est spécifié (comme wrect ) en utilisant des proportions de la largeur et de la hauteur de la sous-fenêtre courante.

Examples

// première sous-fenêtre
xsetech([0,0,1.0,0.5])
plot2d()
// deuxième sous-fenêtre activée
xsetech([0,0.5,1.0,0.5])
grayplot()
// recupération de l'échelle
xsetech([0,0,1.0,0.5])
[wrect,frect,logflag,arect]=xgetech();
// recupération de l'échelle
xsetech([0,0.5,1.0,0.5])
[wrect,frect,logflag,arect]=xgetech();
xbasc();

See Also

xsetech ,

Author

J.Ph.C.;


xgetmouse

Scilab Function
Last update : 10/02/2006

xgetmouse - get the mouse events and current position

Calling Sequence

rep=xgetmouse([flag], [sel])

Parameters

  • flag : integer. If present, the mouse click event queue is not cleared when entering xgetmouse.
  • sel : boolean vector [getmotion, getrelease] . default value is [%t, %f]
  • rep : vector of size 3, [x,y,ibutton].

Description

If the mouse pointer is located in the current graphics window, xgetmouse returns in rep the current pointer position (x,y) and the value ibutton . The ibutton value indicates the event type:

ibutton==0: Left mouse button has been pressed
ibutton==1: Middle mouse button has been pressed
ibutton==2: Right mouse button has been pressed

ibutton==3: Left mouse button has been clicked
ibutton==4: Middle mouse button has been clicked
ibutton==5: Right mouse button has been clicked

ibutton==10: Left mouse button has been double-clicked
ibutton==11: Middle mouse button has been double-clicked
ibutton==12: Right mouse button has been double-clicked

ibutton==-5: Left mouse button has been released
ibutton==-4: Middle mouse button has been released
ibutton==-3: Right mouse button has been released

ibutton==-1: pointer has moved

ibutton > =32: key with ascii code ascii(ibutton) has been pressed
ibutton < =-32: key with ascii code ascii(-ibutton) has been released

ibutton > =1000+32: key with ascii code ascii(ibutton-1000) has been pressed while CTRL key pressed
ibutton==-1000: graphic window has been closed

Examples

//  rectangle selection
clf();  // erase/create window
a=gca();a.data_bounds=[0 0;100 100];//set user coordinates
xtitle(" drawing a rectangle ") //add a title
xselect(); //put the window on the top

[b,xc,yc]=xclick(); //get a point
xrect(xc,yc,0,0) //draw a rectangle entity
r=gce();// the handle of the rectangle
rep=[xc,yc,-1];first=%f;

while rep(3)==-1 do // mouse just moving ...
  if first then rep=xgetmouse();else rep=xgetmouse(0);end
  xc1=rep(1);yc1=rep(2);
  ox=mini(xc,xc1);
  oy=maxi(yc,yc1);
  w=abs(xc-xc1);h=abs(yc-yc1);
  r.data=[ox,oy,w,h]; //change the retangle origin, width an height
  first=%f;
end

See Also

locate , xclick , seteventhandler ,

Author

S. Steer


xget

Scilab Function
Last update : 16/12/2005

xget - récupère des valeurs du contexte graphique de la fenêtre courante

Calling Sequence

[x1]=xget(str,[flag])
xget()

Parameters

  • str : chaîne de caractères.
  • flag : optionnel. Choisir 1 pour le mode "bavard".

Description

Remarque Importante : Les versions Scilab 4.x seront les dernières à fonctionner avec l'ancien mode graphique.

Cette fonction est utilisée pour récupérer des valeurs du contexte graphique de la fenêtre courante, sur le sujet précisé par la chaîne de caractères str . Sans argument, cette fonction affiche une boîte de dialogue montrant les valeurs courantes et des changements peuvent être effectués à l'aide de boutons.

number=xget("alufunction"): Opérateur logique utilisé pour les dessins Voir xset .
str=xget("auto clear"): donne le mode d'effacement automatique ( "on" ou "off" ).
color=xget("background"): donne la couleur d'arrière plan
rect=xget("clipping"): donne la zone de clipping sous forme d'un rectangle rect=[x,y,w,h] (point en haut à gauche, largeur, hauteur).
c=xget("color"): donne la couleur par défaut pour le tracé de ligne, le texte ou le remplissage. c est l'indice de la couleur dans la table de couleurs de la fenêtre.
cmap=xget("colormap"): donne la table de couleurs de la fenêtre graphique (matrice m x 3 d'intensités R,V,B)
dash=xget("dashes"): obsolète
font=xget("font"): donne le code et la taille de la police par défaut font=[fontid,fontsize],
fontsize=xget("font size"): donne la taille par défaut des polices
color=xget("foreground"): donne la couleur de premier plan
str=xget("fpf"): donne le format d'affichage des nombres pour les fonctions dessinant des courbes de niveau (voir contour). str="" désigne le format par défaut.
color=xget("hidden3d"): donne la couleur du dessous des facettes pour le dessin des surfaces en 3D.
pat=xget("lastpattern"): donne le dernier indice de couleur disponible dans la table des couleurs. En fait pat+1 et pat+2 sont toujours disponibles et correspondent toujours au noir et au blanc.
type=xget("line mode"): donne le mode de tracé des lignes. type=1 : absolu, type=0 : relatif (le mode type=0 est buggé)
xget("line style"): donne le style de ligne par défaut (1 : plein, >1 : pointillés).
mark=xget("mark"): donne le numéro et la taille du marqueur par défaut mark=[markid,marksize] .
marksize=xget("mark size"): donne la taille de marqueur par défaut
pat=xget("pattern"): obsolète
value=xget("thickness"): donne la largeur des lignes en pixels (0 et 1 = 1 pixel d'épaisseur).
flag=xget("use color"): 0 (mode noir et blanc) ou 1 (mode en couleurs). Voir xset .
[x,y]=xget("viewport"): donne la position de la partie visible des graphiques dans la fenêtre glissante.
dim=xget("wdim"): donne la largeur et la hauteur de la fenêtre graphique dim=[width,height].
win=xget("window"): donne le numéro de la fenêtre win .
pos=xget("wpos");: donne la position du point en haut à gauche de la fenêtre graphique pos=[x,y].

See Also

xset , colormap ,

Author

J.Ph.C.


xgraduate

Scilab Function
Last update : 16/06/2004

xgraduate - graduation des axes

Calling Sequence

[xi,xa,np1,np2,kMinr,kMaxr,ar]=xgraduate(xmi,xma)

Parameters

  • xmi,xma : scalaire réel
  • xi, xa, kMinr, kMaxr, ar :scalaires réels
  • np1,np2 : entier

Description

xgraduate renvoie les graduations des axes utilisées par les routines de dessin. Elle renvoie un intervalle [xi,xa] contenant l'intervalle donné [xmi,xma] avec xi et xa tels que

xi= kMinr*10^ar , xa=kMaxr*10^ar et l'intervalle peut être divise en np2 intervalles et chaque intervalle est divisé en np1 sous-intervalles.

Examples

  [x1,xa,np1,np2,kMinr,kMaxr,ar]=xgraduate(-0.3,0.2)

See Also

graduate , plot2d ,

Author

J.P.C ; ;


xgrid

Scilab Function
Last update : 16/06/2004

xgrid - ajoute une grille sur un dessin 2D

Calling Sequence

xgrid([style])

Parameters

  • style : entier

Description

xgrid ajoute une grille sur un dessin 2D. style est le numéro de couleur de la grille. Utiliser xset() pour voir les numéros de couleurs.

Examples

x=[0:0.1:2*%pi]';
plot2d(sin(x))
xgrid(2)

See Also

xset , plot2d ,

Author

J.Ph.C.


xinfo

Scilab Function
Last update : 16/06/2004

xinfo - affiche une chaîne de caractères dans la sous-fenêtre de messages

Calling Sequence

xinfo(info)

Parameters

  • info : chaîne de caractères

Description

xinfo dessine la chaîne de caractères info dans la sous-fenêtre de messages de la fenêtre graphique courante.


xinit

Scilab Function
Last update : 06/07/2004

xinit - initialisation d'un pilote graphique

Calling Sequence

xinit([driver-name])

Parameters

  • driver-name : chaîne de caractères.

Description

Initialisation d'un pilote donné.

Pour XWindows, driver-name peut être une chaîne de caractères donnant le nom du display et une nouvelle fenêtre graphique est créée. Si l'argument est omis la valeur de la variable d'environnement DISPLAY est utilisée (si elle existe) sinon la valeur "unix:0.0" est utilisée.

Pour les pilotes Postscript, Xfig ou Gif, driver-name est le nom d'un fichier où tous les ordres graphiques sont enregistrés.

Dans le cas Postscript case le fichier généré n'est pas un fichier postscript complet. Il doit etre converti en utilisant les programmes shell BEpsf ou Blatexpr (voir printing)

Examples

driver("Pos")
xinit("foo.ps")
plot2d()
xend()
driver("X11")

See Also

xbasimp , xend ,

Author

J.Ph.C.


xlfont

Scilab Function
Last update : 13/12/2005

xlfont - load a font in the graphic context or query loaded font

Calling Sequence

xlfont(font-name,font-id)
fonts=xlfont()

Parameters

  • font-name : string, name of the font family.
  • font-id : integer between 0 and 10.
  • fonts : a column vector of currently loaded font names.

Description

Without any argument, xlfont() returns the list of currently loaded fonts.

With arguments, xlfont is used to load a new font at different sizes in the graphics context. The font must be available with size 8, 10, 12, 14, 18 and 24.

Default fonts are "Courier Roman" (0), "Symbol" (1), "Times Roman" (2), "Times Italic" (3), "Times Bold" (4), "Times Bold Italic" (5), "Helvetica" (6), "Helvetica Oblique" (7), "Helvetica Bold" (8), "Helvetica Bold Oblique" (9). These default fonts are automaticaly loaded when needed and so xlfont is not really required for them. In fact xlfont is essentially useful to load a new font.

font-name can be of 2 types:

- if it contains the character "%", it is supposed to be an X11 font name with %s in the size field of the name, for example "-b&h-lucidabright-demibold-r-normal--%s-*-75-75-p-*-iso8859-1"
- if it does not contain the character "%", it is supposed to be an alias name and the fonts aliased by font-name08,...,font-name24 are loaded.
font-id: give the id font-id to the loaded font font-name .

Currently this load font feature works only for screen drivers and not for others (Postscript, Fig, Gif, PPM). If you export a graphical screen output in Postscript, Fig, Gif or PPM while you have previously loaded a new font, the behavior depends of the choice of the identifier font-id for the loaded font :

-if font-id=10 then the strings (drawn with this font) will be drawn with the default font (Times) at the same size;
-else the strings will be drawn with the default font corresponding to font-id .

Examples

// Caution : this example may not work if your system have not
//           the schoolbook bold font
if MSDOS then
   xlfont("Century Schoolbook Bold",10)
else
   xlfont("-adobe-new century schoolbook-bold-r-normal-*-%s-*-75-75-*-*-iso8859-1",10)
end
xset("font", 10, 4) // use Schoolbook bold at 18 pts
plot2d()

See Also

xset , getfont ,

Author

J.Ph.C.


xload

Scilab Function
Last update : 09/12/2005

xload - load a saved graphics

Calling Sequence

xload(file_name,[win_num])

Parameters

  • file_name : string, name of the file.
  • win_num : integer, the graphics window number. If not given, the current graphics window is used.

Description

xload reloads the graphics contained in the file file_name in the graphics window win_num .

For files containing new graphics, the load function can be used instead of xload . xload does not restore the window number, the window size nor the window dimensions.

Examples

    //new style
    set figure_style new
    t=0:0.01:10;
    subplot(211),plot2d(t,sin(t))
    subplot(212),plot2d(t,sin(3*t))
    save(TMPDIR+'/foo.scg',gcf())
    clf()
    load(TMPDIR+'/foo.scg')

    a=gca();
    curve=a.children.children; //handle on the curve
    save(TMPDIR+'/foo.scg',curve)
    delete(curve)
    load(TMPDIR+'/foo.scg')

    //old style
    set figure_style old
    t=0:0.01:10;
    subplot(211),plot2d(t,sin(t))
    subplot(212),plot2d(t,sin(3*t))
    xsave(TMPDIR+'/foo.scg')
    xbasc()
    set figure_style old
    xload(TMPDIR+'/foo.scg')

See Also

xsave , load , loadplots , save ,

Author

J.Ph.C.


xname

Scilab Function
Last update : 16/06/2004

xname - change le nom de la fenêtre graphique courante

Calling Sequence

xname(name)

Parameters

  • name : chaîne de caractères, nom de la fenêtre graphique.

Description

xname change le nom de la fenêtre graphique courante.

Author

J.Ph.C.


xnumb

Scilab Function
Last update : 16/06/2004

xnumb - dessine des nombres

Calling Sequence

xnumb(x,y,nums,[box,angle])

Parameters

  • x,y,nums : vecteurs de même taille.
  • box : entier.
  • angle : vecteur optionnel de même taille que x

Description

xnumb dessine les nombres nums(i) aux positions x(i),y(i) dans l'échelle courante. Si box vaut 1, une boîte est dessinée autour des nombres. Si angle est donné, il donne la direction pour le dessin de la chaîne de caractères.

Examples

plot2d([-100,500],[-100,600],[-1,-1],"022")
x=0:100:200;
xnumb(x,500*ones(x),[10,20,35],1)

See Also

xstring ,

Author

J.Ph.C.


xpause

Scilab Function
Last update : 16/06/2004

xpause - interrompt Scilab pendant une durée donnée

Calling Sequence

xpause(microsecs)

Description

xpause interrompt Scilab pendant un temps donné en microsecondes spécifié par l'argument. Le temps de pause peut être plus long que prévu à cause de l'activité du système, ou bien tout simplement à cause du temps passé pendant l'appel lui même.

Author

J.Ph.C.


xpolys

Scilab Function
Last update : 16/06/2004

xpolys - dessine un ensemble de lignes brisées ou de polygones

Calling Sequence

xpolys(xpols,ypols,[draw])

Parameters

  • xpols,ypols : matrices de même taille (p,n) (points des lignes brisées).
  • draw : vecteur de taille n.

Description

xpolys dessine un ensemble de lignes brisées ou de polygones. Les coordonnées de chaque ligne brisée sont stockées dans une colonne de xpols et ypols .

Le style de la ligne brisée i est donné par draw(i) :

-Si draw(i) < 0 , le marqueur numéro -draw(i) est utilisé (les marqueurs sont dessinés en utilisant la couleur courante). Utiliser xset() pour voir les codes des marqueurs.
-Si draw(i) > 0, la couleur numéro draw(i) est utilisé pour dessiner la ligne brisée i. Utiliser xset() pour voir les codes des couleurs.

Examples

    plot2d(0,0,-1,"012"," ",[0,0,1,1])
    rand("uniform")
    xset("color",3)
    xpolys(rand(3,5),rand(3,5),[-1,-2,0,1,2])
    xset("default")

See Also

xfpoly , xfpolys , xpoly ,

Author

J.Ph.C.


xpoly

Scilab Function
Last update : 06/10/2005

xpoly - dessine une ligne brisée ou un polygone

Calling Sequence

xpoly(xv,yv [,dtype [,close]])

Parameters

  • xv,yv : matrices de même taille (points de la ligne brisée).
  • dtype : chaîne de caractères (style de dessin, valeur par défaut : "lines").
  • close : entier. Si close=1, la ligne brisée est fermée (valeur par défaut : 0).

Description

xpoly dessine une ligne brisée décrite par les vecteurs de coordonnées xv et yv . Si xv et yv sont des matrices elles sont considérées comme des vecteurs (par concaténation de leurs colonnes). Si close=1 un segment supplémentaire est ajouté entre le premier et le dernier point de la ligne brisée. dtype peut être égal à "lines" pour utiliser le style de ligne courant ou "marks" pour utiliser des marqueurs.

Examples

x=sin(2*%pi*(0:4)/5);
y=cos(2*%pi*(0:4)/5);

plot2d(0,0,-1,"010"," ",[-2,-2,2,2])
xset("color",5)
xpoly(x,y,"lines",1) // by default closed

// News graphics only
e=gce(); // get the current entity (the last created: here the polyline)
e.closed = 'off' // the polyline is now open

See Also

xfpoly , xfpolys , xpolys ,

Author

J.Ph.C.


xrects

Scilab Function
Last update : 16/06/2004

xrects - dessine ou remplit un ensemble de rectangles

Calling Sequence

xrects(rects,[fill])

Parameters

  • rects : matrice de taille (4,n).
  • fill : vecteur de taille n.

Description

xrects dessine ou remplit un ensemble de rectangles. Chaque colonne de rects décrit un rectangle (point en haut à gauche, largeur, hauteur): rects=[x1 y1 w1 h1;x2 y2 w2 h2;...]' .

fill(i) définit le motif utilisé pour dessiner ou remplir le rectangle i:

si fill(i)<0 , le rectangle i est dessiné avec la couleur -fill(i) .

si fill(i)>0 , le rectangle i est rempli avec la couleur fill(i) .

si fill(i)=0 , le rectangle i est dessiné avec le style de ligne courant.

Examples

plot2d([-100,500],[-50,50],[-1,-1],"022")
cols=[-34,-33,-32,-20:5:20,32,33,34];
x=400*(0:14)/14; step=20;
rects=[x;10*ones(x);step*ones(x);30*ones(x)];
xrects(rects,cols)
xnumb(x,15*ones(x),cols)

See Also

xfrect , xrect ,

Author

J.Ph.C.


xrect

Scilab Function
Last update : 16/06/2004

xrect - dessine un rectangle

Calling Sequence

xrect(x,y,w,h)
xrect(rect) // rect =[x,y,w,h]

Parameters

  • x,y,w,h : 4 valeurs réelles définissant le rectangle.

Description

xrect dessine un rectangle défini par [x,y,w,h] (point en haut à gauche, largeur, hauteur) en utilisant l'échelle courante et le style de ligne courant.

Examples

plot2d(0,0,-1,"010"," ",[-2,-2,2,2])
xset("color",5)
xrect(-1,1,2,2)
xset("default")

See Also

xfrect , xrects ,

Author

J.Ph.C.


xrpoly

Scilab Function
Last update : 16/06/2004

xrpoly - dessine un polygone régulier

Calling Sequence

xrpoly(orig,n,r,[theta])

Parameters

  • orig : vecteur de taille 2.
  • n : entier, nombre de faces.
  • r : scalaire.
  • theta : réel, angle en radians (0 par défaut).

Description

xrpoly dessine un polygone régulier à n faces contenu dans le disque de diamètre r et avec l'origine au point orig . theta spécifie un angle de rotation en radians. Cette fonction utilise l'échelle graphique courante.

Examples

plot2d(0,0,-1,"012"," ",[0,0,10,10])
xrpoly([5,5],5,5)

See Also

xrect ,


xs2bmp

Scilab Function
Last update : 27/07/2005

xs2bmp - send graphics to a file in BMP syntax (Only for Windows)

Calling Sequence

xs2bmp(win_num,filen)

Parameters

  • win_num : integer scalar.
  • filen : string, file name.

Description

xs2bmp sends the recorded graphics of the window win_num in the file filen in BMP format. This function works only if the selected driver is "Rec" in the window win_num or if the window is in "new style".

Examples

    //simple example
    scf(0)
    plot2d()
    xs2bmp(0,'foo.bmp')

See Also

xs2fig , xs2ps , xs2ppm , xs2emf ,

Author

A.C


xs2emf

Scilab Function
Last update : 27/07/2005

xs2emf - send graphics to a file in EMF syntax (Only for Windows)

Calling Sequence

xs2emf(win_num,filen)

Parameters

  • win_num : integer scalar.
  • filen : string, file name.

Description

xs2emf sends the recorded graphics of the window win_num in the file filen in EMF format. This function works only if the selected driver is "Rec" in the window win_num or if the window is in "new style".

Examples

    //simple example
    scf(0)
    plot2d()
    xs2emf(0,'foo.emf')

See Also

xs2fig , xs2ps , xs2ppm , xs2bmp ,

Author

A.C


xs2eps

Scilab Function
Last update : 08/06/2005

xs2eps - save graphics to a Postscript file.

Calling Sequence

xs2eps(win_num,filen [,colored] [,orientation])

Parameters

  • win_num : integer scalar or vector .
  • filen : string, file name.
  • colored : optional integer or boolean. 0 (%f) means black and white and 1 (%t) means color. The default value (-1) is to use a value compatible with the screen status.
  • orientation : optional character, with possible values 'p' (portrait) or 'l' (landscape). The default value is 'p'.

Description

xs2eps saves the recorded graphics of the window win_num to file filen in Postscript syntax. Note that filen must not have extension.

xs2eps produces a complete encapsulated Postscrip file. It simply calls xs2eps and then BEpsf .

This function works only if the selected driver is "Rec" in the window win_num or if the window is in "new style". The generated postscript file does not contrains the header part

Examples

    scf(0)
    plot2d()
    // Postscript export
    filename='foo'; // ! no extension
    xs2eps(0,filename)

See Also

set_posfig_dim , printing , xs2ps , xs2fig , xs2gif , xbasimp , xs2ppm ,


xs2fig

Scilab Function
Last update : 29/06/2005

xs2fig - send graphics to a file in Xfig syntax

Calling Sequence

xs2fig(win_num,filen,[color])

Parameters

  • win_num : integer scalar or vector .
  • filen : string, file name.
  • color : optional integer. 0 means black and white and 1 means color. The default value is to use a value compatible with the screen status.

Description

xs2fig sends the recorded graphics of the window win_num in the file filen in Xfig syntax. This function works only if the selected driver is "Rec" or if the window is in "new style".

To convert a sequence of "GIF" files to an animated GIF file one can use the "convert" program for ImageMagic (http://www.imagemagick.org/)

For example if one has generated a sequence of Gif files named img*.gif it is possible to build an animated Gif file (named anim.gif) by

    convert -delay 10  img*.gif anim.gif

Examples

    scf(0)
    plot2d()
    xs2fig(0,'foo.fig')

See Also

xs2ps , xs2gif , xs2ppm ,


xs2gif

Scilab Function
Last update : 21/06/2005

xs2gif - send graphics to a file in GIF syntax

Calling Sequence

xs2gif(win_num,filen,[color])

Parameters

  • win_num : integer scalar or vector .
  • filen : string, file name.
  • color : optional integer. 0 means black and white and 1 means color. The default value is to use a value compatible with the screen status.

Description

xs2gif sends the recorded graphics of the window win_num in the file filen in GIF format. This function works only if the selected driver is "Rec" in the window win_num or if the window is in "new style".

To convert a sequence of "GIF" files to an animated GIF file one can use the "convert" program for ImageMagic (http://www.imagemagick.org/)

For example if one has generated a sequence of Gif files named img*.gif it is possible to build an animated Gif file (named anim.gif) by

    convert -delay 10  img*.gif anim.gif

Examples

    scf(0)
    plot2d()
    xs2gif(0,'foo.gif')

See Also

xs2fig , xs2ps , xs2ppm ,


xs2ppm

Scilab Function
Last update : 28/09/2004

xs2ppm - send graphics to a file in PPM syntax

Calling Sequence

xs2ppm(win_num,filen,[color])

Parameters

  • win_num : integer scalar or vector .
  • filen : string, file name.
  • color : optional integer. 0 means black and white and 1 means color. The default value is to use a value compatible with the screen status.

Description

xs2ppm sends the recorded graphics of the window win_num in the file filen in PPM format. This function works only if the selected driver is "Rec" in the window win_num or if the window is in "new style".

Examples

    scf(0)
    plot2d()
    xs2ppm(0,'foo.ppm')

See Also

xs2fig , xs2ps , xs2gif ,


xs2ps

Scilab Function
Last update : 12/01/2006

xs2ps - send graphics to a file in PS syntax

Calling Sequence

xs2ps(win_num,filen,[color])

Parameters

  • win_num : integer scalar or vector .
  • filen : string, file name.
  • color : optional integer. 0 means black and white and 1 means color. The default value is to use a value compatible with the screen status.

Description

xs2ps saves the recorded graphics of the window win_num to file filen in Postscript syntax. The filen must not have suffix extension.

Note that the generated Postscript file cannot be direcly printed since it requires a header file. The Scilab command BEpsf or others can be used to add a header file. The function xs2eps can be used to directly produce an encapsulated Postscript file with an header.

This function works only if the selected driver is "Rec" in the window win_num or if the window is in "new style". The generated postscript file does not contrains the header part

Examples

    scf(0)
    plot2d()
    // Postcript export
    filename='foo'; // ! no extension
    xs2ps(0,filename)
    //add the Postscript file header and create <filename>.eps file
    if MSDOS then
      unix_s(pathconvert('""'+WSCI+'/bin/BEpsf'+'""',%f)+' -p ' +filename)
    else
      unix_s(pathconvert('SCI/bin/BEpsf',%f)+' -p ' +filename)
    end
    // Gif export
    xs2gif(0,'foo.gif')
    // ppm export
    xs2ppm(0,'foo.ppm')

See Also

set_posfig_dim , printing , xs2eps , xs2fig , xs2gif , xbasimp , xs2ppm ,


xsave

Scilab Function
Last update : 09/12/2005

xsave - save graphics into a file

Calling Sequence

xsave(filename,[win_num])

Parameters

  • file_name : string, name of the file.
  • win_num : integer, the graphics window number. If not given, the current graphics window is used.

Description

xsave saves the graphics contained in the graphics window win_num in the binary file file_name . and can be reloaded with xload .

For new graphics xsave(file_name,win_num) use preferabily save(file_name,scf(win_num)) .

Examples

    //new style
    set figure_style new
    t=0:0.01:10;
    subplot(211),plot2d(t,sin(t))
    subplot(212),plot2d(t,sin(3*t))
    save(TMPDIR+'/foo.scg',gcf())
    clf()
    load(TMPDIR+'/foo.scg')

    a=gca();
    curve=a.children.children; //handle on the curve
    save(TMPDIR+'/foo.scg',curve)
    delete(curve)
    load(TMPDIR+'/foo.scg')

    //old style
    set figure_style old
    t=0:0.01:10;
    subplot(211),plot2d(t,sin(t))
    subplot(212),plot2d(t,sin(3*t))
    xsave(TMPDIR+'/foo.scg')
    xbasc()
    set figure_style old
    xload(TMPDIR+'/foo.scg')

See Also

xload , save , load ,

Author

J.Ph.C.


xsegs

Scilab Function
Last update : 08/06/2005

xsegs - dessine des segments non connectés

Calling Sequence

xsegs(xv,yv,[style])

Parameters

  • xv,yv : matrices de la même taille.
  • style : vecteur ou scalaire. Si style est un scalaire positif, il donne la couleur pour tous les segments. Si style est négatif la couleur courante est utilisé. Si style est un vecteur, alors style(i) donne la couleur du segment i .

Description

xsegs dessine un ensemble de segments déconnectés donnés par xv et yv . Si xv et yv sont des matrices elles sont considérées comme des vecteurs (par concaténation de leurs colonnes). Les coordonnées des deux points définissant un segment sont données par les valeurs consécutives des termes de xv et yv :

(xv(i),yv(i))-->(xv(i+1),yv(i+1)) .

Par exemple, en utilisant des matrices de taille (2,n) :

xv=[xi_1 xi_2 ...; xf_1 xf_2 ...] yv=[yi_1 yi_2 ...; yf_1 yf_2
    ...]

le segment numéro k est défini par : (xi_k,yi_k)-->(xf_k,yf_k) .

Examples

x=2*%pi*(0:9)/10;
xv=[sin(x);9*sin(x)];
yv=[cos(x);9*cos(x)];
plot2d([-10,10],[-10,10],[-1,-1],"022")
xsegs(xv,yv,1:10)

Author

J.Ph.C.


xselect

Scilab Function
Last update : 16/06/2004

xselect - met la fenêtre graphique courante au premier plan

Calling Sequence

xselect()

Description

xselect met la fenêtre graphique courante au premier plan. Une fenêtre est créée si aucune fenêtre n'existait auparavant. Si la fenêtre graphique est iconifiée, xselect n'a aucun effet.

Author

J.Ph.C.


xsetech

Scilab Function
Last update : 16/06/2004

xsetech - sélectionne la sous-fenêtre d'une fenêtre graphique pour les dessins

Calling Sequence

xsetech(wrect,[frect,logflag])
xsetech(wrect=[...],frect=[..],logflag="..", arect=[...])
xsetech()

Parameters

  • wrect : vecteur de taille 4, définition de la sous-fenêtre
  • frect : vecteur de taille 4.
  • logflag : chaîne de caractères de taille 2 "xy", où x et y peuvent être "n" ou "l". "n" pour échelle normale et "l" pour échelle logarithmique. x pour axe des x et y pour axe des y.
  • arect : vecteur de taille 4.

Description

xsetech est principalement utilisée pour définir la sous-fenêtre d'une fenêtre graphique, à utiliser pour les dessins. La sous-fenêtre est définie par wrect=[x,y,w,h] (point en haut à gauche, largeur, hauteur). Les valeurs dans wrect sont spécifiées sous forme de proportions de la largeur et de la hauteur de la fenêtre graphique courante. Par exemple wrect=[0,0,1,1] signifie que toute la fenêtre graphique sera utilisée, et wrect=[0.5,0,0.5,1] signifie que l'on sélectionne la moitié droite de la fenêtre graphique.

xsetech permet aussi de définir l'échelle graphique pour les dessins 2D et peut être utilisée préalablement à des commandes nécessitant que l'échelle soit déjà définie (par exemple strf="x0z" ou frameflag=0 dans plot2d ).

frect=[xmin,ymin,xmax,ymax] est utilisé pour changer l'échelle graphique et est similaire à l'argument rect de plot2d . Si frect n'est pas donné la valeur courante de l'échelle graphique n'est pas modifiée. La valeur par défaut de rect est [0,0,1,1] (à la création de la fenêtre, ou par exemple après un xset('default') ou après effacement complet de la fenêtre avec xbasc() ).

arect=[x_gauche, x_droite, y_haut, y_bas] est utilisé pour définir le cadre dans la sous-fenêtre. Le cadre est spécifié (comme wrect ) en utilisant des proportions de la largeur et de la hauteur de la sous-fenêtre courante. La valeur par défaut est 1/8*[1,1,1,1] . Si arect n'est pas donné le cadre courant n'est pas modifié.

Examples

// pour avoir une explication des paramètres de xsetech() taper :
exec('SCI/demos/graphics/xsetechfig.sce');

// On coupe la fenêtre en deux
// D'abord on choisit la première sous-fenêtre
// et l'échelle
xsetech([0,0,1.0,0.5],[-5,-3,5,3])
// on appelle plot2d avec l'option "001" pour utiliser l'échelle
// choisie par xsetech
plot2d([1:10]',[1:10]',1,"001"," ")
// on choisit la deuxième sous-fenêtre
xsetech([0,0.5,1.0,0.5])
// l'échelle est [0,0,1,1] par défaut
// on la change avec l'argument rect de plot2d
plot2d([1:10]',[1:10]',1,"011"," ",[-6,-6,6,6])
// 4 dessins sur une seule fenêtre
xbasc()
xset("font",2,0)
xsetech([0,0,0.5,0.5]); plot3d()
xsetech([0.5,0,0.5,0.5]); plot2d()
xsetech([0.5,0.5,0.5,0.5]); grayplot()
xsetech([0,0.5,0.5,0.5]); histplot()
// retour aux valeurs par défaut
xsetech([0,0,1,1])
// Un dessin avec arect change
xbasc()
xset("default")
xsetech(arect=[0,0,0,0])
x=1:0.1:10;plot2d(x',sin(x)')
xbasc()
xsetech(arect=[1/8,1/8,1/16,1/4])
x=1:0.1:10;plot2d(x',sin(x)')
xbasc()
xset("default")

See Also

xgetech , subplot , isoview , square ,

Author

J.Ph.C.


xsetm

Scilab Function
Last update : 16/06/2004

xsetm - boîte de dialogue pour changer des valeurs du contexte graphique

Calling Sequence

xsetm()

Description

xsetm() est identique à xset() .

See Also

xset ,

Author

J.Ph.C.


xset

Scilab Function
Last update : 16/12/2005

xset - change des valeurs du contexte graphique

Calling Sequence

xset(choice-name,x1,x2,x3,x4,x5)
xset()

Parameters

  • choice-name : chaîne de caractères
  • x1,...,x5 : dépend de choice-name

Description

Remarque Importante : Les versions Scilab 4.x seront les dernières à fonctionner avec l'ancien mode graphique.

xset est utilisée pour changer des valeurs du contexte graphique de la fenêtre graphique courante.

Quand elle est appelée sans argument, une boîte de dialogue est affichée avec les valeurs courantes et des changements peuvent être effectués à l'aide de boutons.

Utiliser xset() pour afficher ou changer la couleur courante, le marqueur ou la police.

xset("alufunction",number): utilisé pour changer l'opérateur logique de dessin L'opérateur est choisi avec x1 . Les valeurs habituelles sont : 3 pour la copie (par défaut), 6 pour le ou exclusif (pour faire des animations) et 0 pour effacer. Voir alufunctions pour plus de détails.
xset("auto clear","on"|"off"): Met "on" ou "off" le mode d'effacement automatique des graphiques. Quand le mode est "on", les dessins successifs ne sont pas superposés, i.e. la commande xbasc() (effacement de la fenêtre graphique et effacement des graphiques enregistrés) est exécutée avant chaque commande graphique de haut niveau (plot2d par exemple). La valeur par défaut est "off".
xset("background",color): Change la couleur d'arrière plan de la fenêtre graphique courante. La fenêtre graphique courante désigne la zone des axes où les dessins sont dessinés, pas la figure entière.
xset("clipping",x,y,w,h): Définit la zone de clipping (la zone de la fenêtre graphique où les dessins peuvent être dessinés) comme le rectangle (x,y,w,h) (point en haut à gauche, largeur, hauteur). Cette fonction utilise l'échelle courante de la fenêtre graphique.
xset("color",value): Définit la couleur par défaut de tracé de ligne, de remplissage, de texte, pour toutes les fonctions de dessin. value est un entier projeté sur l'intervalle [0,whiteid]. 0 est utilisé pour le noir et whiteid pour le blanc. La valeur de whiteid peut être obtenue avec xget("white") .
xset("colormap",cmap): Définit la table des couleurs à partir d'une matrice m x 3. m est le nombre de couleurs. La couleur numéro i est donnée comme le triplet cmap(i,1), cmap(i,2), cmap(i,3) correspondant respectivement aux intensités de rouge, vert et bleu, comprises entre 0 et 1.
xset("dashes",i): en mode noir et blanc ( xset("use color",0) ), choisit le style de pointillé numéro i (0 pour une ligne continue). En mode couleur ( xset("use color",1) ) cette commande est utilisée pour choisir la couleur du marqueur, des lignes et du texte. Ce mot-clé est obsolète, utiliser xset('color',i) et xset('line style',i) à la place.
xset("default"): Réinitialise le contexte graphiques aux valeurs par défaut.
xset("font",fontid,fontsize) : choisit la police courante et sa taille.Noter que fontsize s'applique aussi à toutes les polices autres que fontid .
xset("font size",fontsize): Choisit la taille des polices.
xset("foreground",color): Choisit la couleur de premier plan pour la fenêtre graphique courante.
xset("fpf",string): Change le format des nombres affichés sur les courbes de niveau, où string précise le format comme en langage C (par exemple string="%.3f" ). Utiliser string="" pour revenir au format par défaut.
xset("hidden3d",colorid) : Choisit la couleur des parties arrières dans la fonction plot3d. colorid=0 supprime l'affichage des parties arrières des objets 3D. Il s'agit d'une technique dénommée 'culling' et permet d'accélérer le rendu des surfaces fermées.
xset("line mode",type): Cette fonction est utilisée pour changer le mode de dessin des lignes. Mode absolu pour type=1 et relatif avec type=0. (attention : le mode type=0 est buggé)
xset("line style",value): Choisit le style de ligne (1: continu, >1 pour les pointillés).
xset("mark",markid,marksize): Choisit le marqueur ainsi que sa taille. Utiliser xset() pour voir les marqueurs. Noter que marksize s'applique aussi à tous les marqueurs autres que markid .
xset("mark size",marksize): Choisit la taille de marqueur
xset("pattern",value): Choisit le motif pour les fonctions de remplissage. value est un entier projeté sur l'intervalle [0,whiteid]. 0 est utilisé pour le noir et whiteid pour le blanc. La valeur de whiteid peut être obtenue avec xget("white") . "pattern" est équivalent à "color".
xset("pixmap",flag)Si flag=0 les graphiques sont dessinés directement sur l'écran. Si flag=1 les graphiques sont dessinés sur un pixmap et sont affichés à l'écran avec la commande xset("wshow") . Le pixmap est effacé avec la commande xset("wwpc") . Noter que la commande xbasc() efface aussi le pixmap.
xset("thickness",value): Choisit l'épaisseur des lignes en pixels (0 et 1 = épaisseur de 1 pixel).
xset("use color",flag)Si flag=1 alors xset("pattern",.) ou xset("dashes",.) changent la couleur de dessin ou de remplissage. Si flag=0 on passe en mode pointillés et noir et blanc.
xset("viewport",x,y): Choisit la position de la fenêtre glissante.
xset("wdim",width,height): Choisit la largeur et la hauteur de la fenêtre graphique courante. Cette option n'est pas prise en compte par le pilote PostScript.
xset("wpdim",width,height): Choisit (en pixels) la largeur et la hauteur de la fenêtre graphique courante physique (qui peut être différente de la taille réelle en mode wresize=1). Cette option n'est pas prise en compte par le pilote PostScript.
xset("window",window-number): Choisit la fenêtre window-number comme fenêtre graphique par défaut et crée cette fenêtre si elle n'existe pas.
xset("wpos",x,y): Choisit la position (en pixels) du point en haut à gauche de la fenêtre graphique.
xset("wresize",flag)Si flag=1 alors les graphiques sont automatiquement redimensionnés de manière à remplir la fenêtre graphique.
xdel();xset("wresize",1);plot2d();xset("wdim",1000,500)

Si flag=0 l'échelle des graphiques est inchangée quand la fenêtre est redimensionnée. Le "panner" en haut à gauche de la fenêtre ou les flèches du clavier peuvent être utilisées pour faire glisser le contenu de la fenêtre.

xdel();plot2d();xset("wresize",0);xset("wdim",1000,500)
xset("wshow"): Voir xset("pixmap",1) ci-dessus.
xset("wwpc"): Voir xset("pixmap",1) ci-dessus.

See Also

colormap , xget , getcolor , getsymbol ,

Author

J.Ph.C.


xstringb

Scilab Function
Last update : 16/06/2004

xstringb - dessine des chaînes de caractères dans une boîte

Calling Sequence

xstringb(x,y,str,w,h,[option])

Parameters

  • x,y,w,h : vecteur de 4 scalaires définissant la boîte
  • str : matrice de chaînes de caractères.
  • option : chaîne de caractères.

Description

xstringb dessine la matrice de chaînes de caractères str centrée dans le le rectangle rect=[x,y,w,h] (point en haut à gauche, largeur, hauteur) dans l'échelle graphique courante. Si option est donné avec la valeur "fill" , la taille de la police est calculée de manière à remplir le rectangle au maximum.

Taper xstringb() pour voir une démonstration de la fonction.

Examples

str=["Scilab" "n''est ";"pas" "Matlab"];
plot2d(0,0,[-1,1],"010"," ",[0,0,1,1]);
r=[0,0,1,0.5];
xstringb(r(1),r(2),str,r(3),r(4),"fill");
xrect(r(1),r(2)+r(4),r(3),r(4))
r=[r(1),r(2)+r(4)+0.01,r(3),r(4)/2];
xrect(r(1),r(2)+r(4),r(3),r(4))
xstringb(r(1),r(2),str,r(3),r(4),"fill");
r=[r(1),r(2)+r(4)+0.01,r(3),r(4)/2];
xrect(r(1),r(2)+r(4),r(3),r(4))
xstringb(r(1),r(2),str,r(3),r(4),"fill");

See Also

titlepage , xstring , xstringl , xtitle ,

Author

J.Ph.C.


xstringl

Scilab Function
Last update : 28/11/2005

xstringl - calcule les dimensions d'une boîte entourant des chaînes de caractères

Calling Sequence

rect=xstringl(x,y,str,[fontId,fontSize])

Parameters

  • rect : vecteur de 4 scalaires définissant la boîte
  • x,y : scalaires réels, coordonnées du point en bas à gauche des chaînes de caractères.
  • str : matrice de chaînes de caractères.
  • fonId : un entier specifiant le type de la fonte.
  • fontSize : un entier specifiant la taille de la fonte.

Description

xstringl renvoie dans rect=[x,y,w,h] (point en haut à gauche, largeur, hauteur) les dimensions d'un rectangle dans l'échelle graphique courante entourant les chaînes de caractères str dessinées à la position x,y (point en bas à gauche).

Le résultat est approximatif avec le pilote PostScript.

Examples

plot2d([0;1],[0;1],0)
str=["Scilab" "n''est ";"pas" "Matlab"];
r=xstringl(0.5,0.5,str)
xrects([r(1) r(2)+r(4) r(3) r(4)]')
xstring(r(1),r(2),str)

plot2d([0;1],[0;1],0)
str=["Scilab" "n''est ";"pas" "Matlab"];
r2 = xstringl(0.5,0.5,str,2,5)
xrects([r2(1) r2(2)+r2(4) r2(3) r2(4)]')
xstring(r2(1),r2(2),str)

e=gce();
e.children(1).font_size = 5;
e.children(1).font_style = 2;
e.children(2).font_size = 5;
e.children(2).font_style = 2;

See Also

titlepage , xstring , xstringl , xtitle , stringbox ,

Author

J.Ph.C.


xstring

Scilab Function
Last update : 16/06/2004

xstring - dessine des chaînes de caractères

Calling Sequence

xstring(x,y,str,[angle,box])

Parameters

  • x,y : scalaires réels, coordonnées du point en bas à gauche des chaînes de caractères.
  • str : matrice de chaînes de caractères.
  • angle : réel, angle en degrés dans le sens horaire (0 par défaut).
  • box : entier, 0 par défaut.

Description

xstring dessine la matrice de chaînes de caractères str à la position x,y (point en bas à gauche de la chaîne) dans l'échelle graphique courante : chaque ligne de la matrice correspond à une ligne de texte et les éléments d'une ligne sont considérés comme des mots à séparer par un espace. Si angle est donné, il définit l'angle en degrés utilisé pour dessiner les chaînes de caractères. Si box vaut 1 et que angle vaut 0, une boîte est dessinée autour des chaînes de caractères.

Examples

plot2d([0;1],[0;1],0)
xstring(0.5,0.5,["Scilab" "n''est ";"pas" "Matlab"])
// autre exemple
alphabet=["a" "b" "c" "d" "e" "f" "g" ..
          "h" "i" "j" "k" "l" "m" "n" ..
          "o" "p" "q" "r" "s" "t" "u" ..
          "v" "w" "x" "y" "z"];
xbasc()
plot2d([0;1],[0;2],0)
xstring(0.1,1.8,alphabet)     // alphabet
xstring(0.1,1.6,alphabet,0,1) // alphabet dans une boîte
xstring(0.1,1.4,alphabet,20)  // angle
xset("font",1,1)              // police "symbol"
xstring(0.1,0.1,alphabet)
xset("font",1,3)              // changement de la taille de police
xstring(0.1,0.3,alphabet)
xset("font",1,24); xstring(0.1,0.6,"a") // un grand alpha
xset("default")

See Also

titlepage , xnumb , xstringb , xstringl , xtitle ,

Author

J.Ph.C.


xtape

Scilab Function
Last update : 16/06/2004

xtape - détermine le processus d'enregistrement des graphiques

Calling Sequence

xtape(str,[num,rect])

Parameters

  • str : chaîne de caractères, "on", "clear", "replay" ou "replaysc".
  • num : entier.
  • rect : vecteur ligne de taille 4.

Description

xtape est utilisée pour déterminer le processus d'enregistrement des graphiques :

xtape("on") sélectionne le pilote "Rec" qui enregistre toutes les opérations graphiques.

xtape("clear",num) efface la fenêtre graphique num ainsi que les graphiques enregistrés.

xtape("replay",num) ré-exécute les ordres graphiques enregistrés dans la fenêtre num .

xtape("replaysc",num,rect) redessine le contenu de la fenêtre graphique num en utilisant rect=[xmin,ymin,xmax,ymax] comme bornes.

See Also

driver , replot , xbasc , xbasr ,

Author

J.Ph.C.


xtitle

Scilab Function
Last update : 03/02/2006

xtitle - add titles on a graphics window

Calling Sequence

xtitle(title,[x_label,[y_label,[z_label]]],<opts_args>)

Parameters

  • title,x_label,y_label, z_label : matrices of strings.
  • <opt_args> : a sequence of statements key1=value1, key2=value2 , ... where keys may be boxed (see below). In this case, the order has no special meaning.
  • boxed : an integer value. If it is 1, a box is drawn around each title.

Description

xtitle add titles on a 2D or 3D plot. title is the general title and x_label, y_label and z_label are the titles on the three axis. If the arguments are matrices, each line of the matrices is displayed on a different line.

Enter the command xtitle() to see a demo.

Examples

// draw a surface
plot3d() ;
// puts the titles
xtitle( 'My surface is blue', 'X axis', 'Y axis', 'Z axis' ) ;
// draw a box around the titles
xtitle( 'My surface is blue', 'X axis', 'Y axis', 'Z axis', boxed = 1 ) ;

See Also

titlepage label_properties ,

Author

J.Ph.C.


zgrid

Scilab Function
Last update : 12/01/2004

zgrid - zgrid plot

Calling Sequence

zgrid()

Description

plots z-plane grid lines: lines of constant damping factor (zeta) and natural frequency (Wn) are drawn in within the unit Z-plane circle.

Iso-frequency curves are shown in frequency*step on the interval [0,0.5]. Upper limit corresponds to Shannon frequency ( 1/dt > 2*f ) .

See Also

frep2tf , freson ,


zoom_rect

Scilab Function
Last update : 16/11/2004

zoom_rect - zoom a selection of the current graphic figure

Calling Sequence

zoom_rect()
zoom_rect(rect)

Parameters

  • rect : vector of size 4 [xmin,ymin,xmax,ymax] give the rectangle to be zoomed.

Description

zoom_rect is used to zoom a given rectangle of the current graphic figure: the rectangle(s) formed by the intersection of the given rectangle with the axes boxe(s) are zoomed, i.e. the rectangle(s) content are enlarged to fill the axes boxe(s). The selected rectangle for each axes is stored in the zoom_box property of associated the axes entity (see axes_properties ).

Without argument, the user is required to select the rectangle with the mouse. If specified, the rect argument should contain the coordinates ( using the current graphics scale) of two opposite corner of the rectangle.

The zoom_rect function corresponds to the Zoom menu.

Examples

    clf()
    x=0:0.01:6*%pi;
    plot2d(x,sin(x^2))
    zoom_rect([16,-1,18,1])
    //more zoom
    zoom_rect([16,0,16.2,1])
    //back to the original
    unzoom()
    // zooming using axes_properties
    a=gca();
    a.zoom_box=[16,0,16.2,1];
    a.zoom_box=[];

    //zooming subplots accordingly
    clf()
    x=0:0.01:6*%pi;
    subplot(211)
    plot2d(x,cos(x))
    subplot(212)
    plot2d(x,cos(2*x))
    rect=[3 -2 7 10]; //a rectangle specified in the current axes (last one) coordinates
    zoom_rect(rect)
    unzoom()
    //set the global underlying axes as current
    f=gcf();set('current_axes',f.children($))
    rect=[0.4 0 0.6 1] //a rectangle specified in ratio of the window size
    zoom_rect(rect)
    rect=[0.4 0.2 0.6 0.8]; //a rectangle specified in ratio of the window size
    zoom_rect(rect)

See Also

unzoom , axes_properties ,

Author

Serge Steer INRIA


GlobalProperty

Scilab Function
Last update : 08/06/2005

GlobalProperty - to customize the objects appearance (curves, surfaces...) in a plot or surf command.

Calling Sequence

None. The GlobalProperty is an optional argument that can be used inside a plot or surf command. It allows a global customization of all the new plotted lines (respectivly surfaces). It has to be given as a couple {PropertyName, PropertyValue}. Several couples can be set at the same time in a plot or surf call.
PropertyName must be a string defining the property to set.The PropertyValue can be a real, integer or string (scalar or matrix) depending on the type of property used. For example, to specify a red (color) longdash-dot (line style) with diamond marker (marker), the sequence should be : 'Colo','red','LineSt','-.','Marker','diam'.
As you can see, a full complete spelling of each property name and value is not required but those arguments, specified in any order, must remain unambiguous. Furthermore, the string specification is not case sensitive. GlobalProperty is predominant on all LineSpec previously stated.

Description

Here is a complete list of the PropertyName you can specify (using plot or surf ) and their available associated PropertyValue . If not specified, those properties are available for both Polyline and Fac3d objects (created respectivly by plot or surf) and, as previously said, they are applied to the new created objects (lines or surfaces).

Sometimes, you may have two PropertyName correponding to one property : the first one is the equivalent default Matlab name, the second is the default name used by Scilab (i.e.: Color or Foreground for a line, see below).

CData or ColorData: a real matrix specifiying the color at every points defined by Z matrix. This property is linked to the object's data.color property (see surface_properties ). Note that this property is available for surfaces only.
CDataMapping or ColorDataMapping: a string with value 'scaled' or 'direct' . If a data.color is set, each index color data specifies a single value for each vertex. cdata_mapping determines wether those indices are scaled to map linearly into the current colormap ( 'scaled' mode) or point directly into this colormap ( 'direct ' mode). This property is usefull when color_flag equals 2 , 3 or 4 . Note that this property exists only with Fac3d entities. Note also that plot3d has 'direct' mode by default and surf has 'scaled' mode by default.
Clipping: a string "on" or "off" defining the clipping mode ( "on" by default). It is equivalent to the clip_state property. This field contains the visible property (see polyline_properties ). Note that this property is not yet available for surface entities.
Color or Foreground: a string defining a known color (see color_list ) or a 1 x 3 (or 3 x 1 ) RGB vector defining a color number. Color number is given as a 3-uple R , G , B corresponding respectively to red, green and blue intensity between 0 and 1. This property is linked to the object's foreground property (see polyline_properties ). Warning : Color is not available for surfaces objects. The Foreground property exists for surfaces objects but is linked to the Matlab EdgeColor property (see surface_properties ).
EdgeColor or Foreground: a string defining a known color (see color_list ) or a 1 x 3 (or 3 x 1 ) RGB vector defining a color number. Color number is given as a 3-uple R , G , B corresponding respectively to red, green and blue intensity between 0 and 1. This property is linked to the surface foreground property (see surface_properties ). Warning : For polyline objects, the Foreground property exists with a different meaning (see above) and EdgeColor does not exist at all.
FaceColor: a string with value 'none' , 'flat' or 'interp' specifying the way the facet's color are rendered. When 'none' is selected, a mesh of the surface is drawn; if 'flat' (deault mode) is set, the Fac3d color.data values determine one color per facet using the color of the first vertex of the facet. If the value is 'interp' , an interpolated shading is done on the surface using color.data to determine a color at each vertex of each facet.
LineStyle: This property value should be a string defining a line style. This property is linked to tje object's line_style property (see polyline_properties or surface_properties ).
Specifier | Line Style
- Solid line (default)
-- Dashed line
: Dotted line
-. Dash-dotted line
none | No line
Marker or MarkStyle: A string defining the marker type. Note that if you specify a marker wihtout a line style, both line (with default solid mode enabled) and marker are drawn.This property is linked to the object's mark_style and mark_mode properties (see polyline_properties or surface_properties ).
Specifier | Marker Type
+ Plus sign
o | Circle
* Asterisk
. Point
x | Cross
'square' or 's' | Square
'diamond' or 'd' | Diamond
^ Upward-pointing triangle
v | Downward-pointing triangle
> Right-pointing triangle
< Left-pointing triangle
'pentagram' | Five-pointed star (pentagram)
'none' | No marker (default)
MarkerEdgeColor or MarkForeground: a string defining a known color (see color_list) or a 1 x 3 (or 3 x 1 ) RGB vector defining a color number. Color number is given as a 3-uple R , G , B corresponding respectively to red, green and blue intensity between 0 and 1. This property is linked to the object's mark_foreground property (see polyline_properties or surface_properties ).
MarkerFaceColor or MarkBackground: a string defining a known color (see color_list) or a 1 x 3 (or 3 x 1 ) RGB vector defining a color number. Color number is given as a 3-uple R , G , B corresponding respectively to red, green and blue intensity between 0 and 1. This property is linked to the object's mark_background property (see polyline_properties or surface_properties ).
MarkerSize or MarkSize: a scalar defining the marker size in point unit. This property is linked to the object's mark_size property with mark_size_unit enabled to "point" (see polyline_properties or surface_properties ).
Visible: a string "on" or "off" defining the visibility mode ( "on" by default). This property is linked to the object's visible property (see polyline_properties or surface_properties ).
X data: a real vector or matrix (re-)defining the given data for all the plotted lines or surfaces. Concerning dimensions, note that this new data must match all the previous specified X data : that is to say all those data matrices must be of the same dimensions. This property is linked to the object's data.x property (see polyline_properties or surface_properties ).
Y data: a real vector or matrix (re-)defining the given data for all the plotted lines or surfaces. Concerning dimensions, note that this new data must match all the previous specified Y data : that is to say all those data matrices must be of the same dimensions. This property is linked to the object's data.y property (see polyline_properties or surface_properties ).
Z data: when used with plot , a real vector or matrix adding a Z data for all the plotted lines ; with surf , a real matrix (re-)defining the given data for all the surfaces. Concerning dimensions, note that this new data must match all the previous specified X and Y data. This property is linked to the object's data.z property (see polyline_properties or surface_properties ).

Examples

// --------------------
// With the plot command :
// --------------------
x=1:10; // Init.
plot(x,sin(x),'colo','red','linest','-.','marker','>','markeredg','cyan','markerFace','yellow','markersize',5)
clf();

// combinations' order in {PropertyName,PropertyValue} does not matter
plot(x,sin(x),'marker','p','markerfac','cyan','markersiz',10)
clf();

// combination of LineSpec and GlobalProperty shows the GlobalProperty predominance
plot(x,x.*x,'*cya--','color','gr','linestyle','-','marker','sq','markersize',6,'markforegroun','red','markbackgro',[0.2 0.5 0.6])
clf();

//multiple plots with different LineSpecs and finally some global GlobalProperty
clf();
t=0:%pi/20:2*%pi;
plot(t,sin(t),'ro-.',t,cos(t),'cya+',t,abs(sin(t)),'--mo','markstyl','diam')

// --------------------
// With the surf command :
// --------------------

Z= [   0.0001    0.0013    0.0053   -0.0299   -0.1809   -0.2465   -0.1100   -0.0168   -0.0008   -0.0000
    0.0005    0.0089    0.0259   -0.3673   -1.8670   -2.4736   -1.0866   -0.1602   -0.0067    0.0000
    0.0004    0.0214    0.1739   -0.3147   -4.0919   -6.4101   -2.7589   -0.2779    0.0131    0.0020
   -0.0088   -0.0871    0.0364    1.8559    1.4995   -2.2171   -0.2729    0.8368    0.2016    0.0130
   -0.0308   -0.4313   -1.7334   -0.1148    3.0731    0.4444    2.6145    2.4410    0.4877    0.0301
   -0.0336   -0.4990   -2.3552   -2.1722    0.8856   -0.0531    2.6416    2.4064    0.4771    0.0294
   -0.0137   -0.1967   -0.8083    0.2289    3.3983    3.1955    2.4338    1.2129    0.2108    0.0125
   -0.0014   -0.0017    0.3189    2.7414    7.1622    7.1361    3.1242    0.6633    0.0674    0.0030
    0.0002    0.0104    0.1733    1.0852    2.6741    2.6725    1.1119    0.1973    0.0152    0.0005
    0.0000    0.0012    0.0183    0.1099    0.2684    0.2683    0.1107    0.0190    0.0014    0.0000];

clf();
f=gcf();
f.figure_size = [610,724];
subplot(211)
surf(Z,'facecol','interp','ydat',101:110,'edgecol','mage')
subplot(212)
surf(Z,'edgeco','b','marker','d','markersiz',9,'markerfac','k','xdata',-50:-41)

See Also

LineSpec , plot , surf , clf , polyline_properties , surface_properties ,

Author

F.Leray


Graphics

Scilab Function
Last update : 06/07/2004

Graphics - contenu de la librairie graphique

DESSINS 2D

  • plot2d : représentation de courbes dans le plan
  • plot2d2 : représentation d'une fonction constante par morceaux
  • plot2d3 : représentation de courbes dans le plan sous forme de barres verticales
  • plot2d4 : représentation de courbes dans le plan sous forme de flèches
  • fplot2d : représentation d'une courbe définie par une fonction
  • champ : champ de vecteur 2D
  • champ1 : champ de vecteur 2D. Flèches colorées
  • fchamp : champ défini par une équation différentielle du premier ordre
  • contour2d : courbes de niveau d'une surface
  • fcontour2d : courbes de niveau d'une surface (définie par une fonction)
  • grayplot : représentation d'une surface en 2D sous forme de couleurs
  • fgrayplot : représentation d'une surface (définie par une fonction) en 2D sous forme de couleurs
  • Sgrayplot : représentation d'une surface en 2D sous forme de couleurs interpolées
  • Sfgrayplot : représentation d'une surface (définie par une fonction) en 2D sous forme de couleurs interpolées
  • xgrid : ajoute une grille sur un dessin 2D
  • errbar : ajoute des barres d'erreur sur un dessin 2D
  • histplot : dessine un histogramme
  • Matplot : dessin en 2D d'une matrice en pseudo-couleurs

    • DESSINS 3D

  • plot3d : représentation en en couleurs d'une surface
  • plot3d1 : représentation en en couleurs d'une surface
  • fplot3d : représente une surface non paramétrique définie par une fonction
  • fplot3d1 : représente une surface non paramétrique définie par une fonction
  • param3d : représente une courbe paramétrique en 3D
  • param3d1 : représente des courbes paramétriques en 3D
  • contour : courbes de niveau sur une surface en 3D
  • fcontour : courbes de niveau sur une surface en 3D définie par une fonction
  • hist3d : représentation d'un histogramme en 3D
  • genfac3d : calcule les facettes d'une surface non paramétrique
  • eval3dp : calcule les facettes d'une surface paramétrique
  • geom3d : projection 3D vers 2D après un dessin 3D

    • DESSINS DE POLYGONES ET DE LIGNES

  • xpoly : dessine une ligne brisée ou un polygone
  • xpolys : dessine un ensemble de lignes brisées ou de polygones
  • xrpoly : dessine un polygone régulier
  • xsegs : dessine des segments déconnectés
  • xfpoly : remplit un polygone
  • xfpolys : remplit un ensemble de polygones

    • DESSINS DE RECTANGLES

  • xrect : dessine un rectangle
  • xfrect : remplit un rectangle
  • xrects : dessine ou remplit un ensemble de rectangles

    • DESSINS DES ARCS

  • xarc : dessine un arc d'ellipse
  • xarcs : dessine des arcs d'ellipses
  • xfarc : remplit un secteur angulaire d'ellipse
  • xfarcs : remplit des secteurs angulaires d'ellipses

    • DESSINS DE FLÈCHES

  • xarrows : dessine un ensemble de flèches

    • DESSINS DE TEXTES

  • xstring : dessine des chaînes de caractères
  • xstringl : calcule une boîte contenant des chaînes de caractères
  • xstringb : dessine des chaînes de caractères dans une boîte
  • xtitle : ajoute des titres et légendes sur une fenêtre graphique
  • titlepage : ajoute un titre au milieu d'une fenêtre graphique
  • xinfo : affiche une chaîne de caractères dans la sous-fenêtre des messages

    • CADRES ET AXES

  • xaxis : dessine un axe
  • graduate : graduations simplifiées
  • plotframe : dessine un cadre avec axes et mise à l'échelle

    • TRANSFORMATIONS DE COORDONNÉES

  • isoview : échelle isométrique (fonction obsolète)
  • square : échelle isométrique (par changement de la taille de la fenêtre)
  • scaling : transformation affine d'un ensemble de points
  • rotate : rotation d'un ensemble de points
  • xsetech : choix d'une sous-fenêtre graphique
  • subplot : divise la fenêtre graphique en sous-fenêtres
  • xgetech : donne l'échelle graphique courante
  • xchange : transformation de coordonnées réelles vers pixels

    • COULEURS

  • colormap : utilisation des tables de couleurs
  • getcolor : boîte de dialogue pour sélectionner des couleurs dans la table des couleurs
  • addcolor : ajout de nouvelles couleurs à la tables des couleurs
  • graycolormap : table de couleurs du noir au blanc
  • hotcolormap : table de couleurs "chaude" du rouge au jaune

    • CONTEXTE GRAPHIQUE

  • xset : change des valeurs du contexte graphique
  • xget : récupère des valeurs du contexte graphique
  • xlfont : charge une police dans le contexte graphique ou donne la liste des polices
  • getsymbol : boîte de dialogue pour choisir un marqueur (ou symbole)

    • SAUVEGARDE ET CHARGEMENT

  • xsave : sauve les graphiques dans un fichier
  • xload : charge des graphiques sauvés
  • xbasimp : envoie des graphiques à une imprimante Postscript ou un fichier
  • xs2fig : envoie des graphiques dans un fichier au format XFig

    • PRIMITIVES GRAPHIQUES

  • xbasc : efface une fenêtre graphique et les graphiques enregistrés
  • xclear : efface une fenêtre graphique
  • driver : choisit un pilote graphique
  • xinit : initialisation d'un pilote graphique
  • xend : termine une session graphique
  • xbasr : redessine une fenêtre graphique
  • replot : redessine une fenêtre graphique avec de nouvelles bornes
  • xpause : suspend l'exécution de Scilab
  • xselect : met une fenêtre graphique au premier plan
  • xclea : effacement d'un rectangle
  • xclip : définit une zone de clipping
  • xdel : supprime une fenêtre graphique
  • winsid : renvoie la liste des fenêtre graphiques
  • xname : change le nom d'une fenêtre graphique

    • POSITION DE LA SOURIS

  • xclick : attend un clic de souris
  • locate : sélection d'un ensemble de points
  • xgetmouse : renvoie la position courante du pointeur de la souris

    • ÉDITEUR INTERACTIF

  • edit_curv : éditeur graphique interactif
  • gr_menu : éditeur graphique élémentaire
  • sd2sci : conversion d'objets gr_menu en instructions Scilab
  • ged :EDiteur interactif des propriétésdes entités graphiques

    • FONCTIONS GRAPHIQUES EN AUTOMATIQUE

  • bode : diagramme de Bode
  • gainplot : magnitude plot
  • nyquist : Nyquist plot
  • m_circle : M-circle plot
  • chart : Nichols chart
  • black : Black's diagram
  • evans : Evans root locus
  • sgrid : s-plane grid lignes
  • plzr : pole-zero plot
  • zgrid : zgrid plot


LineSpec

Scilab Function
Last update : 08/06/2005

LineSpec - to quickly customize the lines appearance in a plot

Calling Sequence

None. The LineSpec is an optional argument that can be used inside a plot command to customize each new line aspect. It has to be given as a concatenated string containing information about color, line style or markers. It is very usefull to quickly specify such basic line properties.
To specify a red longdash-dot with diamond marker, the string can be 'r-.diam'. As you can see, a full complete spelling of each property value is not required but the string, which is a concatenation (in any order) of these three types of properties , must remain unambiguous. Furthermore, the string specification is not case sensitive.

Description

Here is a complete list of the LineSpec types you can specify (using plot ).

LineStyle: a string defining the line style. This property is linked to the object's line_style property (see polyline_properties ).
Specifier Line Style
- Solid line (default)
-- Dashed line
: Dotted line
-. Dash-dotted line
Color: a string defining the line color. This property is linked to the object's foreground property (see polyline_properties ).
Specifier | Color
r | Red
g | Green
b | Blue
c | Cyan
m | Magenta
y | Yellow
k | Black
w | White
A default color table is used to color plotted curves if you do not specify a color (neither with LineSpec nor with GlobalProperty ). When drawing multiple lines, the plot command automatically cycles through this table. Here are the used colors:
R | G | B
0. | 0. | 1.
0. | 0.5 | 0.
1. | 0. | 0.
0. | 0.75 | 0.75
0.75 | 0. | 0.75
0.75 | 0.75 | 0.
0.25 | 0.25 | 0.25
Marker type: A string defining the marker type. note that if you specify a marker wihtout a line style, only the marker is drawn. This property is linked to the object's mark_style and mark_mode properties (see polyline_properties ).
Specifier | Marker Type
+ Plus sign
o | Circle
* Asterisk
. Point
x | Cross
'square' or 's' | Square
'diamond' or 'd' | Diamond
^ Upward-pointing triangle
v | Downward-pointing triangle
> Right-pointing triangle
< Left-pointing triangle
'pentagram' | Five-pointed star (pentagram)
'none' | No marker (default)

Examples

x=1:0.1:10; // Init.
plot(x,sin(x),'r.->') // plots a dash-dotted line with a right-pointing triangle centered on each points.
clf();

// If you specify a marker wihtout a line style, only the marker is drawn
plot(x,sin(x),'d') // plots a dash-dotted line with a right-pointing triangle centered on each points.

x=1:10; // Init.
// combinations' order does not matter
plot(x,x.*x,'*cya--')

//multiple plots with different LineSpecs
clf();
t=0:%pi/20:2*%pi;
plot(t,sin(t),'ro-.',t,cos(t),'cya+',t,abs(sin(t)),'--mo')

See Also

GlobalProperty , plot , clf ,

Author

F.Leray


Matplot1

Scilab Function
Last update : 04/12/2006

Matplot1 - 2D plot of a matrix using colors

Calling Sequence

Matplot1(a,rect)

Parameters

  • a : real matrix of size (n1,n2).
  • rect : [xmin,ymin,xmax,ymax]

Description

The entries of matrix int(a) are used as colormap entries in the current colormap. rect specify a rectangle in the current scale and the matrix is drawn inside this rectangle. Each matrix entry will be rendered as a small rectangle filled with its associated color.

Examples

//--- first example
set figure_style new;
clf();
ax=gca();//get current axes handle
ax.data_bounds=[0,0;10,10];//set the data_bounds
ax.box='on'; //draw a box
a=5*ones(11,11); a(2:10,2:10)=4; a(5:7,5:7)=2;
// first matrix in rectangle [1,1,3,3]
Matplot1(a,[1,1,3,3])
a=ones(10,10); a= 3*tril(a)+ 2*a;
// second matrix in rectangle [5,6,7,8]
Matplot1(a,[5,6,7,8])

//--- second example  (animation)
n=100;

set figure_style new;
clf();
f=gcf();//get current figure handle
f.pixmap='on';//double buffer mode
ax=gca();//get current axes handle
ax.data_bounds=[0,0;10,10];//set the data_bounds
ax.box='on'; //draw a box
show_pixmap()
for k=-n:n,
  a=ones(n,n);
  a= 3*tril(a,k)+ 2*a;
  a= a + a';
  k1= 3*(k+100)/200;
  if k>-n then delete(gce()),end
  Matplot1(a,[k1,2,k1+7,9])
  show_pixmap() //send double buffer to screen
end

See Also

colormap , plot2d , Matplot , grayplot , Matplot_properties ,

Author

J.Ph.C.


Matplot_properties

Scilab Data type
Last update : 13/12/2005

Matplot_properties - description of the Matplot entities properties

Description

The Matplot entity is a leaf of the graphics entities hierarchy. It represents 2D plots of surface using colors and images (see Matplot and Matplot1 ).

parent: This property contains the handle of the parent. The parent of the Matplot entity should be of the type "Axes" .
children: This property contains a vector with the children of the handle. However, Matplot handles currently do not have any children .
visible: This field contains the visible property value for the entity . It should be "on" or "off" . By default, the plot is visible, the value's property is "on" . If "off" the plot is not drawn on the screen.
data: This field defines a [ m x n ] color data matrix using the current colormap. The color associated to color(i,j) is used do draw a small square of length 1 with center at location (x=j,y=(m-i+1)) .
user_data: This field can be use to store any scilab variable in the Matplot data structure, and to retreive it.

Examples

   set("figure_style","new") //create a figure

   Matplot((1:xget("lastpattern")))
   e=gce(); // get current entity

   e.data=e.data($:-1:1) // reverse order

See Also

set , get , delete , grayplot , Matplot , Matplot1 , graphics_entities , grayplot_properties ,

Author

F.Leray


Matplot

Scilab Function
Last update : 13/12/2005

Matplot - 2D plot of a matrix using colors

Calling Sequence

Matplot(a,[strf,rect,nax])
Matplot(a,<opt_args>)

Parameters

  • a : real matrix of size (n1,n2).
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following:
    • rect : sets the bounds of the plot. If this key is given and neither frameflag nor strf is given then the y character of strf is supposed to be 7 . See below for value.
    • nax : sets the grids definition. If this key is given and neither axesflag nor strf is given then the z character of strf is supposed to be 1 . See below for value.
    • frameflag : specifies how the frame of the plot is computed. The value is an integer ranging from 0 to 8. It corresponds to the y character of strf . See below.
    • axesflag : specifies what kind of axes are drawn around the plot. The value is an integer ranging from 0 to 5. It corresponds to the z character of strf . See below.
  • strf : is a string of length 3 "xyz" .
    • default The default is "081" .
    • x : controls the display of captions.
      • x=0 : no caption.
      • x=1 : captions are displayed. They are given by the optional argument leg .
    • y : controls the computation of the actual coordinate ranges from the minimal requested values. Actual ranges can be larger than minimal requirements.
      • y=0 : no computation, the plot use the previus (or default) scale
      • y=1 : from the rect arg
      • y=2 : from the min/max of the x, y datas
      • y=3 : built for an isometric scale from the rect arg
      • y=4 : built for an isometric plot from the min/max of the x, y datas
      • y=5 : enlarged for pretty axes from the rect arg
      • y=6 : enlarged for pretty axes from the min/max of the x, y datas
      • y=7 : like y=1 but the previus plot(s) are redrawn to use the new scale
      • y=8 : like y=2 but the previus plot(s) are redrawn to use the new scale
    • z : controls the display of information on the frame around the plot. If axes are requested, the number of tics can be specified by the nax optional argument.
      • z=0 : nothing is drawn around the plot.
      • z=1 : axes are drawn, the y=axis is displayed on the left.
      • z=2 : the plot is surrounded by a box without tics.
      • z=3 : axes are drawn, the y=axis is displayed on the right.
      • z=4 : axes are drawn centred in the middle of the frame box.
      • z=5 : axes are drawn so as to cross at point (0,0) . If point (0,0) does not lie inside the frame, axes will not appear on the graph.
  • rect : This argument is used when the second character y of argument strf is 1, 3 or 5. It is a row vector of size 4 and gives the dimension of the frame: rect=[xmin,ymin,xmax,ymax] .
  • nax : This argument is used when the third character z of argument strf is 1. It is a row vector with four entries [nx,Nx,ny,Ny] where nx ( ny ) is the number of subgraduations on the x (y) axis and Nx ( Ny ) is the number of graduations on the x (y) axis.

Description

The entries of matrix int(a) are used as colormap entries in the current colormap. The color associated to a(i,j) is used do draw a small square of length 1 with center at location (x=j,y=(n1-i+1)) .

Enter the command Matplot() to see a demo.

Examples

Matplot([1 2 3;4 5 6])
clf()
// draw the current colormap
Matplot((1:xget("lastpattern")))

See Also

colormap , plot2d , Matplot1 , Matplot_properties ,

Author

J.Ph.C.


Sfgrayplot

Scilab Function
Last update : 08/06/2005

Sfgrayplot - smooth 2D plot of a surface defined by a function using colors

Calling Sequence

Sfgrayplot(x,y,f,<opt_args>)
Sfgrayplot(x,y,f [,strf, rect, nax, zminmax, colminmax, mesh, colout])

Parameters

  • x,y : real row vectors of size n1 and n2.
  • f : scilab function (z=f(x,y))
  • <opt_args> : This represents a sequence of statements key1=value1, key2=value2 ,... where key1 , key2,... can be one of the following: strf, rect, nax, zminmax, colminmax, mesh, colout (see plot2d for the 3 first and fec for the 4 last).
  • strf,rect,nax : see plot2d .
  • zminmax, colminmax, mesh, colout : see fec .

Description

Sfgrayplot is the same as fgrayplot but the plot is smoothed. The function fec is used for smoothing. The surface is plotted assuming that it is linear on a set of triangles built from the grid (here with n1=5, n2=3):

             _____________
             | /| /| /| /|
             |/_|/_|/_|/_|
             | /| /| /| /|
             |/_|/_|/_|/_|

The function colorbar may be used to see the color scale (but you must know (or compute) the min and max values).

Instead of Sfgrayplot, you can use Sgrayplot and this may be a little faster.

Enter the command Sfgrayplot() to see a demo.

Examples

// example #1: plot 4 surfaces
function z=surf1(x,y), z=x*y, endfunction
function z=surf2(x,y), z=x^2-y^2, endfunction
function z=surf3(x,y), z=x^3+y^2, endfunction
function z=surf4(x,y), z=x^2+y^2, endfunction
xbasc()
xset("colormap",[jetcolormap(64);hotcolormap(64)])
ng = get("figure_style") == "new";
x = linspace(-1,1,60);
y = linspace(-1,1,60);
if ng then, drawlater(), end
subplot(2,2,1)
   colorbar(-1,1,[1,64])
   Sfgrayplot(x,y,surf1,strf="041",colminmax=[1,64])
   xtitle("f(x,y) = x*y")
subplot(2,2,2)
   colorbar(-1,1,[65,128])
   Sfgrayplot(x,y,surf2,strf="041",colminmax=[65,128])
   xtitle("f(x,y) = x^2-y^2")
subplot(2,2,3)
   colorbar(-1,2,[65,128])
   Sfgrayplot(x,y,surf3,strf="041",colminmax=[65,128])
   xtitle("f(x,y) = x^3+y^2")
subplot(2,2,4)
   colorbar(0,2,[1,64])
   Sfgrayplot(x,y,surf4,strf="041",colminmax=[1,64])
   xtitle("f(x,y) = x^2+y^2")
if ng then, drawnow(), end
xselect()

// example #2: plot surf3 and add some contour lines
function z=surf3(x,y), z=x^3+y^2, endfunction
xbasc()
x = linspace(-1,1,60);
y = linspace(-1,1,60);
xset("colormap",hotcolormap(128))
ng = get("figure_style") == "new";
if ng then, drawlater(), end
colorbar(-1,2)
Sfgrayplot(x,y,surf3,strf="041")
z = (x')^3*ones(y) + ones(x')*y^2;
fcontour2d(x,y,surf3,[-0.1, 0.025, 0.4],style=[1 1 1],strf="000")
xtitle("f(x,y) = x^3+y^2")
if ng then, drawnow(), end
xselect()

// example #3: plot surf3 and use zminmax and colout optional arguments
//             to restrict the plot for -0.5<= z <= 1
function z=surf3(x,y), z=x^3+y^2, endfunction
xbasc()
x = linspace(-1,1,60);
y = linspace(-1,1,60);
xset("colormap",jetcolormap(128))
ng = get("figure_style") == "new";
if ng then, drawlater(), end
zminmax = [-0.5 1]; colors=[32 96];
colorbar(zminmax(1),zminmax(2),colors)
Sfgrayplot(x, y, surf3, strf="041", zminmax=zminmax, colout=[0 0], colminmax=colors)
z = (x')^3*ones(y) + ones(x')*y^2;
fcontour2d(x,y,surf3,[-0.5, 1],style=[1 1 1],strf="000")
xtitle("f(x,y) = x^3+y^2, with parts under z = -0.5 and upper z = 1 removed")
if ng then, drawnow(), end
xselect()

See Also

fec , fgrayplot , grayplot , Sgrayplot ,

Author

J.Ph.C.


Sgrayplot

Scilab Function
Last update : 13/12/2005

Sgrayplot - smooth 2D plot of a surface using colors

Calling Sequence

Sgrayplot(x,y,z,<opt_args>)
Sgrayplot(x,y,z [,strf, rect, nax, zminmax, colminmax, mesh, colout])

Parameters

  • x,y : real row vectors of size n1 and n2.
  • z : real matrix of size (n1,n2). z(i,j) is the value of the surface at the point (x(i),y(j)).
  • <opt_args> : This represents a sequence of statements key1=value1,key2=value2 ,... where key1 , key2,... can be one of the following: strf, rect, nax, zminmax, colminmax, mesh, colout (see plot2d for the 3 first and fec for the 4 last).
  • strf,rect,nax : see plot2d .
  • zminmax, colminmax, mesh, colout : see fec .

Description

Sgrayplot is the same as grayplot but the plot is smoothed. The function fec is used for smoothing. The surface is plotted assuming that it is linear on a set of triangles built from the grid (here with n1=5, n2=3):

             _____________
             | /| /| /| /|
             |/_|/_|/_|/_|
             | /| /| /| /|
             |/_|/_|/_|/_|

The function colorbar may be used to see the color scale.

The parameter zminmax is useful for animation purpose (see an example after) and the parameter colminmax lets the user choose a part of the current colormap (see the fec help page).

Enter the command Sgrayplot() to see a demo.

Examples

// example #1
x=-10:10; y=-10:10;m =rand(21,21);
clf()
xset("colormap",hotcolormap(64))
Sgrayplot(x,y,m, strf="011", rect=[-20,-20,20,20])

// example #2
t=-%pi:0.1:%pi; m=sin(t)'*cos(t);
clf()
xset("colormap",jetcolormap(64))
colorbar(-1,1)
Sgrayplot(t,t,m, strf="041")

// example #3: an animation display cos(t)*sin(x)sin(y).
// (Remark: this animation uses the old mode)
n = 30;
nt = 100;
x = linspace(0,2*%pi,n);
y = linspace(0,%pi,n/2);
z = sin(x')*sin(y);
t = linspace(0,4*%pi,nt);
xselect(); clf()
f=gcf();
f.color_map=jetcolormap(64);
f.pixmap='on';
colorbar(-1,1)
Sgrayplot(x,y,cos(t(1))*z, strf="042", zminmax=[-1,1])
c=gce(),e=c.children
xtitle("Kaa''s eyes")
for i = 1:nt
   e.data(:,3)=matrix(cos(t(i))*z,-1,1);
   show_pixmap()
end
f.pixmap='off';

See Also

fec , fgrayplot , grayplot , Sfgrayplot , colorbar ,

Author

J.Ph.C.


Fonctions élémentaires
abs - valeur absolue ou module
acos - cosinus inverse
acosh - cosinus hyperbolique inverse
acoshm - cosinus hyperbolique matriciel inverse
acosm - cosinus matriciel inverse
addf - addition symbolique
adj2sp - converts adjacency form into sparse matrix.
amell - Fonction am de Jacobi
and (&) - et logique
asin - sinus inverse
asinh - sinus hyperbolique inverse
asinhm - sinus hyperbolique matriciel inverse
asinm - sinus matriciel inverse
atan - 2-quadrant and 4-quadrant inverse tangent
atanh - hyperbolic tangent inverse
atanhm - tangente hyperbolique inverse d'une matrice carrée
atanm - tangente matricielle inverse d'une matrice carrée
besselh - Modified Bessel function of the third kind.
besseli - Modified Bessel function of the first kind (I sub alpha).
besselj - Bessel function of the first kind (J sub alpha).
besselk - Modified Bessel function of the second kind (K sub alpha).
bessely - Bessel function of the second kind (Y sub alpha).
beta - beta function
binomial - binomial distribution probabilities
bloc2exp - block-diagram to symbolic expression
bloc2ss - block-diagram to state-space conversion
bsplin3val - 3d spline arbitrary derivative evaluation function
calerf - calcule différentes fonctions d'erreur.
cat - concatenate several arrays
ceil - partie entière supérieure
cell2mat - convert a cell array into a matrix
cellstr - convert strings vector (or strings matrix) into a cell of strings
char - char function
cmb_lin - combinaison linéaire symbolique
conj - conjugaison complexe
cos - cosinus
cosh - cosinus hyperbolique
coshm - cosinus hyperbolique matriciel
cosm - cosinus matriciel
cotg - cotangente
coth - cotangente hyperbolique
cothm - cotangente hyperbolique matricielle
cshep2d - bidimensional cubic shepard (scattered) interpolation
cumprod - produit cumulatif.
cumsum - somme cumulative.
delip - intégrale elliptique
diag - extraction de diagonale ou construction d'une matrice à partir d'une diagonale.
diff - Difference and discrete derivative
dlgamma - dérivée de la fonction gammaln ou fonction psi.
double - conversion de type entier vers flottant double précision.
dsearch - dichotomic (binary) search
erf - fonction erreur
erfc - fonction erreur complémentaire.
erfcx - fonction erreur complémentaire normalisée.
eval - évaluation d'une matrice de chaînes de caractères
eval_cshep2d - bidimensional cubic shepard interpolation evaluation
eye - matrice identité
factorial - retourne factorielle
fix - arrondi vers zéro ou troncature
floor - partie entière
frexp - calcule la représentation en base 2 (mantisse et exposant) d'un nombre flottant.
full - sparse to full matrix conversion
gamma - The gamma function.
gammaln - Le logarithme de la fonction gamma.
gsort - tri par ordre décroissant
imag - partie imaginaire
imult - multiplication by i the imaginary unitary
ind2sub - linear index to matrix subscript values
int - arrondi vers zéro ou troncature
int16 - conversion au codage entier à 2 octets
int32 - conversion au codage entier à 4 octets
int8 - conversion au codage entier à 1 octet
uint16 - conversion au codage entier non signé à 2 octets
uint32 - conversion au codage entier non signé à 4 octets
uint8 - conversion au codage entier non signé à 1 octet
integrate - intégration numérique
interp - cubic spline evaluation function
interp1 - one_dimension interpolation function
interp2d - bicubic spline (2d) evaluation function
interp3d - 3d spline evaluation function
interpln - interpolation linéaire
intersect - recherche de valeurs communes à deux vecteurs.
intsplin - intégration approchée de données expérimentales utilisant une interpolation par une spline.
inttrap - intégration approchée de données expérimentales avec la méthode des trapèzes.
iscellstr - verifie si toutes les composantes d'une cell sont des strings
isdef - vérifie si une variable existe
isempty - check if a variable is an empty matrix or an empty list
isequal - objects comparison
isinf - vérifie si des composantes "Inf" (infinies) sont présentes.
isnan - vérifie si des composantes "NaN" (Not a Number) sont présentes.
isreal - vérifie si une matrice a des éléments complexes
kron - produit de kronecker (.*.)
ldivf - division à gauche symbolique
legendre - associated Legendre functions
lex_sort - tri des lignes d'une matrice suivant l'ordre lexicographique.
linear_interpn - n dimensional linear interpolation
linspace - vecteur de valeurs équidistantes
log - logarithme naturel
log10 - logarithme en base 10
log1p - computes with accuracy the natural logarithm of its argument added by one
log2 - logarithme en base 2
logm - logarithme matriciel d'une matrice carrée
logspace - vecteur de valeurs logarithmiquement équidistantes.
lsq_splin - weighted least squares cubic spline fitting
lstsize - nombre d'éléments des objets list, tlist et mlist
max - maximum
maxi - maximum
meshgrid - construit des matrices ou des tableaux 3-D
min - minimum
mini - minimum
minus (-) - opérateur de soustraction, changement de signe
modulo - reste arithmétique symétrique modulo m
pmodulo - reste arithmétique positif modulo m
mps2linpro - convert lp problem given in MPS format to linpro format
mtlb_sparse - convert sparse matrix
mulf - multiplication symbolique
ndgrid - arrays for multidimensional function evaluation on grid
ndims - number of dimensions of an array
nearfloat - get previous or next floating-point number
nextpow2 - next higher power of 2.
nnz - nombre de termes non nuls dans une matrice
norm - normes matricielles
not (~) - négation logique
number_properties - determine floating-point parameters
oldbesseli - Modified Bessel functions of the first kind (I sub alpha).
oldbesselj - Bessel functions of the first kind (J sub alpha).
oldbesselk - Modified Bessel functions of the second kind (K sub alpha).
oldbessely - Bessel functions of the second kind (Y sub alpha).
ones - matrice remplie de 1
or | - disjonction logique
pen2ea - Conversion faisceau vers deux matrices E,A
perms - retourne toutes les permutations des composantes d'un vecteur
permute - permute the dimensions of an array
pertrans - pertranspose
prod - produit des termes d'une matrice
rand - générateur de nombres aléatoires
rat - approximation rationnelle d'un flottant
rdivf - division symbolique à droite
real - partie réelle
round - arrondi
setdiff - returns components of a vector which do not belong to another one
sign - fonction signe
signm - fonction signe matriciel
sin - sinus
sinc - sinc function
sinh - sinus hyperbolique
sinhm - sinus hyperbolique matriciel
sinm - sinus matriciel
size - taille d'un objet
smooth - interpolation par une spline
solve - solveur symbolique de système linéaire
sort - tri par ordre décroissant
sp2adj - converts sparse matrix into adjacency form
sparse - sparse matrix definition
spcompack - converts a compressed adjacency representation
speye - matrice identité creuse
spget - retrieves entries of sparse matrix
splin - cubic spline interpolation
splin2d - bicubic spline gridded 2d interpolation
splin3d - spline gridded 3d interpolation
spones - matrice creuse dont les termes valent 1
sprand - matrice creuse aléatoire
spzeros - sparse zero matrix
sqrt - racine carrée
sqrtm - racine carrée matricielle
squarewave - génère un signal carré de période 2*%pi
ssprint - pretty print for linear system
ssrand - random system generator
sub2ind - matrix subscript values to linear index
subf - soustraction symbolique
sum - somme des vecteurs et matrices
sysconv - system conversion
sysdiag - block diagonal system connection
syslin - définition d'un système dynamique linéaire
tan - tangente
tanh - tangente hyperbolique
tanhm - tangente hyperbolique matricielle
tanm - tangente matricielle
toeplitz - matrice de Toeplitz
trfmod - poles and zeros display
trianfml - triangularisation symbolique
tril - partie triangulaire inférieure d'une matrice
trisolve - solveur symbolique de système linéaire
triu - partie triangulaire supérieure d'une matrice
typeof - object type
union - extrait les composantes distinctes issues de l'union de deux vecteurs
unique - extrait les composantes distinctes d'un vecteur
vectorfind - finds in a matrix rows or columns matching a vector
zeros - matrice nulle


abs

Scilab Function
Last update : 16/06/2004

abs - valeur absolue ou module

Calling Sequence

t=abs(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)
  • t : vecteur ou matrice (réelle ou complexe)

Description

abs(x) est la valeur absolue des éléments de x . Quand x est complexe, abs(x) est le module des éléments de x .

Examples

abs([1,%i,-1,-%i,1+%i])


acoshm

Scilab Function
Last update : 16/06/2004

acoshm - cosinus hyperbolique matriciel inverse

Calling Sequence

t=acoshm(x)

Parameters

  • x,t : matrice carrée complexe ou réelle

Description

acoshm est le cosinus hyperbolique matriciel inverse de la matrice x. Utilise la formule t=logm(x+(x+eye())*sqrtm((x-eye())/(x+eye()))) Pour les matrices non symétriques le résultat peut être imprécis.

Examples

A=[1,2;3,4];
coshm(acoshm(A))
A(1,1)=A(1,1)+%i;
coshm(acoshm(A))

See Also

acosh , logm , sqrtm ,


acosh

Scilab Function
Last update : 16/06/2004

acosh - cosinus hyperbolique inverse

Calling Sequence

[t]=acosh(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)
  • t : vecteur ou matrice (réelle ou complexe)

Description

Les composantes de t sont les cosinus hyperboliques inverses des composantes correspondantes de x . Le domaine de définition est ]1,+infini[. Cette fonction prend ses valeurs dans

Examples

x=[0,1,%i];
cosh(acosh(x))


acosm

Scilab Function
Last update : 16/06/2004

acosm - cosinus matriciel inverse

Calling Sequence

t=acosm(x)

Parameters

  • x : matrice carrée complexe ou réelle
  • t : matrice carrée complexe ou réelle

Description

t est le cosinus matriciel inverse de la matrice x . La méthode de diagonalisation est utilisée. Pour les matrices non symétriques le résultat peut être imprécis. On a t=-%i*logm(x+%i*sqrtm(eye()-x*x))

Examples

A=[1,2;3,4];
cosm(acosm(A))

See Also

acos , sqrtm , logm ,


acos

Scilab Function
Last update : 16/06/2004

acos - cosinus inverse

Calling Sequence

t=acos(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)
  • t : vecteur ou matrice (réelle ou complexe)

Description

Les composantes de t sont les cosinus inverses des composantes correspondantes de x . Le domaine de définition est [-1, 1].

Cette fonction est à valeurs dans

Examples

x=[1,%i,-1,-%i]
cos(acos(x))


addf

Scilab Function
Last update : 16/06/2004

addf - addition symbolique

Calling Sequence

addf("a","b")

Parameters

  • "a","b" : chaînes de caractères

Description

addf("a","b") renvoie la chaîne de caractères "a+b" . Des simplifications triviales du type addf("0","a") ou addf("1","2") sont effectuées.

Examples

addf('0','1')
addf('1','a')
addf('1','2')
'a'+'b'

See Also

mulf , subf , ldivf , rdivf , eval , evstr ,


adj2sp

Scilab Function
Last update : 16/06/2004

adj2sp - converts adjacency form into sparse matrix.

Parameters

  • xadj : integer vector of length (n+1).
  • adjncy : integer vector of length nz containing the row indices for the corresponding elements in anz
  • anz : column vector of length nz, containing the non-zero elements of A
  • mn : row vector with 2 entries, mn=size(A) (optional).
  • A : real or complex sparse matrix (nz non-zero entries)

Description

sp2adj converts an adjacency form representation of a matrix into its standard Scilab representation (utility fonction). xadj, adjncy, anz = adjacency representation of A i.e:

xadj(j+1)-xadj(j) = number of non zero entries in row j. adjncy = column index of the non zeros entries in row 1, row 2,..., row n. anz = values of non zero entries in row 1, row 2,..., row n. xadj is a (column) vector of size n+1 and adjncy is an integer (column) vector of size nz=nnz(A) . anz is a real vector of size nz=nnz(A) .

Examples

A = sprand(100,50,.05);
[xadj,adjncy,anz]= sp2adj(A);
[n,m]=size(A);
p = adj2sp(xadj,adjncy,anz,[n,m]);
A-p,

See Also

sp2adj , spcompack ,


amell

Scilab Function
Last update : 16/06/2004

amell - Fonction am de Jacobi

Calling Sequence

[sn]=amell(u,k)

Parameters

  • u : scalaire ou vecteur réel
  • k : scalaire
  • sn : scalaire ou vecteur réel

Description

Calcule la fonction elliptique de Jacobi am(u,k) où k est le paramètre et u l'argument. Si u est un vecteur sn est le vecteur des valeurs calculées (élément par élément). Utilisé dans la fonction %sn .

See Also

delip , %sn , %asn ,


and (&)

Scilab Function
Last update : 16/06/2004

and (&) - et logique

Calling Sequence

b=and(A), b=and(A,'*')
b=and(A,'r'), b=and(A,1)
b=and(A,'c'), b=and(A,2)
A&B

Description

and(A) donne la conjonction (et) logique des éléments de la matrice booléenne A . and(A) est vrai ( %t ) si tous les termes de A sont %t .

y=and(A,'r') (et y=and(A,1) ) donne la conjonction suivant l'indice de ligne. Chaque élément du vecteur ligne y contient la conjonction de chaque colonne de x ( y(j)= and(A(i,j),i=1,m) ).

y=and(A,'c') (et y=and(A,2) ) donne la conjonction suivant l'indice de colonne. Chaque élément du vecteur colonne y contient la conjonction de chaque ligne de x ( y(i)= and(A(i,j),j=1,n) )).

A&B renvoie la conjonction logique élément par élément des matrices booléennes A et B . A et B doivent être des matrices de même dimensions ou l'une d'elle doit être un simple booléen.

See Also

not , or ,


asinhm

Scilab Function
Last update : 16/06/2004

asinhm - sinus hyperbolique matriciel inverse

Calling Sequence

t=asinhm(x)

Parameters

  • x,t : matrice carrée complexe ou réelle

Description

asinhm est le sinus hyperbolique matriciel inverse de la matrice x. Cette fonction utilise la formule t=logm(x+sqrtm(x*x+eye())) . Pour les matrices non symétriques le résultat peut être imprécis.

Examples

A=[1,2;2,3]
sinhm(asinhm(A))

See Also

asinh , logm , sqrtm ,


asinh

Scilab Function
Last update : 16/06/2004

asinh - sinus hyperbolique inverse

Calling Sequence

[t]=asinh(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)
  • t : vecteur ou matrice (réelle ou complexe)

Description

Les composantes de t sont les sinus hyperboliques inverses des composantes correspondantes de x . Le domaine de définition est ]-1, i[. Cette fonction prend ses valeurs dans

Examples

A=[1,2;2,3]
sinh(asinh(A))


asinm

Scilab Function
Last update : 16/06/2004

asinm - sinus matriciel inverse

Calling Sequence

t=asinm(x)

Parameters

  • x : matrice carrée complexe ou réelle
  • t : matrice carrée complexe ou réelle

Description

t est le sinus matriciel inverse de la matrice x . La méthode de diagonalisation est utilisée. Pour les matrices non symétriques le résultat peut être peu fiable.

Examples

A=[1,2;3,4]
sinm(asinm(A))
asinm(A)+%i*logm(%i*A+sqrtm(eye()-A*A))

See Also

asin , sinm ,


asin

Scilab Function
Last update : 16/06/2004

asin - sinus inverse

Calling Sequence

[t]=asin(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)
  • t : vecteur ou matrice (réelle ou complexe)

Description

Les composantes de t sont les sinus inverses des composantes correspondantes de x . Le domaine de définition est [-1, 1].

Cette fonction est à valeurs dans

Examples

A=[1,2;3,4]
sin(asin(A))

See Also

sin , sinm , asinm ,


atanhm

Scilab Function
Last update : 16/06/2004

atanhm - tangente hyperbolique inverse d'une matrice carrée

Calling Sequence

t=atanhm(x)

Parameters

  • x : matrice carrée complexe ou réelle
  • t : matrice carrée complexe ou réelle

Description

atanhm(x) est l'arctangente hyperbolique matricielle de la matrice x. Le résultat peut être imprécis si x n'est pas symétrique.

Examples

A=[1,2;3,4];
tanhm(atanhm(A))

See Also

atanh , tanhm ,


atanh

Scilab Function
Last update : 12/01/2004

atanh - hyperbolic tangent inverse

Calling Sequence

t=atanh(x)

Parameters

  • x : real or complex vector/matrix
  • t : real or complex vector/matrix

Description

The components of vector t are the hyperbolic tangent inverse of the corresponding entries of vector x . Definition domain is [-1,1] for the real function (see Remark).

Remark

In Scilab (as in some others numerical software) when you try to evaluate an elementary mathematical function outside its definition domain in the real case, then the complex extension is used (with a complex result). The more famous example being the sqrt function (try sqrt(-1) !). This approach have some drawbacks when you evaluate the function at a singular point which may led to different results when the point is considered as real or complex. For the atanh this occurs for -1 and 1 because the at these points the imaginary part do not converge and so atanh(1) = +Inf + i NaN while atanh(1) = +Inf for the real case (as lim x->1- of atanh(x)). So when you evaluate this function on the vector [1 2] then like 2 is outside the definition domain, the complex extension is used for all the vector and you get atanh(1) = +Inf + i NaN while you get atanh(1) = +Inf with [1 0.5] for instance.

Examples

// example 1
x=[0,%i,-%i]
tanh(atanh(x))

// example 2
x = [-%inf -3 -2 -1 0 1 2 3 %inf]
ieee(2)
atanh(tanh(x))

// example 3 (see Remark)
ieee(2)
atanh([1 2])
atanh([1 0.5])

See Also

tanh , ieee ,


atanm

Scilab Function
Last update : 16/06/2004

atanm - tangente matricielle inverse d'une matrice carrée

Calling Sequence

[t]=atanm(x)

Parameters

  • x : matrice carrée complexe ou réelle
  • t : matrice carrée complexe ou réelle

Description

atanm(x) est l'arctangente matricielle de la matrice x. Le résultat peut être imprécis si x n'est pas symétrique.

Examples

tanm(atanm([1,2;3,4]))

See Also

atan ,


atan

Scilab Function
Last update : 12/01/2004

atan - 2-quadrant and 4-quadrant inverse tangent

Calling Sequence

phi=atan(x)
phi=atan(y,x)

Parameters

  • x : real or complex scalar, vector or matrix
  • phi : real or complex scalar, vector or matrix
  • x, y : real scalars, vectors or matrices of the same size
  • phi : real scalar, vector or matrix

Description

The first form computes the 2-quadrant inverse tangent, which is the inverse of tan(phi) . For real x , phi is in the interval (-pi/2, pi/2). For complex x , atan has two singular, branching points +%i , -%i and the chosen branch cuts are the two imaginary half-straight lines [i, i*oo) and (-i*oo, -i].

The second form computes the 4-quadrant arctangent (atan2 in Fortran), this is, it returns the argument (angle) of the complex number x+i*y . The range of atan(y,x) is (-pi, pi].

For real arguments, both forms yield identical values if x>0 .

In case of vector or matrix arguments, the evaluation is done element-wise, so that phi is a vector or matrix of the same size with phi(i,j)=atan(x(i,j)) or phi(i,j)=tan(y(i,j),x(i,j)) .

Examples

// examples with the second form
x=[1,%i,-1,%i]
phasex=atan(imag(x),real(x))
atan(0,-1)
atan(-%eps,-1)

// branch cuts
atan(-%eps + 2*%i)
atan(+%eps + 2*%i)
atan(-%eps - 2*%i)
atan(+%eps - 2*%i)

// values at the branching points
ieee(2)
atan(%i)
atan(-%i)

See Also

tan , ieee ,

Authors

B.P.
L.V.D. (authors of the complex atan function).


besselibesseljbesselkbesselybesselh

Scilab Function
Last update : 27/02/2006

besseli - Modified Bessel function of the first kind (I sub alpha).

besselj - Bessel function of the first kind (J sub alpha).

besselk - Modified Bessel function of the second kind (K sub alpha).

bessely - Bessel function of the second kind (Y sub alpha).

besselh - Modified Bessel function of the third kind.

Calling Sequence

y = besseli(alpha,x [,ice])
y = besselj(alpha,x [,ice])
y = besselk(alpha,x [,ice])
y = bessely(alpha,x [,ice])
y = besselh(alpha,x)
y = besselh(alpha,K,x [,ice])

Parameters

  • x : real or complex vector.
  • alpha : real vector
  • ice : integer flag, with default value 0
  • K : integer , with possible values 1 or 2, the Hankel function type.

Description

Warning: the semantics of these function changes between Scilab-3.0 and Scilab-3.1. The old semantics is available for compatibility using the oldbesseli, oldbesselj, oldbesselk, oldbessely functions.
* besseli(alpha,x) computes modified Bessel functions of the first kind (I sub alpha), for real order alpha and argument x . besseli(alpha,x,1) computes besseli(alpha,x).*exp(-abs(real(x))) .
* besselj(alpha,x) computes modified Bessel functions of the first kind (J sub alpha), for real order alpha and argument x . besselj(alpha,x,1) computes besselj(alpha,x).*exp(-abs(imag(x))) .
* besselk(alpha,x) computes modified Bessel functions of the second kind (K sub alpha), for real order alpha and argument x . besselk(alpha,x,1) computes besselk(alpha,x).*exp(x) .
* bessely(alpha,x) computes modified Bessel functions of the second kind (Y sub alpha), for real order alpha and argument x . bessely(alpha,x,1) computes bessely(alpha,x).*exp(-abs(imag(x))) .
* besselh(alpha [,K] ,x) computes modified Bessel functions of the third kind (Hankel function H1 or H2 depending on K ), for real order alpha and argument x . If omitted K is supposed to be equal to 1. besselh(alpha,1,x,1) computes besselh(alpha,1,x).*exp(-%i*x) and besselh(alpha,2,x,1) computes besselh(alpha,2,x).*exp(%i*x)

If alpha and x are arrays of the same size, the result y is also that size. If either input is a scalar, it is expanded to the other input's size. If one input is a row vector and the other is a column vector, the result y is a two-dimensional table of function values.

I_alpha and K_alpha are 2 independant solutions of the modified Bessel's differential equation :

2 2 2 x y(x)" + x y(x)' - (x + alpha ) y(x) = 0 ,

J_alpha and Y_alpha are 2 independant solutions of the Bessel's differential equation :

2 2 2 x y(x)" + x y(x)' + (x - alpha ) y(x) = 0 ,

Examples

//  besselI functions
// ==================
   x = linspace(0.01,10,5000)';
   xbasc()
   subplot(2,1,1)
   plot2d(x,besseli(0:4,x), style=2:6)
   legend('I'+string(0:4),2);
   xtitle("Some modified Bessel functions of the first kind")
   subplot(2,1,2)
   plot2d(x,besseli(0:4,x,1), style=2:6)
   legend('I'+string(0:4),1);
   xtitle("Some modified scaled Bessel functions of the first kind")

// besselJ functions
// =================
   x = linspace(0,40,5000)';
   xbasc()
   plot2d(x,besselj(0:4,x), style=2:6, leg="J0@J1@J2@J3@J4")
   legend('I'+string(0:4),1);
   xtitle("Some Bessel functions of the first kind")

// use the fact that J_(1/2)(x) = sqrt(2/(x pi)) sin(x)
// to compare the algorithm of besselj(0.5,x) with a more direct formula
   x = linspace(0.1,40,5000)';
   y1 = besselj(0.5, x);
   y2 = sqrt(2 ./(%pi*x)).*sin(x);
   er = abs((y1-y2)./y2);
   ind = find(er > 0 & y2 ~= 0);
   xbasc()
   subplot(2,1,1)
   plot2d(x,y1,style=2)
   xtitle("besselj(0.5,x)")
   subplot(2,1,2)
   plot2d(x(ind), er(ind), style=2, logflag="nl")
   xtitle("relative error between 2 formulae for besselj(0.5,x)")

// besselK functions
// =================
   x = linspace(0.01,10,5000)';
   xbasc()
   subplot(2,1,1)
   plot2d(x,besselk(0:4,x), style=0:4, rect=[0,0,6,10])
   legend('K'+string(0:4),1);
   xtitle("Some modified Bessel functions of the second kind")
   subplot(2,1,2)
   plot2d(x,besselk(0:4,x,1), style=0:4, rect=[0,0,6,10])
   legend('K'+string(0:4),1);
   xtitle("Some modified scaled Bessel functions of the second kind")

// besselY functions
// =================
   x = linspace(0.1,40,5000)'; // Y Bessel functions are unbounded  for x -> 0+
   xbasc()
   plot2d(x,bessely(0:4,x), style=0:4, rect=[0,-1.5,40,0.6])
   legend('Y'+string(0:4),4);
   xtitle("Some Bessel functions of the second kind")

// besselH functions
// =================
   x=-4:0.025:2; y=-1.5:0.025:1.5;
   [X,Y] = ndgrid(x,y);
   H = besselh(0,1,X+%i*Y);
   clf();f=gcf();
   xset("fpf"," ")
   f.color_map=jetcolormap(16);
   contour2d(x,y,abs(H),0.2:0.2:3.2,strf="034",rect=[-4,-1.5,3,1.5])
   legends(string(0.2:0.2:3.2),1:16,"ur")
   xtitle("Level curves of |H1(0,z)|")

Authors

Amos, D. E., (SNLA)
Daniel, S. L., (SNLA)

Used Function

The source codes can be found in routines/calelm

Slatec : dbesi.f, zbesi.f, dbesj.f, zbesj.f, dbesk.f, zbesk.f, dbesy.f, zbesy.f, zbesh.f

Drivers to extend definition area (Serge Steer INRIA): dbesig.f, zbesig.f, dbesjg.f, zbesjg.f, dbeskg.f, zbeskg.f, dbesyg.f, zbesyg.f, zbeshg.f


beta

Scilab Function
Last update : 17/12/2003

beta - beta function

Calling Sequence

z = beta(x,y)

Parameters

  • x, y : 2 positive reals or 2 matrices (or vectors) of positive reals of same size.
  • z : a real or a matrix of the same size than x with z(i,j) = beta(x(i,j),y(i,j)) .

Description

Computes the complete beta function :

               /1
               |   x-1     y-1        gamma(x) gamma(y)
  beta(x,y) =  |  t   (1-t)    dt  =  ----------------
               /0                        gamma(x+y)

For small x and y the algorithm uses the expression in function of the gamma function, else it applies the exponential function onto the result of the betaln function provided with the DCDFLIB: Library of Fortran Routines for Cumulative Distribution Functions, Inverses, and Other Parameter (see cdfbet for more information about DCDFLIB).

Examples

// example 1 :
beta(5,2) - beta(2,5)   // symetry (must be exactly 0)
beta(0.5,0.5)           // exact value is pi

// example 2 : an error study based on the relation  B(1,x) = 1/x
// (computing 1/x must lead to only a relative error of eps_m, so
//  it may be used near as a reference to evaluate the error in B(1,x))
x = logspace(-8,8,20000)';
e = beta(ones(x),x) - (1)./x;
er = abs(e) .* x;
ind = find(er ~= 0);
eps = ones(x(ind))*number_properties("eps");
xbasc()
plot2d(x(ind),[er(ind) eps 2*eps],style=[1 2 3],logflag="ll",leg="er@eps_m@2 eps_m")
xtitle("approximate relative error in computing beta(1,x)")
xselect()

// example 3 : plotting the beta function
t = linspace(0.2,10,60);
X = t'*ones(t); Y = ones(t')*t;
Z = beta(X,Y);
xbasc()
plot3d(t, t, Z, flag=[2 4 4], leg="x@y@z", alpha=75, theta=30)
xtitle("The beta function on [0.2,10]x[0.2,10]")
xselect()

See Also

gamma , cdfbet ,


binomial

Scilab Function
Last update : 12/01/2004

binomial - binomial distribution probabilities

Calling Sequence

pr=binomial(p,n)

Parameters

  • pr : row vector with n+1 components
  • p : real number in [0,1]
  • n : an integer >= 1

Description

pr=binomial(p,n) returns the binomial probability vector, i.e. pr(k+1) is the probability of k success in n independent Bernouilli trials with probability of success p . In other words : pr(k+1) = probability(X=k) , with X a random variable following the B(n,p) distribution, and numerically :

            / n \  k      n-k       / n \       n!
 pr(k+1) =  |   | p  (1-p)    with  |   |  = ---------
            \ k /                   \ k /    k! (n-k)!

Examples

// first example
n=10;p=0.3; xbasc(); plot2d3(0:n,binomial(p,n));

// second example
n=50;p=0.4;
mea=n*p; sigma=sqrt(n*p*(1-p));
x=( (0:n)-mea )/sigma;
xbasc()
plot2d(x, sigma*binomial(p,n));
deff('y=Gauss(x)','y=1/sqrt(2*%pi)*exp(-(x.^2)/2)')
plot2d(x, Gauss(x), style=2);

// by binomial formula (Caution if big n)
function pr=binomial2(p,n)
x=poly(0,'x');pr=coeff((1-p+x)^n).*horner(x^(0:n),p);
endfunction
p=1/3;n=5;
binomial(p,n)-binomial2(p,n)

// by Gamma function: gamma(n+1)=n! (Caution if big n)
p=1/3;n=5;
Cnks=gamma(n+1)./(gamma(1:n+1).*gamma(n+1:-1:1));
x=poly(0,'x');
pr=Cnks.*horner(x.^(0:n).*(1-x)^(n:-1:0),p);
pr-binomial(p,n)

See Also

cdfbin , grand ,


bloc2exp

Scilab Function
Last update : 12/01/2004

bloc2exp - block-diagram to symbolic expression

Calling Sequence

[str]=bloc2exp(blocd)
[str,names]=bloc2exp(blocd)

Parameters

  • blocd : list
  • str : string
  • names : string

Description

given a block-diagram representation of a linear system bloc2exp returns its symbolic evaluation. The first element of the list blocd must be the string 'blocd' . Each other element of this list (blocd(2),blocd(3),...) is itself a list of one the following types :

list('transfer','name_of_linear_system')

list('link','name_of_link',
               [number_of_upstream_box,upstream_box_port],
               [downstream_box_1,downstream_box_1_portnumber],
               [downstream_box_2,downstream_box_2_portnumber],
               ...)

The strings 'transfer' and 'links' are keywords which indicate the type of element in the block diagram.

Case 1 : the second parameter of the list is a character string which may refer (for a possible further evaluation) to the Scilab name of a linear system given in state-space representation ( syslin list) or in transfer form (matrix of rationals).

To each transfer block is associated an integer. To each input and output of a transfer block is also associated its number, an integer (see examples)

Case 2 : the second kind of element in a block-diagram representation is a link. A link links one output of a block represented by the pair [number_of_upstream_box,upstream_box_port] , to different inputs of other blocks. Each such input is represented by the pair [downstream_box_i,downstream_box_i_portnumber] .

The different elements of a block-diagram can be defined in an arbitrary order.

For example

[1] S1*S2 with unit feedback.

There are 3 transfers S1 (number n_s1=2 ) , S2 (number n_s2=3 ) and an adder (number n_add=4 ) with symbolic transfer function ['1','1'] .

There are 4 links. The first one (named 'U' ) links the input (port 0 of fictitious block -1, omitted) to port 1 of the adder. The second and third one link respectively (output)port 1 of the adder to (input)port 1 of system S1 , and (output)port 1 of S1 to (input)port 1 of S2 . The fourth link (named 'Y' ) links (output)port 1 of S2 to the output (port 0 of fictitious block -1, omitted) and to (input)port 2 of the adder.

//Initialization
syst=list('blocd'); l=1;
//
//Systems
l=l+1;n_s1=l;syst(l)=list('transfer','S1');  //System 1
l=l+1;n_s2=l;syst(l)=list('transfer','S2');  //System 2
l=l+1;n_adder=l;syst(l)=list('transfer',['1','1']);  //adder
//
//Links
// Inputs  -1 --> input 1
l=l+1;syst(l)=list('link','U',[-1],[n_adder,1]);
// Internal
l=l+1;syst(l)=list('link',' ',[n_adder,1],[n_s1,1]);
l=l+1;syst(l)=list('link',' ',[n_s1,1],[n_s2,1]);
// Outputs // -1 -> output 1
l=l+1;syst(l)=list('link','Y',[n_s2,1],[-1],[n_adder,2]);
//Evaluation call
w=bloc2exp(syst);

The result is the character string: w=-(s2*s1-eye())\s2*s1 .

Note that invoked with two output arguments, [str,names]= blocd(syst) returns in names the list of symbolic names of named links. This is useful to set names to inputs and outputs.

[2] second example

//Initialization
syst=list('blocd'); l=1;
//
//System (2x2 blocks plant)
l=l+1;n_s=l;syst(l)=list('transfer',['P11','P12';'P21','P22']);
//
//Controller
l=l+1;n_k=l;syst(l)=list('transfer','k');
//
//Links
l=l+1;syst(l)=list('link','w',[-1],[n_s,1]);
l=l+1;syst(l)=list('link','z',[n_s,1],[-1]);
l=l+1;syst(l)=list('link','u',[n_k,1],[n_s,2]);
l=l+1;syst(l)=list('link','y',[n_s,2],[n_k,1]);
//Evaluation call
w=bloc2exp(syst);

In this case the result is a formula equivalent to the usual one:

P11+P12*invr(eye()-K*P22)*K*P21;

See Also

bloc2ss ,

Author

S. S., F. D. (INRIA)


bloc2ss

Scilab Function
Last update : 12/01/2004

bloc2ss - block-diagram to state-space conversion

Calling Sequence

[sl]=bloc2ss(blocd)

Parameters

  • blocd : list
  • sl : list

Description

Given a block-diagram representation of a linear system bloc2ss converts this representation to a state-space linear system. The first element of the list blocd must be the string 'blocd' . Each other element of this list is itself a list of one the following types :

list('transfer','name_of_linear_system')

list('link','name_of_link',
             [number_of_upstream_box,upstream_box_port],
             [downstream_box_1,downstream_box_1_portnumber],
             [downstream_box_2,downstream_box_2_portnumber],
             ...)

The strings 'transfer' and 'links' are keywords which indicate the type of element in the block diagram.

Case 1 : the second parameter of the list is a character string which may refer (for a possible further evaluation) to the Scilab name of a linear system given in state-space representation ( syslin list) or in transfer form (matrix of rationals).

To each transfer block is associated an integer. To each input and output of a transfer block is also associated its number, an integer (see examples)

Case 2 : the second kind of element in a block-diagram representation is a link. A link links one output of a block represented by the pair [number_of_upstream_box,upstream_box_port] , to different inputs of other blocks. Each such input is represented by the pair [downstream_box_i,downstream_box_i_portnumber] .

The different elements of a block-diagram can be defined in an arbitrary order.

For example

[1] S1*S2 with unit feedback.

There are 3 transfers S1 (number n_s1=2 ) , S2 (number n_s2=3 ) and an adder (number n_add=4 ) with symbolic transfer function ['1','1'] .

There are 4 links. The first one (named 'U' ) links the input (port 0 of fictitious block -1, omitted) to port 1 of the adder. The second and third one link respectively (output)port 1 of the adder to (input)port 1 of system S1 , and (output)port 1 of S1 to (input)port 1 of S2 . The fourth link (named 'Y' ) links (output)port 1 of S2 to the output (port 0 of fictitious block -1, omitted) and to (input)port 2 of the adder.

//Initialization
syst=list('blocd'); l=1;
//
//Systems
l=l+1;n_s1=l;syst(l)=list('transfer','S1');  //System 1
l=l+1;n_s2=l;syst(l)=list('transfer','S2');  //System 2
l=l+1;n_adder=l;syst(l)=list('transfer',['1','1']);  //adder
//
//Links
// Inputs  -1 --> input 1
l=l+1;syst(l)=list('link','U1',[-1],[n_adder,1]);
// Internal
l=l+1;syst(l)=list('link',' ',[n_adder,1],[n_s1,1]);
l=l+1;syst(l)=list('link',' ',[n_s1,1],[n_s2,1]);
// Outputs // -1 -> output 1
l=l+1;syst(l)=list('link','Y',[n_s2,1],[-1],[n_adder,2]);

With s=poly(0,'s');S1=1/(s+1);S2=1/s; the result of the evaluation call sl=bloc2ss(syst); is a state-space representation for 1/(s^2+s-1) .

[2] LFT example

//Initialization
syst=list('blocd'); l=1;
//
//System (2x2 blocks plant)
l=l+1;n_s=l;syst(l)=list('transfer',['P11','P12';'P21','P22']);
//
//Controller
l=l+1;n_k=l;syst(l)=list('transfer','k');
//
//Links
l=l+1;syst(l)=list('link','w',[-1],[n_s,1]);
l=l+1;syst(l)=list('link','z',[n_s,1],[-1]);
l=l+1;syst(l)=list('link','u',[n_k,1],[n_s,2]);
l=l+1;syst(l)=list('link','y',[n_s,2],[n_k,1]);

With

P=syslin('c',A,B,C,D);
P11=P(1,1);
P12=P(1,2);
P21=P(2,1);
P22=P(2,2);
K=syslin('c',Ak,Bk,Ck,Dk);

bloc2exp(syst) returns the evaluation the lft of P and K .

See Also

bloc2exp ,

Author

S. S., F. D. (INRIA)


bsplin3val

Scilab Function
Last update : 24/03/2004

bsplin3val - 3d spline arbitrary derivative evaluation function

Calling Sequence

[dfp]=bsplin3val(xp,yp,zp,tl,der)

Parameters

  • xp, yp, zp : real vectors or matrices of same size
  • tl : tlist of type "splin3d", defining a 3d tensor spline (called s in the following)
  • der : vector with 3 components [ox,oy,oz] defining which derivative of s to compute.
  • dfp : vector or matrix of same format than xp , yp and zp , elementwise evaluation of the specified derivative of s on these points.

Description

While the function interp3d may compute only the spline s and its first derivatives, bsplin3val may compute any derivative of s . The derivative to compute is specified by the argument der=[ox,oy,oz] :

               ox   oy   oz
              d    d    d
   dfp(i) =  ---  ---  ---   s (xp(i),yp(i),zp(i))
               ox   oy   oz
             dx   dy   dz

So der=[0 0 0] corresponds to s, der=[1 0 0] to ds/dx, der=[0 1 0] to ds/dy, der=[1 1 0] to d2s/dxdy, etc...

For a point with coordinates (xp(i),yp(i),zp(i)) outside the grid, the function returns 0.

Examples

deff("v=f(x,y,z)","v=cos(x).*sin(y).*cos(z)");
deff("v=fx(x,y,z)","v=-sin(x).*sin(y).*cos(z)");
deff("v=fxy(x,y,z)","v=-sin(x).*cos(y).*cos(z)");
deff("v=fxyz(x,y,z)","v=sin(x).*cos(y).*sin(z)");
deff("v=fxxyz(x,y,z)","v=cos(x).*cos(y).*sin(z)");
n = 20;  // n x n x n  interpolation points
x = linspace(0,2*%pi,n); y=x; z=x; // interpolation grid
[X,Y,Z] = ndgrid(x,y,z); V = f(X,Y,Z);
tl = splin3d(x,y,z,V,[5 5 5]);

// compute f and some derivates on a point
// and compare with the spline interpolant
xp = grand(1,1,"unf",0,2*%pi);
yp = grand(1,1,"unf",0,2*%pi);
zp = grand(1,1,"unf",0,2*%pi);

f_e = f(xp,yp,zp)
f_i = bsplin3val(xp,yp,zp,tl,[0 0 0])

fx_e = fx(xp,yp,zp)
fx_i = bsplin3val(xp,yp,zp,tl,[1 0 0])

fxy_e = fxy(xp,yp,zp)
fxy_i = bsplin3val(xp,yp,zp,tl,[1 1 0])

fxyz_e = fxyz(xp,yp,zp)
fxyz_i = bsplin3val(xp,yp,zp,tl,[1 1 1])

fxxyz_e = fxxyz(xp,yp,zp)
fxxyz_i = bsplin3val(xp,yp,zp,tl,[2 1 1])

See Also

splin3d , interp3d ,

Authors

R.F. Boisvert, C. De Boor (code from the CMLIB fortran lib)
B. Pincon (scilab interface)


calerf

Scilab Function
Last update : 16/06/2004

calerf - calcule différentes fonctions d'erreur.

Parameters

  • x : vecteur réel
  • flag : un entier
  • y : vecteur réel (de même taille que x)

Description

calerf(x,0) calcule la fonction erreur : erf(x)

calerf(x,1) calcule la fonction erreur complémentaire : erfc(x)

calerf(x,2) calcule la fonction erreur complémentaire normalisée : erfcx(x)

Examples

deff('y=f(t)','y=exp(-t^2)');
calerf(1,0)
2/sqrt(%pi)*intg(0,1,f)

See Also

erf , erfc , calerf ,

Author

W. J. Cody (code from Netlib (specfun))


cat

Scilab Function
Last update : 27/10/2005

cat - concatenate several arrays

Calling Sequence

y=cat(dims,A1,A2,...,An)

Parameters

  • dims : a positive real scalar.
  • A1,A2,..An : scalars, vectors, matrices or mutlti-arrays, or cells arrays. A1,A2,...,An must have the same size (excluding the dimension number dims). size(A1,i)=size(A2,i)=...=size(An,i) for i different of dims and size(A1,dims), size(A2,dims),...,size(An,dims) can be different.
  • y : a scalar, vector, matrix or mutlti-array, y has the same type than A1,A2,...,An.

Description

y=cat(dims,A1,A2,...,An) : y is the result of the concatenation of the input arguments A1,A2,...,An. if dims=1then the concatenation is done according to the rows : if dims=2 then concatenation is done according to the columns of the input arguments,...

if dims=1, then the concatenation is done according to the rows

A1=[1 2 3 ; 4 5 6]; A2=[7 8 9 ; 10 11 12]; y=cat(1,A1,A2) => y=[1 2 3 ; 4 5 61 ;7 8 9; 10 11 12]

if dims=2, then the concatenation is done according to the columns of the input arguments

A1=[1 2 3;4 5 6]; A2=[7 8 9 ;10 11 12]; y=cat(2,A1,A2) => y=[1 2 3 7 8 9 ; 4 5 6 10 11 12]

Examples

// first example : concatenation according to the rows
dims=1; A1=[1 2 3]; A2=[4 5 6 ; 7 8 9]; A3=[10 11 12]; y=cat(dims,A1,A2,A3)
// second example :  concatenation according to the columns
dims=2; A1=[1 2 3]'; A2=[4 5;7 8;9 10]; y=cat(dims,A1,A2)
// third example : concatenation according to the 3th dimension
dims=3; A1=matrix(1:12,[2,2,3]); A2=[13 14;15 16]; A3=matrix(21:36,[2,2,4]); y=cat(dims,A1,A2,A3)

See Also

permute , matrix ,

Author

Farid Belahcene


ceil

Scilab Function
Last update : 16/06/2004

ceil - partie entière supérieure

Calling Sequence

[y]=ceil(x)

Parameters

  • x : matrice réelle
  • y : matrice entière

Description

Renvoie dans y, pour chaque élément de x, le plus petit entier supérieur.

Examples

ceil([1.9 -2.5])-[2,-2]
ceil(-%inf)
x=rand()*10^20;ceil(x)-x

See Also

round , floor , int ,


cell2mat

Scilab Function
Last update : 06/01/2006

cell2mat - convert a cell array into a matrix

Calling Sequence

x=cell2mat(c)

Parameters

  • c : cell, the components of c must have the same type and can be scalars or matrices
  • x : matrix

Description

Returns a matrix which is the concatenation of all components of the cell c.

cell2mat(c): all components of c must have the same data type (strings or doubles or integers or booleans). For each row i of c, cell2mat concatenates all the components of the ith row of the cell c

Note that if the components of the cell input c are strings then cell2mat(c) returns a column vector of strings concatenation

Examples

c=makecell([2,2],[1 2 3; 6 7 8],[4 5;9 10],[11 12;16 17],[14 13 15;18 19 20])
cell2mat(c)

See Also

cell ,


cellstr

Scilab Function
Last update : 06/01/2006

cellstr - convert strings vector (or strings matrix) into a cell of strings

Calling Sequence

c=cellstr(s)

Parameters

  • s : strings vector, or strings matrix

Description

returns a cell array of strings

If s is a line vector of strings then cellstr(s) returns a (one-by-one) cell which contains one component (the concatenation of all columns components of s )
If s is a column vector of strings then cellstr(s) convert s into a cell which have the same size : (size(s,1)-by-one) cell of strings
If s is a matrix of strings then for each row i of s , cellstr(s) concatenates all the components of the ith rows of the matrix s (i.e s(i,1), s(i,2), s(i,3),...) and returns a ( size(s,1)-by-one) cell of strings

Examples

cellstr("foo")
cellstr(["sci","lab"])
cellstr(["abc","def",'gh';"i","j","klm"])

See Also

cell , string ,


char

Scilab Function
Last update : 06/01/2006

char - char function

Calling Sequence

y=char( x)
y=char(st1,st2,st3,....)

Parameters

  • x : a cell of strings arrays, or an array of ascii codes
  • st1,st2,st3 : strings arrays
  • y: a strings vector(column)

Description

One input argument :

Given a cell of strings arrays x , this function returns a strings vector y in which the rows are the components of the strings cell

Given an array of ascii codes x, this function returns a strings array y corresponding into ascii codes. If dims ( x )=[n1,n2,n3,n4,....],then returned value have same size as input value instead of second dims, dims( y )=[n1,n3,n4,..]

More than one input argument :

Given strings arrays st1,st2,st3,... , this function returns a vector of strings in which the rows are the components of st1,st2,st3,... In the vector y the length of all strings sti is completed by blanks, to have the same length than the lengthmax of sti.//

Examples

//Example with a hypermatrix of ascii codes :
x=hypermat([4,2,3],61:84);
y=char(x)
size(x)
size(y)

//Example with more than one argument :
st1="zeros";
st2=["one","two"];
st3=["three"];
y=char(st1,st2,st3)
size(y)
//all strings rows are completed by 'blanks' to have the same length : 6
length(y)

See Also

asciimat ,

Author

F.B


cmb_lin

Scilab Function
Last update : 16/06/2004

cmb_lin - combinaison linéaire symbolique

Calling Sequence

[x]=cmb_lin(alfa,x,beta,y)

Description

Évalue alfa*x-beta*y . alfa, beta, x, y sont des chaînes de caractères (routine de bas niveau).

See Also

mulf , addf ,


conj

Scilab Function
Last update : 16/06/2004

conj - conjugaison complexe

Calling Sequence

[y]=conj(x)

Parameters

  • x,y : vecteur ou matrice (réelle ou complexe)

Description

Les éléments de conj(x) sont les complexes conjugués des éléments de x .

Examples

x=[1+%i,-%i;%i,2*%i];
conj(x)
x'-conj(x)  // x' est la transposée conjuguée de x


coshm

Scilab Function
Last update : 16/06/2004

coshm - cosinus hyperbolique matriciel

Calling Sequence

t=coshm(x)

Parameters

  • x,t : matrice carrée réelle ou complexe

Description

coshm est le cosinus hyperbolique matriciel de la matrice x. t=(expm(x)+expm(-x))/2 . Le résultat peut être imprécis pour les matrices non symétriques.

Examples

A=[1,2;2,4]
acoshm(coshm(A))

See Also

cosh , expm ,


cosh

Scilab Function
Last update : 16/06/2004

cosh - cosinus hyperbolique

Calling Sequence

[y]=cosh(x)

Parameters

  • x : vecteur ou matrice réelle ou complexe.

Description

Pour un vecteur ou une matrice, les éléments de cosh(x) sont les cosinus hyperboliques des éléments de x. Pour le cosinus hyperbolique matriciel utiliser la fonction coshm(X) .

Examples

x=[0,1,%i]
acosh(cosh(x))

See Also

coshm , acosh ,


cosm

Scilab Function
Last update : 16/06/2004

cosm - cosinus matriciel

Calling Sequence

t=cosm(x)

Parameters

  • x,t : matrice réelle ou complexe

Description

cosm(x) est le cosinus matriciel de la matrice x. t=0.5*(expm(%i*x)+expm(-%i*x)) .

Examples

A=[1,2;3,4]
cosm(A)-0.5*(expm(%i*A)+expm(-%i*A))

See Also

cos , expm ,


cos

Scilab Function
Last update : 16/06/2004

cos - cosinus

Calling Sequence

[y]=cos(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)

Description

Pour un vecteur ou une matrice, les éléments de cos(x) sont les cosinus des éléments de x. Pour le cosinus matriciel utiliser la fonction cosm(X) .

Examples

x=[0,1,%i]
acos(cos(x))

See Also

cosm ,


cotg

Scilab Function
Last update : 16/06/2004

cotg - cotangente

Calling Sequence

[t]=cotg(x)

Parameters

  • x,t : vecteur ou matrice (réelle ou complexe)

Description

Les éléments de t sont les cotangentes des éléments de x . t=cos(x)./sin(x)

Examples

x=[1,%i];
cotg(x)-cos(x)./sin(x)

See Also

tan ,


cothm

Scilab Function
Last update : 16/06/2004

cothm - cotangente hyperbolique matricielle

Calling Sequence

[t]=cothm(x)

Description

cothm(x) est la cotangente hyperbolique matricielle de la matrice carrée x.

Examples

A=[1,2;3,4];
cothm(A)

See Also

coth ,


coth

Scilab Function
Last update : 16/06/2004

coth - cotangente hyperbolique

Calling Sequence

[t]=coth(x)

Parameters

  • x,t : vecteur ou matrice (réelle ou complexe)

Description

Les éléments de t sont les cotangentes hyperboliques des éléments de x .

Examples

x=[1,2*%i]
t=exp(x);
(t-ones(x)./t).\(t+ones(x)./t)
coth(x)

See Also

cotg ,


cshep2d

Scilab Function
Last update : 24/03/2004

cshep2d - bidimensional cubic shepard (scattered) interpolation

Calling Sequence

tl_coef = cshep2d(xyz)

Parameters

  • xyz : a n x 3 matrix of the (no gridded) interpolation points (the i th row given the (x,y) coordinates then the altitude z of the i th interpolation point)
  • tl_coef : a tlist scilab structure (of type cshep2d)

Description

This function is useful to define a 2d interpolation function when the interpolation points are not on a grid (you may use it in this case but splin2d is better for that purpose). The interpolant is a cubic shepard one and is a C2 (twice continuously differentiable) bivariate function s(x,y) such that : s(xi,yi)=zi for all i=1,..,n ( (xi,yi,zi) being the i th row of xyz ).

The evaluation of s at some points must be done by the eval_cshep2d function.

Remark

The function works if n >= 10, if the nodes are not all colinears (i.e. the (x,y) coordinates of the interpolation points are not on the same straight line), and if there is no duplicate nodes (i.e. 2 or more interpolation points with the same (x,y) coordinates). An error is issued if these conditions are not respected.

Examples

// interpolation of cos(x)cos(y) with randomly choosen interpolation points
n = 150; // nb of interpolation points
xy = grand(n,2,"unf",0,2*%pi);
z = cos(xy(:,1)).*cos(xy(:,2));
xyz = [xy z];
tl_coef = cshep2d(xyz);

// evaluation on a grid
m = 30;
xx = linspace(0,2*%pi,m);
[X,Y] = ndgrid(xx,xx);
Z = eval_cshep2d(X,Y, tl_coef);
xbasc()
plot3d(xx,xx,Z,flag=[2 6 4])
param3d1(xy(:,1),xy(:,2),list(z,-9), flag=[0 0])
xtitle("Cubic Shepard Interpolation of cos(x)cos(y) with randomly choosen interpolation points")
legends("interpolation points",-9,1)
xselect()

See Also

splin2d , eval_cshep2d ,

Authors

Robert J. Renka
B. Pincon (scilab interface)


cumprod

Scilab Function
Last update : 14/12/2005

cumprod - produit cumulatif.

Calling Sequence

y=cumprod(x)
y=cumprod(x,'r') ou y=cumprod(x,1)
y=cumprod(x,'c') ou y=cumprod(x,2)
y=cumprod(x,'m')

Parameters

  • x : vecteur ou matrice (réelle ou complexe)
  • y : vecteur ou matrice (réelle ou complexe)

Description

Pour un vecteur x , y=cumprod(x) renvoie dans y le produit cumulatif de tous les éléments de x . Si x est une matrice, elle est considérée comme un vecteur (les colonnes sont mises bout à bout).

y=cumprod(x,'c') (ou y=cumprod(x,2) ) renvoie dans y le produit cumulatif des éléments des lignes de x : y(i,:)=cumprod(x(i,:)) .

y=cumprod(x,'r') (ou y=cumprod(x,2) ) renvoie dans y le produit cumulatif des colonnes de x : y(:,i)=cumprod(x(:,i)) .

y=cumprod(x,'m') effectue le produit cumulatif selon la première dimension plus grande que 1 (compatibilité avec Matlab).

Examples

A=[1,2;3,4];
cumprod(A)
cumprod(A,'r')
cumprod(A,'c')
rand('seed',0);
a=rand(3,4);
[m,n]=size(a);
w=zeros(a);
w(1,:)=a(1,:);
for k=2:m;w(k,:)=w(k-1,:).*a(k,:);end;w-cumprod(a,'r')

See Also

cumsum , sum , prod ,


cumsum

Scilab Function
Last update : 14/12/2005

cumsum - somme cumulative.

Calling Sequence

y=cumsum(x)
y=cumsum(x,'r') ou y=cumsum(x,1)
y=cumsum(x,'c') ou y=cumsum(x,2)
y=cumsum(x,'m')

Parameters

  • x : vecteur ou matrice (entière, réelle ou complexe)
  • y : vecteur ou matrice (entière,réelle ou complexe)

Description

Pour un vecteur x , y=cumsum(x) renvoie dans y la somme cumulative de tous les éléments de x . Si x est une matrice, elle est considérée comme un vecteur (les colonnes sont mises bout à bout).

y=cumsum(x,'c') (ou y=cumsum(x,2) ) renvoie dans y la somme cumulative des éléments des lignes de x : y(i,:)=cumsum(x(i,:)) .

y=cumsum(x,'r') (ou y=cumsum(x,2) ) renvoie dans y la somme cumulative des colonnes de x : y(:,i)=cumsum(x(:,i)) .

y=cumsum(x,'m') effectue la somme cumulative selon la première dimension plus grande que 1 (compatibilité avec Matlab).

Examples

A=[1,2;3,4];
cumsum(A)
cumsum(A,'r')
cumsum(A,'c')
a=rand(3,4)+%i;
[m,n]=size(a);
w=zeros(a);
w(1,:)=a(1,:);
for k=2:m;w(k,:)=w(k-1,:)+a(k,:);end;w-cumsum(a,'r')

See Also

cumprod , sum , prod ,


delip

Scilab Function
Last update : 16/06/2004

delip - intégrale elliptique

Calling Sequence

[r]=delip(x,ck)

Parameters

  • x : réel (ou vecteur réel)
  • ck : scalaire entre -1 et 1
  • r : réel ou complexe (ou vecteur)

Description

Renvoie la valeur de l'intégrale elliptique avec le paramètre ck :

x réel et positif. Quand x est un vecteur r est évalué pour chaque composante de x .

Examples

ck=0.5;
delip([1,2],ck)
deff('y=f(t)','y=1/sqrt((1-t^2)*(1-ck^2*t^2))')
intg(0,1,f)    // OK puisque la solution est réelle !

See Also

amell , %asn , %sn ,


diag

Scilab Function
Last update : 16/06/2004

diag - extraction de diagonale ou construction d'une matrice à partir d'une diagonale.

Calling Sequence

[y]=diag(vm, [k])

Parameters

  • vm : vecteur ou matrice (stockage plein ou creux)
  • k : entier (valeur par défaut 0)
  • y : vecteur ou matrice

Description

Pour vm un n-vecteur (ligne ou colonne) diag(vm) renvoie une matrice diagonale avec les composantes de vm sur la diagonale principale.

diag(vm,k) est une matrice (n+abs(k))x(n+abs(k)) avec les composantes de vm sur la kième diagonale. k=0 correspond à la diagonale principale k>0 correspond aux diagonales supérieures et k<0 aux diagonales inférieures.

Pour une matrice vm , diag(vm,k) est le vecteur colonne dont les composantes sont les termes de la kième diagonale de vm . diag(vm) est la diagonale principale de vm . diag(diag(x)) est une matrice diagonale.

Si vm est une matrice creuse diag(vm,k) renvoie une matrice creuse.

Pour construire un système linéaire diagonal, utilisez sysdiag .

Notez que eye(A).*A renvoie une matrice diagonale avec les termes diagonaux de A . Ceci est valide pour tout type de matrice (constante, polynomiale, rationnelle, système dynamique linéaire, ...).

Examples

diag([1,2])

A=[1,2;3,4];
diag(A)  // diagonale principale
diag(A,1)

diag(sparse(1:10))  // matrice diagonale creuse

// Construction d'une matrice tridiagonale de taille 2*m+1
m=5;diag(-m:m) +  diag(ones(2*m,1),1) +diag(ones(2*m,1),-1)

See Also

sysdiag , sparse ,


diff

Scilab Function
Last update : 07/04/2004

diff - Difference and discrete derivative

Calling Sequence

y=diff(x)
y=diff(x [,n [,dim]])

Parameters

  • x : vector or matrix (real, complex, sparse or polynomial)
  • n : integer the order of differentiation
  • dim : integer or character string with values "r","c" and "*"
  • y : scalar or vector

Description

y=diff(x) compute the difference function y=x(2:$)-x(1:$-1)

diff(x,n,dim) is the n th difference function along dimension dim .

diff(x,n,"*") is equivalent to diff(x(:),n).

Default value for n is 1. Default value for dim is "*" .

dim='r' is equivalent to dim=1 and dim='c' is equivalent to dim=2 .

Examples

v=(1:8)^3;
diff(v)
diff(v,3)

A=[(1:8)^2
   (1:8)^3
   (1:8)^4];

diff(A,3,2)

//approximate differentiation
step=0.001
t=0:step:10;
y=sin(t);
dy=diff(sin(t))/step; //approximate differentiation of sine function
norm(dy-cos(t(1:$-1)),%inf)


dlgamma

Scilab Function
Last update : 16/06/2004

dlgamma - dérivée de la fonction gammaln ou fonction psi.

Calling Sequence

y = dlgamma(x)

Parameters

  • x : vecteur réel.
  • y : vecteur réel de même taille.

Description

dlgamma(x) calcule la dérivée de la fonction gammaln pour chaque composante de x .

          d/dx (gamma(x)) / gamma(x) = d/dx (ln gamma(x))

x doit être réel. Cette fonction est aussi connue sous le nom de fonction psi

Examples

dlgamma(0.5)

See Also

gamma , gammaln ,

Author

W. J. Cody (code from Netlib (specfun))


double

Scilab Function
Last update : 16/06/2004

double - conversion de type entier vers flottant double précision.

Calling Sequence

y=double(X)
y=int16(X)
y=int32(X)
y=uint8(X)
y=uint16(X)
y=uint32(X)

Parameters

  • X : matrice de flottants ou d'entiers
  • y : matrice de flottants

Description

Convertit des données sous forme d'entiers à 1,2 ou 4 octets au type flottant double précision. Si les composantes de X sont déjà des flottants double précision il n'y a pas de conversion.

Examples

x=int8([0 12 140])
double(x)

See Also

int8 , inttype , type ,


dsearch

Last update : 12/01/2004

dsearch - dichotomic (binary) search

Calling Sequence

[ind, occ, info] = dsearch(X, val [, ch ])

Parameters

  • X : a real (row or column) vector (1,m) or (m,1)
  • val : a real (row or column) vector with n components in strictly increasing order val(1) < val(2) < ... < val(n)
  • ch : (optionnal) a character "c" or "d" (default value "c")
  • ind : a real vector with the same dimensions than X
  • occ : a real vector with the same format than val (but with n-1 components in the case ch="c")
  • info : integer

Description

case ch="c"this is the interval case, for each X(i) search in which of the n-1 intervals it falls, the intervals being defined by :

            I1 = [val(1), val(2)]
            Ik = (val(k), val(k+1)] for 1 < k <= n-1 ;
ind(i)is the interval number of X(i) (0 if X(i) is not in [val(1),val(n)])
occ(k)is the number of components of X which are in Ik
infois the number of components of X which are not in [val(1),val(n)]
case ch="d"this is the discrete case, for each X(i) search if it is equal to one val(k)
ind(i)is equal to the index of the component of val which matches X(i) (ind(i) = k if X(i)=val(k)) or 0 if X(i) is not in val.
occ(k)is the number of components of X equal to val(k)
infois the number of components of X which are not in val

Examples

// example #1 (elementary stat for U(0,1))
m = 50000 ; n = 10;
X = grand(m,1,"def");
val = linspace(0,1,n+1)';
[ind, occ] = dsearch(X, val);
xbasc() ; plot2d2(val, [occ/m;0])  // no normalisation : y must be near 1/n

// example #2 (elementary stat for B(N,p))
N = 8 ; p = 0.5; m = 50000;
X = grand(m,1,"bin",N,p); val = (0:N)';
[ind, occ] = dsearch(X, val, "d");
Pexp = occ/m; Pexa = binomial(p,N);
xbasc() ; hm = 1.1*max(max(Pexa),max(Pexp));
plot2d3([val val+0.1], [Pexa' Pexp],[1 2],"111",  ...
        "Pexact@Pexp", [-1 0 N+1 hm],[0 N+2 0 6])
xtitle(  "binomial law B("+string(N)+","+string(p)+") :" ...
        +" exact probability versus experimental ones")

// example #3 (piecewise Hermite polynomial)
x = [0 ; 0.2 ; 0.35 ; 0.5 ; 0.65 ; 0.8 ;  1];
y = [0 ; 0.1 ;-0.1  ; 0   ; 0.4  ;-0.1 ;  0];
d = [1 ; 0   ; 0    ; 1   ; 0    ; 0   ; -1];
X = linspace(0, 1, 200)';
ind = dsearch(X, x);
// define Hermite base functions
deff("y=Ll(t,k,x)","y=(t-x(k+1))./(x(k)-x(k+1))")   // Lagrange left on Ik
deff("y=Lr(t,k,x)","y=(t-x(k))./(x(k+1)-x(k))")     // Lagrange right on Ik
deff("y=Hl(t,k,x)","y=(1-2*(t-x(k))./(x(k)-x(k+1))).*Ll(t,k,x).^2")
deff("y=Hr(t,k,x)","y=(1-2*(t-x(k+1))./(x(k+1)-x(k))).*Lr(t,k,x).^2")
deff("y=Kl(t,k,x)","y=(t-x(k)).*Ll(t,k,x).^2")
deff("y=Kr(t,k,x)","y=(t-x(k+1)).*Lr(t,k,x).^2")
// plot the curve
Y = y(ind).*Hl(X,ind) + y(ind+1).*Hr(X,ind) + d(ind).*Kl(X,ind) + d(ind+1).*Kr(X,ind);
xbasc(); plot2d(X,Y,2) ; plot2d(x,y,-9,"000")
xtitle("an Hermite piecewise polynomial")
// NOTE : you can verify by adding these ones :
// YY = interp(X,x,y,d); plot2d(X,YY,3,"000")

See Also

find ,

Author

B.P.


erfcx

Scilab Function
Last update : 16/06/2004

erfcx - fonction erreur complémentaire normalisée.

Calling Sequence

y = erfcx(x)

Parameters

  • x : vecteur réel
  • y : vecteur réel (de même taille que x)

Description

erfcx calcule la fonction erreur complémentaire normalisée.

               2
      y = exp(x ) * erfc(x)

                 1
      y  -->  ---------    when x --> +oo
              x sqrt(pi)

See Also

erf , erfc , calerf ,

Author

W. J. Cody (code from Netlib (specfun))


erfc

Scilab Function
Last update : 16/06/2004

erfc - fonction erreur complémentaire.

Calling Sequence

y = erfc(x)

Parameters

  • x : vecteur réel
  • y : vecteur réel (de même taille que x)

Description

erfc calcule la fonction erreur complémentaire.

                    /+oo    2
             2      |     -t
      y = -------   |    e    dt
          sqrt(pi)  |
                    /x

      y = 1 - erf(x)

Examples

erf([0.5,0.2])+erfc([0.5,0.2])

See Also

erf , erfcx , calerf ,

Author

W. J. Cody (code from Netlib (specfun))


erf

Scilab Function
Last update : 16/06/2004

erf - fonction erreur

Calling Sequence

y = erf(x)

Parameters

  • x : vecteur réel
  • y : vecteur réel (de même taille que x)

Description

erf calcule la fonction erreur:

                     /x     2
             2       |    -t
      y = -------    |   e    dt
          sqrt(pi)  /0

Examples

deff('y=f(t)','y=exp(-t^2)');
erf(0.5)-2/sqrt(%pi)*intg(0,0.5,f)

See Also

erfc , erfcx , calerf ,

Author

W. J. Cody (code from Netlib (specfun))


eval_cshep2d

Scilab Function
Last update : 06/07/2004

eval_cshep2d - bidimensional cubic shepard interpolation evaluation

Calling Sequence

[zp [,dzpdx, dzpdy [,d2zpdxx,d2zpdxy,d2zpdyy]]] = eval_cshep2d(xp, yp, tl_coef)

Parameters

  • xp, yp : two real vectors (or matrices) of the same size
  • tl_coef : a tlist scilab structure (of type cshep2d) defining a cubic Shepard interpolation function (named S in the following)
  • zp : vector (or matrix) of the same size than xp and yp , evaluation of the interpolant S at these points
  • dzpdx,dzpdy : vectors (or matrices) of the same size than xp and yp , evaluation of the first derivatives of S at these points
  • d2zpdxx,d2zpdxy,d2zpdyy : vectors (or matrices) of the same size than xp and yp , evaluation of the second derivatives of S at these points

Description

This is the evaluation routine for cubic Shepard interpolation function computed with cshep2d , that is :

      zp(i) = S(xp(i),yp(i))
      dzpdx(i) = dS/dx(xp(i),yp(i))
      dzpdy(i) = dS/dy(xp(i),yp(i))
      d2zpdxx(i) = d2S/dx2(xp(i),yp(i))
      d2zpdxy(i) = d2S/dxdy(xp(i),yp(i))
      d2zpdyy(i) = d2S/dy2(xp(i),yp(i))

Remark

The interpolant S is C2 (twice continuously differentiable) but is also extended by zero for (x,y) far enough the interpolation points. This leads to a discontinuity in a region far outside the interpolation points, and so, is not cumbersome in practice (in a general manner, evaluation outside interpolation points (i.e. extrapolation) leads to very inacurate results).

Examples

// see example section of cshep2d

// this example shows the behavior far from the interpolation points ...
deff("z=f(x,y)","z = 1+ 50*(x.*(1-x).*y.*(1-y)).^2")
x = linspace(0,1,10);
[X,Y] = ndgrid(x,x);
X = X(:); Y = Y(:); Z = f(X,Y);
S = cshep2d([X Y Z]);
// evaluation inside and outside the square [0,1]x[0,1]
m = 40;
xx = linspace(-1.5,0.5,m);
[xp,yp] = ndgrid(xx,xx);
zp = eval_cshep2d(xp,yp,S);
// compute facet (to draw one color for extrapolation region
// and another one for the interpolation region)
[xf,yf,zf] = genfac3d(xx,xx,zp);
color = 2*ones(1,size(zf,2));
// indices corresponding to facet in the interpolation region
ind=find( mean(xf,"r")>0 & mean(xf,"r")<1 & mean(yf,"r")>0 & mean(yf,"r")<1 );
color(ind)=3;
xbasc();
plot3d(xf,yf,list(zf,color), flag=[2 6 4])
legends(["extrapolation region","interpolation region"],[2 3],1)
xselect()

See Also

cshep2d ,

Authors

Robert J. Renka
B. Pincon (scilab interface)


eval

Scilab Function
Last update : 16/06/2004

eval - évaluation d'une matrice de chaînes de caractères

Calling Sequence

[H]= eval(Z)

Description

renvoie le résultat de l'évaluation d'une matrice de chaînes de caractères Z .

Examples

a=1; b=2; Z=['a','sin(b)'] ; eval(Z)  // renvoie la matrice [1,0.909];

See Also

evstr , execstr ,


eye

Scilab Function
Last update : 16/06/2004

eye - matrice identité

Calling Sequence

X=eye(m,n)
X=eye(A)
X=eye()

Parameters

  • A,X : matrices ou listes de type syslin .
  • m,n : entiers

Description

Renvoie, suivant les arguments, une matrice m x n avec des 1 sur la diagonale principale ou une matrice identité de même taille que A .

Attention : eye(10) est équivalent à eye(A) avec A=10 c'est à dire 1 . (Ce n'est pas une matrice identité 10 x 10!).

Si A est un système linéaire représenté par une liste de type syslin , eye(A) renvoie une eye matrice de dimension appropriées : (nombre de sorties x nombre d'entrées).

eye() renvoie une matrice identité de dimension non définie. Ses dimensions sont définies quand cette matrice est ajoutée à une matrice de dimensions fixées.

Examples

eye(2,3)
A=rand(2,3);eye(A)
s=poly(0,'s');A=[s,1;s,s+1];eye(A)
A=[1/s,1;s,2];eye(A);
A=ssrand(2,2,3);eye(A)
[1 2;3 4]+2*eye()

See Also

ones , zeros ,


factorial

Scilab Function
Last update : 28/09/2006

factorial - retourne factorielle

Calling Sequence

y=factorial(n)

Parameters

  • n : un scalaire, vecteur, matrice, ou hypermatrice d'entiers positifs
  • y : un scalaire, vecteur, matrice, ou hypermatrice

Description

factorial(n) retoune factotielle n, si n est de dimension superieur à 1 alors factorial(n) retourne factorielle composante par composante ( x et y ont la meme taille)

Examples

// n scalaire
n=4
y=factorial(n)
// n matrice
n=[2 6 8;5 4 3]
y=factorial(n)
// n hypermatrice
n=matrix(1:12,[2,2,3])
y=factorial(n)


fix

Scilab Function
Last update : 16/06/2004

fix - arrondi vers zéro ou troncature

Calling Sequence

[y]=fix(x)

Parameters

  • x : matrice réelle
  • y : matrice d'entiers

Description

fix(x) renvoie une matrice d'entiers dont les éléments sont les arrondis vers zéro des éléments de x (la partie décimale est supprimée) c'est à dire que y=sign(x).*floor(abs(x)) . Cette fonction est la même que la fonction int .

See Also

round , floor , ceil , int ,


floor

Scilab Function
Last update : 16/06/2004

floor - partie entière

Calling Sequence

[y]=floor(x)

Parameters

  • x : matrice réelle
  • y : matrice entière

Description

Renvoie dans y pour chaque élément de x sa partie entière (l'entier directement inférieur).

Examples

floor([1.9 -2.5])-[1,-3]
floor(-%inf)
x=rand()*10^20;floor(x)-x

See Also

round , floor , int ,


frexp

Scilab Function
Last update : 16/06/2004

frexp - calcule la représentation en base 2 (mantisse et exposant) d'un nombre flottant.

Calling Sequence

[f,e]=frexp(x)

Parameters

  • x : matrice ou vecteur réel
  • f : matrice ou vecteur réel, habituellement dans l'intervalle 0.5 <= abs(f) < 1.
  • e : matrice ou vecteur d'entiers satisfaisant l'équation: x = f.*2.^e

Description

Cette fonction correspond à la fonction ANSI C frexp(). Chaque 0 dans x produit f=0 et e=0 .

Examples

[f,e]=frexp([1,%pi,-3,%eps])

See Also

log , hat , ieee , log2 ,


full

Scilab Function
Last update : 12/01/2004

full - sparse to full matrix conversion

Calling Sequence

X=full(sp)

Parameters

  • sp : real or complex sparse (or full) matrix
  • X : full matrix

Description

X=full(sp) converts the sparse matrix sp into its full representation. (If sp is already full then X equals sp ).

Examples

sp=sparse([1,2;5,4;3,1],[1,2,3]);
A=full(sp)

See Also

sparse , sprand , speye ,


gammaln

Scilab Function
Last update : 16/06/2004

gammaln - Le logarithme de la fonction gamma.

Calling Sequence

y = gammaln(x)

Parameters

  • x : vecteur ou matrice de nombres réels.
  • y : vecteur ou matrice de nombres réels de même taille que x.

Description

gammaln(x) évalue le logarithme de la fonction gamma pour les composantes de x ., en évitant les valeurs conduisant à un underflow ou un overflow. x doit être à composantes réelles.

Examples

gammaln(0.5)

See Also

gamma , dlgamma ,

Author

W. J. Cody and L. Stoltz (code from Netlib (specfun))


gamma

Scilab Function
Last update : 06/07/2004

gamma - The gamma function.

Calling Sequence

y = gamma(x)

Parameters

  • x : real vector or matrix
  • y : real vector or matrix with same size than x.

Description

gamma(x) evaluates the gamma function at all the elements of x . The gamma function is defined by :

                     /+oo
                     |   x-1  -t
         gamma(x) =  |  t    e    dt
                     /0

and generalizes the factorial function for real numbers ( gamma(n+1) = n! ).

Examples

// simple examples
gamma(0.5)
gamma(6)-prod(1:5)

// the graph of the Gamma function on [a,b]
a = -3; b = 5;
x = linspace(a,b,40000)';
y = gamma(x);
xbasc()
c=xget("color")
xset("color",2)
plot2d(x, y, style=0, axesflag=5, rect=[a, -10, b, 10])
xset("color",c)
xtitle("The gamma function on ["+string(a)+","+string(b)+"]")
xselect()

See Also

gammaln , dlgamma ,

Author

W. J. Cody and L. Stoltz (code from Netlib (specfun))


gsort

Scilab Function
Last update : 16/06/2004

gsort - tri par ordre décroissant

Calling Sequence

[s, [k]]=gsort(v )
[s, [k]]=gsort(v,flag1)
[s, [k]]=gsort(v,flag1,flag2)

Parameters

  • v,s : vecteur ou matrice de nombres réels ou de chaînes de caractères.
  • flag1 : la chaîne de caractères 'r' , 'c' , 'g' , 'lr' et 'lc' .
  • flag2 : la chaîne de caractères 'i' pour l'ordre croissant et 'd' pour l'ordre décroissant. k : vecteur ou matrice de nombres entiers.

Description

gsort est similaire à sort avec des propriétés supplémentaires. Le troisième argument peut être utilisé pour choisir entre tri croissant ou décroissant. Le deuxième argument est utilisé pour l'ordre lexical.

[s,k]=gsort(a,'g') et [s,k]=gsort(a,'g','d') produisent le même résultat que [s,k]=gsort(a) . Ces instructions produisent un tri de la matrice a , a vue comme un vecteur a(:) (les colonnes sont empilées). [s,k]=gsort(a,'g','i') fonctionne de la même manière pour l'ordre croissant.

[s,k]=gsort(a,'lr') trie les lignes de la matrice int(a) (si a est une matrice réelle ou une matrice de chaînes de caractères) dans l'ordre lexical décroissant. s est obtenue par une permutation des lignes de la matrice int(a) (ou a ) donnée par le vecteur k ) de telle manière que les lignes de s vérifient s(i,:) > s(j,:) si i<j . [s,k]=gsort(a,'lr','i') fonctionne de la même manière pour l'ordre lexical croissant.

[s,k]=gsort(a,'lc') trie les colonnes de la matrice int(a) (si a est une matrice réelle ou une matrice de chaînes de caractères) dans l'ordre lexical décroissant. s est obtenue par une permutation des colonnes de la matrice int(a) (ou a ) donnée par le vecteur k ) de telle manière que les colonnes de s vérifient s(:,i) > s(:,j) si i<j . [s,k]=gsort(a,'lc','i') fonctionne de la même manière pour l'ordre lexical croissant.

Examples

alr=[1,2,2;
     1,2,1;
     1,1,2;
     1,1,1];
[alr1,k]=gsort(alr,'lr','i')
[alr1,k]=gsort(alr,'lc','i')

See Also

find ,


imag

Scilab Function
Last update : 16/06/2004

imag - partie imaginaire

Calling Sequence

[y]=imag(x)

Parameters

  • x : matrice réelle ou complexe.
  • y : matrice réelle.

Description

imag(x) renvoie la partie imaginaire de x (voir %i pour entrer des nombres complexes).

See Also

real ,


imult

Scilab Function
Last update : 12/01/2004

imult - multiplication by i the imaginary unitary

Calling Sequence

y=imult(x)

Parameters

  • x : real or complex scalar, vector or matrix
  • y : complex scalar, vector or matrix

Description

imult(x) is a more efficient way to multiply x by i than y = %i*x, without the problems occuring when x comprises "special" floating point numbers as %inf and %nan.

Examples

z1 = imult(%inf)
z2 = %i * %inf

Author

B.P.;


ind2sub

Scilab Function
Last update : 12/01/2004

ind2sub - linear index to matrix subscript values

Calling Sequence

[i1,i2,..] =ind2sub(dims,I)
Mi = ind2sub(dims,I)

Parameters

  • dims : vector: the matrix dimensions
  • I : vector: the given linear index
  • i1,i2,.. : the subscript values (same matrix shape as I )
  • Mi : matrix whose columns contains the subscript values.

Description

ind2sub is used to determine the equivalent subscript values corresponding to a given single index into an array. [i1,i2,..] = ind2sub(dims,I) returns the arrays i1 , i2 , ... containing the equivalent row, column, ... subscripts corresponding to the index matrix I for a matrix of size dims . Mi=ind2sub(dims,I) returns a matrix Mi whose columns are the arrays i1(:) , i2(:) , ...

Examples

   ind2sub([2,3,2],1:12)
   [i,j,k]=ind2sub([2,3,2],1:12)

See Also

sub2ind , extraction , insertion ,

Author

Serge Steer, INRIA


int8 int16int32uint8 uint16uint32

Scilab Function
Last update : 16/06/2004

int8 - conversion au codage entier à 1 octet

int16 - conversion au codage entier à 2 octets

int32 - conversion au codage entier à 4 octets

uint8 - conversion au codage entier non signé à 1 octet

uint16 - conversion au codage entier non signé à 2 octets

uint32 - conversion au codage entier non signé à 4 octets

Calling Sequence

y=int8(X)
y=int16(X)
y=int32(X)
y=uint8(X)
y=uint16(X)
y=uint32(X)

Parameters

  • X : matrice de flottants ou d'entiers
  • y : matrice d'entiers codés sur 1,2 ou 4 octets.

Description

Convertit et stocke sous forme d'entiers. Ces types de données sont particulièrement intéressants pour stocker des images, de longs signaux, ...

y=int8(X): renvoie et stocke dans y des entiers dans l'intervalle [-128,127]
y=uint8(X): renvoie et stocke dans y des entiers dans l'intervalle [0,255]
y=int16(X): renvoie et stocke dans y des entiers dans l'intervalle [-32768,32767]
y=uint16(X): renvoie et stocke dans y des entiers dans l'intervalle [0, 65535]
y=int32(X): renvoie et stocke dans y des entiers dans l'intervalle [-2147483648,2147483647]
y=uint32(X): renvoie et stocke dans y des entiers dans l'intervalle [0, 4294967295]

Examples

int8([1 -120 127 312])
uint8([1 -120 127 312])

x=int32(-200:100:400)
int8(x)

See Also

double , inttype , iconvert ,


integrate

Scilab Function
Last update : 16/06/2004

integrate - intégration numérique

Calling Sequence

[x]=integrate(expr,v,x0,x1 [,ea [,er]])

Parameters

  • expr : chaîne de caractères (expression scilab)
  • v : chaîne de caractères (variable d'intégration)
  • x0,x1 : nombres réels (bornes d'intégration)
  • ea : nombre réel (borne sur l'erreur absolue) par défaut : 0
  • er : nombre réel, (borne sur l'erreur relative) par défaut : 1.d-8

Description

calcule :

                       /x1
                      [
                  x = I  f(v)dv
                      ]
                     /x0

L'approximation satisfait (on l'espère) l'affirmation suivante sur l'erreur : abs(I-x)<= max(ea,er*abs(I)) où I représente la valeur exacte de l'intégrale.

Examples

integrate('sin(x)','x',0,%pi)
integrate(['if x==0 then 1,';
           'else sin(x)/x,end'],'x',0,%pi)

See Also

intg , inttrap , intsplin , ode ,


interp1

Scilab Function
Last update : 06/01/2006

interp1 - one_dimension interpolation function

Calling Sequence

[yp]=interp1(x, y,xp [, method,[extrapolation]])

Parameters

  • xp : reals scalar, vector or matrix (or hypermatrix)
  • x : reals vector
  • method : (optional) string defining the interpolation method
  • extrapolation : (optional) string, or real value defining the yp(j) components for xp(j) values outside [x1,xn] interval.
  • yp : vector, or matrix (or hypermatrix)

Description

Given (x,y,xp) , this function performs the yp components corresponding to xp by the interpolation(linear by default) defined by x and y.

If yp is a vector then the length of xp is equal to the length of yp, if yp is a matrix then xp have the same length than the length of each columns of yp, if yp is a hypermatrix then the length of xp have the same length than the first dimension of yp.

If size(y)=[C,M1,M2,M3,...,Mj] and size(xp)=[N1,N2,N3,...,Nk] then size(yp)=[N1,N2,..,Nk,M1,M2,...Mj] and length of x must be equal to size(y,1)

The method parameter sets the evaluation rule for interpolation

  • "linear" : the interpolation is defined by linear method (see interpln )
  • "spline" : the interpolation is defined by cubic spline interpolation ( see splin , interp )
  • "nearest" : for each value xp(j), yp(j) takes the value or y(i) corresponding to x(i) the nearest neighbor of xp(j)

    • The extrapolation parameter sets the evaluation rule for extrapolation, i.e for xp(i) not in [x1,xn] interval

  • "extrap" : the extrapolation is performed by the defined method. yp=interp1(x,y,xp,method,"extrap")
  • real value : you can choose a real value for extrapolation, in this way yp(i) takes this value for xp(i) not in [x1,xn] interval, for example 0 (but also nan or inf). yi=interp1(x,y,xp,method, 0)
  • by default : the extrapolation is performed by the defined method (for spline method), and by nan for linear and nearest methods. yp=interp1(x,y,xp,method)

    • Examples

    x=linspace(0,3,20);
y=x^2;
xx=linspace(0,3,100);
yy1=interp1(x,y,xx,'linear');
yy2=interp1(x,y,xx,'spline');
yy3=interp1(x,y,xx,'nearest');
plot(xx,[yy1;yy2;yy3],x,y,'*')
xtitle('interpolation of square function')
legend(['linear','spline','nearest'],a=2)

    See Also

    interp , interpln , splin ,

    Author

    F.B


interp2d

Scilab Function
Last update : 24/03/2004

interp2d - bicubic spline (2d) evaluation function

Calling Sequence

[zp[,dzpdx,dzpdy[,d2zpdxx,d2zpdxy,d2zpdyy]]]=interp2d(xp,yp,x,y,C [,out_mode])

Parameters

  • xp, yp : real vectors or matrices of same size
  • x,y,C : real vectors defining a bicubic spline or sub-spline function (called s in the following)
  • out_mode : (optionnal) string defining the evaluation of s outside [x(1),x(nx)]x[y(1),y(ny)]
  • zp : vector or matrix of same format than xp and yp , elementwise evaluation of s on these points.
  • dzpdx, dzpdy : vectors (or matrices) of same format than xp and yp , elementwise evaluation of the first derivatives of s on these points.
  • d2zpdxx, d2zpdxy, d2zpdyy : vectors (or matrices) of same format than xp and yp , elementwise evaluation of the second derivatives of s on these points.

Description

Given three vectors (x,y,C) defining a bicubic spline or sub-spline function (see splin2d ) this function evaluates s (and ds/dx, ds/dy, d2s/dxx, d2s/dxy, d2s/dyy if needed) at (xp(i),yp(i)) :

      zp(i) = s(xp(i),yp(i))
      dzpdx(i) = ds/dx(xp(i),yp(i))
      dzpdy(i) = ds/dy(xp(i),yp(i))
      d2zpdxx(i) = d2s/dx2(xp(i),yp(i))
      d2zpdxy(i) = d2s/dxdy(xp(i),yp(i))
      d2zpdyy(i) = d2s/dy2(xp(i),yp(i))

The out_mode parameter defines the evaluation rule for extrapolation, i.e. for (xp(i),yp(i)) not in [x(1),x(nx)]x[y(1),y(ny)]:

  • "by_zero" : an extrapolation by zero is done
  • "by_nan" : extrapolation by Nan
  • "C0" : the extrapolation is defined as follows :
         s(x,y) = s(proj(x,y)) where proj(x,y) is nearest point
                           of [x(1),x(nx)]x[y(1),y(ny)] from (x,y)
  • "natural" : the extrapolation is done by using the nearest bicubic-patch from (x,y).
  • "periodic" : s is extended by periodicity.

    • Examples

    // see the examples of splin2d

// this example shows some different extrapolation features
// interpolation of cos(x)cos(y)
n = 7;  // a n x n interpolation grid
x = linspace(0,2*%pi,n); y = x;
z = cos(x')*cos(y);
C = splin2d(x, y, z, "periodic");

// now evaluate on a bigger domain than [0,2pi]x [0,2pi]
m = 80; // discretisation parameter of the evaluation grid
xx = linspace(-0.5*%pi,2.5*%pi,m); yy = xx;
[XX,YY] = ndgrid(xx,yy);
zz1 = interp2d(XX,YY, x, y, C, "C0");
zz2 = interp2d(XX,YY, x, y, C, "by_zero");
zz3 = interp2d(XX,YY, x, y, C, "periodic");
zz4 = interp2d(XX,YY, x, y, C, "natural");
xbasc()
subplot(2,2,1)
  plot3d(xx, yy, zz1, flag=[2 6 4])
  xtitle("extrapolation with the C0 outmode")
subplot(2,2,2)
  plot3d(xx, yy, zz2, flag=[2 6 4])
  xtitle("extrapolation with the by_zero outmode")
subplot(2,2,3)
  plot3d(xx, yy, zz3, flag=[2 6 4])
  xtitle("extrapolation with the periodic outmode")
subplot(2,2,4)
  plot3d(xx, yy, zz4, flag=[2 6 4])
  xtitle("extrapolation with the natural outmode")
xselect()

    See Also

    splin2d ,

    Author

    B. Pincon


interp3d

Scilab Function
Last update : 24/03/2004

interp3d - 3d spline evaluation function

Calling Sequence

[fp[,dfpdx,dfpdy,dfpdz]]=interp3d(xp,yp,zp,tl,out_mode)

Parameters

  • xp, yp, zp : real vectors or matrices of same size
  • tl : tlist of type "splin3d", defining a 3d tensor spline (called s in the following)
  • out_mode : (optionnal) string defining the evaluation of s outside the grid ([xmin,xmax]x[ymin,ymax]x[zmin,zmax])
  • fp : vector or matrix of same format than xp , yp and zp , elementwise evaluation of s on these points.
  • dfpdx, dfpdy, dfpdz : vectors (or matrices) of same format than xp , yp and zp , elementwise evaluation of the first derivatives of s on these points.

Description

Given a tlist tl defining a 3d spline function (see splin3d ) this function evaluates s (and ds/dx, ds/dy, ds/dz if needed) at (xp(i),yp(i),zp(i)) :

      zp(i) = s(xp(i),yp(i))
      dzpdx(i) = ds/dx(xp(i),yp(i),zp(i))
      dzpdy(i) = ds/dy(xp(i),yp(i),zp(i))
      dzpdz(i) = ds/dz(xp(i),yp(i),zp(i))

The out_mode parameter defines the evaluation rule for extrapolation, i.e. for (xp(i),yp(i),zp(i)) not in [xmin,xmax]x[ymin,ymax]x[zmin,zmax]:

  • "by_zero" : an extrapolation by zero is done
  • "by_nan" : extrapolation by Nan
  • "C0" : the extrapolation is defined as follows :
         s(x,y) = s(proj(x,y)) where proj(x,y) is nearest point
                           of [x(1),x(nx)]x[y(1),y(ny)] from (x,y)
  • "periodic" : s is extended by periodicity.

    • Examples

    // see the examples of the splin3d help page

    See Also

    splin3d , bsplin3val ,

    Authors

    R.F. Boisvert, C. De Boor (code from the CMLIB fortran lib)
    B. Pincon (scilab interface)


interpln

Scilab Function
Last update : 16/06/2004

interpln - interpolation linéaire

Calling Sequence

[y]=interpln(xyd,x)

Parameters

  • xyd : matrice à deux lignes (coordonnées x et y des points)
  • x : vecteur des abscisses
  • y : vecteur des ordonnées

Description

Étant donné xyd un ensemble de points dans le plan avec des abscisses croissantes et x un ensemble d'abscisses, cette fonction renvoie dans y les ordonnées correspondantes, calculées par interpolation linéaire.

Examples

x=[1 10 20 30 40];
y=[1 30 -10 20 40];
plot2d(x',y',[-3],"011"," ",[-10,-40,50,50]);
yi=interpln([x;y],-4:45);
plot2d((-4:45)',yi',[3],"000");

See Also

splin , interp , smooth ,


interp

Scilab Function
Last update : 06/07/2004

interp - cubic spline evaluation function

Calling Sequence

[yp [,yp1 [,yp2 [,yp3]]]]=interp(xp, x, y, d [, out_mode])

Parameters

  • xp : real vector or matrix
  • x,y,d : real vectors of the same size defining a cubic spline or sub-spline function (called s in the following)
  • out_mode : (optionnal) string defining the evaluation of s outside the [x1,xn] interval
  • yp : vector or matrix of same size than xp , elementwise evaluation of s on xp (yp(i)=s(xp(i) or yp(i,j)=s(xp(i,j))
  • yp1, yp2, yp3 : vectors (or matrices) of same size than xp , elementwise evaluation of the successive derivatives of s on xp

Description

Given three vectors (x,y,d) defining a spline or sub-spline function (see splin ) with yi=s(xi), di = s'(xi) this function evaluates s (and s', s'', s''' if needed) at xp(i) :

      yp(i) = s(xp(i))    or  yp(i,j) = s(xp(i,j))
      yp1(i) = s'(xp(i))   or  yp1(i,j) = s'(xp(i,j))
      yp2(i) = s''(xp(i))   or  yp2(i,j) = s''(xp(i,j))
      yp3(i) = s'''(xp(i))   or  yp3(i,j) = s'''(xp(i,j))

The out_mode parameter set the evaluation rule for extrapolation, i.e. for xp(i) not in [x1,xn] :

  • "by_zero" : an extrapolation by zero is done
  • "by_nan" : extrapolation by Nan
  • "C0" : the extrapolation is defined as follows :
          s(x) = y1  for  x < x1
      s(x) = yn  for  x > xn
  • "natural" : the extrapolation is defined as follows (p_i being the polynomial defining s on [x_i,x_{i+1}]) :
          s(x) = p_1(x)      for  x < x1
      s(x) = p_{n-1}(x)  for  x > xn
  • "linear" : the extrapolation is defined as follows :
          s(x) = y1 + s'(x1)(x-x1)  for  x < x1
      s(x) = yn + s'(xn)(x-xn)  for  x > xn
  • "periodic" : s is extended by periodicity.

    • Examples

    // see the examples of splin and lsq_splin

// an example showing C2 and C1 continuity of spline and subspline
a = -8; b = 8;
x = linspace(a,b,20)';
y = sinc(x);
dk = splin(x,y);  // not_a_knot
df = splin(x,y, "fast");
xx = linspace(a,b,800)';
[yyk, yy1k, yy2k] = interp(xx, x, y, dk);
[yyf, yy1f, yy2f] = interp(xx, x, y, df);
xbasc()
subplot(3,1,1)
plot2d(xx, [yyk yyf])
plot2d(x, y, style=-9)
legends(["not_a_knot spline","fast sub-spline","interpolation points"],...
        [1 2 -9], "ur",%f)
xtitle("spline interpolation")
subplot(3,1,2)
plot2d(xx, [yy1k yy1f])
legends(["not_a_knot spline","fast sub-spline"], [1 2], "ur",%f)
xtitle("spline interpolation (derivatives)")
subplot(3,1,3)
plot2d(xx, [yy2k yy2f])
legends(["not_a_knot spline","fast sub-spline"], [1 2], "lr",%f)
xtitle("spline interpolation (second derivatives)")

// here is an example showing the different extrapolation possibilities
x = linspace(0,1,11)';
y = cosh(x-0.5);
d = splin(x,y);
xx = linspace(-0.5,1.5,401)';
yy0 = interp(xx,x,y,d,"C0");
yy1 = interp(xx,x,y,d,"linear");
yy2 = interp(xx,x,y,d,"natural");
yy3 = interp(xx,x,y,d,"periodic");
xbasc()
plot2d(xx,[yy0 yy1 yy2 yy3],style=2:5,frameflag=2,leg="C0@linear@natural@periodic")
xtitle(" different way to evaluate a spline outside its domain")

    See Also

    splin , lsq_splin ,

    Author

    B. Pincon


intersect

Scilab Function
Last update : 16/06/2004

intersect - recherche de valeurs communes à deux vecteurs.

Calling Sequence

[v, [ka,kb]]=intersect(a,b)

Parameters

  • a : vecteur de nombres réels ou de chaînes de caractères
  • b : vecteur de nombres réels ou de chaînes de caractères
  • v : vecteur ligne de nombres réels ou de chaînes de caractères
  • ka : vecteur ligne d'entiers
  • kb : vecteur ligne d'entiers

Description

intersect(a,b) renvoie un vecteur trié des valeurs communes à a et b .

[v,ka,kb]=intersect(a,b) renvoie aussi deux vecteurs d'indices ka et kb tels que v=a(ka) et v=b(kb) .

Examples

A=round(5*rand(10,1));
B=round(5*rand(7,1));

intersect(A,B)
[N,ka,kb]=intersect(A,B)

intersect('a'+string(A),'a'+string(B))

See Also

unique , sort , union ,


intsplin

Scilab Function
Last update : 16/06/2004

intsplin - intégration approchée de données expérimentales utilisant une interpolation par une spline.

Calling Sequence

v = intsplin([x,] s)

Parameters

  • x : vecteur des abscisses, classées par ordre croissant. La valeur par défaut est 1:size(y,'*')
  • s : vecteur des ordonnées.
  • v : valeur de l'approximation de l'intégrale

Description

Calcule une approximation de :

où f est donnée sous forme de valeurs expérimentales :

s(i)=f(x(i)) et x0=x(1) , x1=x(n)

Entre les points, f est approchée à l'aide d'une spline.

Examples

t=0:0.1:%pi
intsplin(t,sin(t))

See Also

intg , intc , intl , integrate , inttrap , splin ,


inttrap

Scilab Function
Last update : 16/06/2004

inttrap - intégration approchée de données expérimentales avec la méthode des trapèzes.

Calling Sequence

v = inttrap([x,] s)

Parameters

  • x : vecteur des abscisses, classées par ordre croissant. La valeur par défaut est 1:size(y,'*')
  • s : vecteur des ordonnées.
  • v : valeur de l'approximation de l'intégrale

Description

Calcule une approximation de :

où f est donnée sous forme de valeurs expérimentales :

s(i)=f(x(i)) et x0=x(1) , x1=x(n)

Entre les points, f est approchée linéairement.

Examples

t=0:0.1:%pi
inttrap(t,sin(t))

See Also

intg , intc , intl , integrate , intsplin , splin ,


int

Scilab Function
Last update : 16/06/2004

int - arrondi vers zéro ou troncature

Calling Sequence

[y]=int(X)

Parameters

  • X : matrice réelle
  • y : matrice d'entiers

Description

int(X) renvoie une matrice d'entiers dont les éléments sont les arrondis vers zéro des éléments de x. Cette fonction est la même que la fonction fix .

See Also

round , floor , ceil , fix ,


iscellstr

Scilab Function
Last update : 09/11/2006

iscellstr - verifie si toutes les composantes d'une cell sont des strings

Calling Sequence

y=iscellstr(c)

Parameters

  • c : une cell.
  • x : un double (0 ou 1).

Description

Etant donné une cell c , la fonction iscellstr retourne 1 si toutes les composantes de la cell sont des strings sinon elle retourne 0 .

Examples

// exemple 1 :
c=makecell([1,3],'foo1','foo2','foo3');
y=iscellstr(c)

// exemple 2 :
c=makecell([1,3],'foo1',5,'foo3');;
y=iscellstr(c)

See Also

cell , makecell ,


isdef

Scilab Function
Last update : 16/06/2004

isdef - vérifie si une variable existe

Calling Sequence

isdef(name [,where])

Parameters

  • name : une chaîne de caractères.
  • where : une chaîne de caractères valant par défaut 'all'

Description

isdef(name) renvoie %T (vrai) si la variable 'name' existe et %F (faux) sinon.

isdef(name,'local') renvoie %T si la variable 'name' existe dans l'environnement local de la fonction courante et %F sinon.

Examples

A=1;
isdef('A')
clear A
isdef('A')

See Also

exists , whereis , type , typeof , clear ,


isempty

Scilab Function
Last update : 15/06/2004

isempty - check if a variable is an empty matrix or an empty list

Calling Sequence

t=isempty(x)

Parameters

  • x : vector or matrix or list
  • t : a boolean

Description

isempty(x) returns true if x is an empty matrix or an empty list.

Examples

a=1
isempty(a(2:$))
isempty(find(rand(1:10)==5))


isequal

Scilab Function
Last update : 12/01/2004

isequal - objects comparison

Calling Sequence

t=isequal(a,b)
t=isequal(a,b,..)

Parameters

  • a, b , ... : any variables
  • t : boolean

Description

isequal compares its arguments. If all of them are equals function returns %t and in the other case it returns %f .

Examples

a=[1 2]
isequal(a,[1 2])
isequal(a,1)

See Also

equal , less ,


isinf

Scilab Function
Last update : 16/06/2004

isinf - vérifie si des composantes "Inf" (infinies) sont présentes.

Calling Sequence

r=isinf(x)

Parameters

  • x : vecteur ou matrice complexe ou réelle. r : vecteur ou matrice de booléens.

Description

isinf(x) renvoie un vecteur ou une matrice de booléens contenant des composantes égales à %T (vrai) correspondant aux composantes "Inf" (infinies) de x et %F (faux) pour les autres.

Examples

isinf([1 0.01 -%inf %inf])

See Also

isnan ,


isnan

Scilab Function
Last update : 16/06/2004

isnan - vérifie si des composantes "NaN" (Not a Number) sont présentes.

Calling Sequence

r=isnan(x)

Parameters

  • x : vecteur ou matrice complexe ou réelle. r : vecteur ou matrice de booléens.

Description

isnan(x) renvoie un vecteur ou une matrice de booléens contenant des composantes égales à %T (vrai) correspondant aux composantes "NaN" (Not a Number) de x et %F (faux) pour les autres.

Examples

isnan([1 0.01 -%nan %inf-%inf])

See Also

isinf ,


isreal

Scilab Function
Last update : 16/06/2004

isreal - vérifie si une matrice a des éléments complexes

Calling Sequence

t=isreal(x)
t=isreal(x,eps)

Parameters

  • x : vecteur ou matrice réelle ou complexe.
  • eps : nombre réel positif.
  • t : un booléen.

Description

isreal(x) renvoie %T (vrai) si x est stockée comme une matrice réelle ou %F (faux) si x est stockée avec une partie imaginaire (même nulle).

isreal(x,eps) renvoie %T (vrai) si x est stockée comme une matrice réelle ou si les valeurs absolues des parties imaginaires des éléments de x sont plus petites que eps .

Examples

isreal([1 2])
isreal(1+0*%i)
isreal(1+0*%i,0)
isreal(1+%s)
isreal(sprand(3,3,0.1))


kron

Scilab Function
Last update : 16/06/2004

kron - produit de kronecker (.*.)

Calling Sequence

kron(x,y)
x.*.y

Description

Produit tensoriel de Kronecker de deux matrices x et y . Identique à x.*.y . x et y peuvent être des matrices creuses.

Examples

A=[1,2;3,4];
kron(A,A)
A.*.A
sparse(A).*.sparse(A)
A(1,1)=%i;
kron(A,A)


ldivf

Scilab Function
Last update : 16/06/2004

ldivf - division à gauche symbolique

Calling Sequence

ldivf('d','c')

Description

Renvoie la chaîne de caractères 'c\d' Des simplifications triviales du type '1\c' = 'c' sont effectuées.

Examples

ldivf('1','1')
ldivf('a','0')
ldivf('a','x')
ldivf('2','4')

See Also

rdivf , addf , mulf , evstr ,


legendre

Scilab Function
Last update : 17/12/2003

legendre - associated Legendre functions

Calling Sequence

y = legendre(n,m,x [,normflag])

Parameters

  • n : non negative integer or vector of non negative integers regularly spaced with increment equal to 1
  • m : non negative integer or vector of non negative integers regularly spaced with increment equal to 1
  • x : real (row) vector (elements of x must be in the (-1,1) interval)
  • normflag : (optional) scalar string

Description

When n and m are scalars, legendre(n,m,x) evaluates the associated Legendre function Pnm(x) at all the elements of x . The definition used is :

                              m
               m        m/2  d
  Pnm(x) = (-1)  (1-x^2)    --- Pn(x)
                              m
                            dx

where Pn is the Legendre polynomial of degree n . So legendre(n,0,x) evaluates the Legendre polynomial Pn(x) at all the elements of x .

When the normflag is equal to "norm" you get a normalized version (without the (-1)^m factor), precisely :

                     _____________                m
                    /(2n+1)(n-m)!          m/2   d
  Pnm(x,"norm") =  /--------------  (1-x^2)     --- Pn(x)
                 \/     2  (n+m)!                 m
                                                dx

which is useful to compute spherical harmonic functions (see Example 3):

For efficiently, one of the two first arguments may be a vector, for instance legendre(n1:n2,0,x) evaluates all the Legendre polynomials of degree n1, n1+1, ..., n2 at the elements of x and legendre(n,m1:m2,x) evaluates all the Legendre associated functions Pnm for m=m1, m1+1, ..., m2 at x .

Output format

In any case, the format of y is :

        max(length(n),length(m)) x length(x)

and :

       y(i,j) = P(n(i),m;x(j))   if n is a vector
       y(i,j) = P(n,m(i);x(j))   if m is a vector
       y(1,j) = P(n,m;x(j))      if both n and m are scalars

so that x is preferably a row vector but any mx x nx matrix is excepted and considered as an 1 x (mx * nx) matrix, reshaped following the column order.

Examples

// example 1 : plot of the 6 first Legendre polynomials on (-1,1)
l = nearfloat("pred",1);
x = linspace(-l,l,200)';
y = legendre(0:5, 0,  x);
xbasc()
plot2d(x,y', leg="p0@p1@p2@p3@p4@p5@p6")
xtitle("the 6 th first Legendre polynomials")

// example 2 : plot of the associated Legendre functions of degree 5
l = nearfloat("pred",1);
x = linspace(-l,l,200)';
y = legendre(5, 0:5, x, "norm");
xbasc()
plot2d(x,y', leg="p5,0@p5,1@p5,2@p5,3@p5,4@p5,5")
xtitle("the (normalised) associated Legendre functions of degree 5")

// example 3 : define then plot a spherical harmonic
// 3-1 : define the function Ylm
function [y] = Y(l,m,theta,phi)
   // theta may be a scalar or a row vector
   // phi may be a scalar or a column vector
   if m >= 0 then
      y = (-1)^m/(sqrt(2*%pi))*exp(%i*m*phi)*legendre(l, m, cos(theta), "norm")
   else
      y = 1/(sqrt(2*%pi))*exp(%i*m*phi)*legendre(l, -m, cos(theta), "norm")
   end
endfunction

// 3.2 : define another useful function
function [x,y,z] = sph2cart(theta,phi,r)
   // theta row vector      1 x nt
   // phi   column vector  np x 1
   // r     scalar or np x nt matrix (r(i,j) the length at phi(i) theta(j))
   x = r.*(cos(phi)*sin(theta));
   y = r.*(sin(phi)*sin(theta));
   z = r.*(ones(phi)*cos(theta));
endfunction

// 3-3 plot Y31(theta,phi)
l = 3; m = 1;
theta = linspace(0.1,%pi-0.1,60);
phi = linspace(0,2*%pi,120)';
f = Y(l,m,theta,phi);
[x1,y1,z1] = sph2cart(theta,phi,abs(f));       [xf1,yf1,zf1] = nf3d(x1,y1,z1);
[x2,y2,z2] = sph2cart(theta,phi,abs(real(f))); [xf2,yf2,zf2] = nf3d(x2,y2,z2);
[x3,y3,z3] = sph2cart(theta,phi,abs(imag(f))); [xf3,yf3,zf3] = nf3d(x3,y3,z3);

xbasc()
subplot(1,3,1)
plot3d(xf1,yf1,zf1,flag=[2 4 4]); xtitle("|Y31(theta,phi)|")
subplot(1,3,2)
plot3d(xf2,yf2,zf2,flag=[2 4 4]); xtitle("|Real(Y31(theta,phi))|")
subplot(1,3,3)
plot3d(xf3,yf3,zf3,flag=[2 4 4]); xtitle("|Imag(Y31(theta,phi))|")

Authors

Smith, John M. (code dxlegf.f from Slatec)
B. Pincon (scilab interface)


lex_sort

Scilab Function
Last update : 16/06/2004

lex_sort - tri des lignes d'une matrice suivant l'ordre lexicographique.

Calling Sequence

[N, [k]]=lex_sort(M [,sel] [,'unique'])

Parameters

  • M,N : matrices réelles
  • k : vecteur colonne d'entiers

Description

N=lex_sort(M) trie les lignes de la matrice M dans l'ordre croissant. Si nécessaire l'argument de sortie k permet de retrouver l'ordre du tri : [N,k]=lex_sort(M) renvoie k tel que N est égal à M(k,:) .

N=lex_sort(M,sel [,'unique']) produit le même résultat que la suite d'instructions suivante :

[N,k]=lex_sort(M(:,sel) [,'unique']);
N=M(k,:)

La chaîne de caractères 'unique' doit être utilisée si on ne veut retenir que les lignes uniques dans le résultat. Noter que lex_sort(M,sel,'unique') ne retient que les lignes de M telles que M(:,sel) est unique.

Examples

M=round(2*rand(20,3));

lex_sort(M)
lex_sort(M,'unique')
[N,k]=lex_sort(M,[1 3],'unique')

See Also

sort ,


linear_interpn

Scilab Function
Last update : 06/07/2004

linear_interpn - n dimensional linear interpolation

Calling Sequence

vp = linear_interpn(xp1,xp2,..,xpn, x1, ..., xn, v [,out_mode])

Parameters

  • xp1, xp2, .., xpn : real vectors (or matrices) of same size
  • x1 ,x2, ..., xn : strictly increasing row vectors (with at least 2 components) defining the n dimensional interpolation grid
  • v : vector (case n=1), matrix (case n=2) or hypermatrix (case n > 2) with the values of the underlying interpolated function at the grid points.
  • out_mode : (optionnal) string defining the evaluation outside the grid (extrapolation)
  • vp : vector or matrix of same size than xp1, ..., xpn

Description

Given a n dimensional grid defined by the n vectors x1 ,x2, ..., xn and the values v of a function (says f) at the grid points :

      v(i1,i2,...,in) = f(x1(i1),x2(i2), ..., xn(in))

this function computes the linear interpolant of f from the grid (called s in the following) at the points which coordinates are defined by the vectors (or matrices) xp1, xp2, ..., xpn :

   vp(i) = s(xp1(i),xp2(i), ..., xpn(i))

   or vp(i,j) = s(xp1(i,j),xp2(i,j), ..., xpn(i,j)) in case the xpk are matrices

The out_mode parameter set the evaluation rule for extrapolation: if we note Pi=(xp1(i),xp2(i),...,xpn(i)) then out_mode defines the evaluation rule when:

   P(i) not in  [x1(1) x1($)] x [x2(1) x2($)] x ... x [xn(1) xn($)]

The different choices are:

  • "by_zero" : an extrapolation by zero is done
  • "by_nan" : extrapolation by Nan
  • "C0" : the extrapolation is defined as follows:
         s(P) = s(proj(P)) where proj(P) is nearest point from P
                       located on the grid boundary.
  • "natural" : the extrapolation is done by using the nearest n-linear patch from the point.
  • "periodic" : s is extended by periodicity.

    • Examples

    // example 1 : 1d linear interpolation
x = linspace(0,2*%pi,11);
y = sin(x);
xx = linspace(-2*%pi,4*%pi,400)';
yy = linear_interpn(xx, x, y, "periodic");
xbasc()
plot2d(xx,yy,style=2)
plot2d(x,y,style=-9, strf="000")
xtitle("linear interpolation of sin(x) with 11 interpolation points")

// example 2 : bilinear interpolation
n = 8;
x = linspace(0,2*%pi,n); y = x;
z = 2*sin(x')*sin(y);
xx = linspace(0,2*%pi, 40);
[xp,yp] = ndgrid(xx,xx);
zp = linear_interpn(xp,yp, x, y, z);
xbasc()
plot3d(xx, xx, zp, flag=[2 6 4])
[xg,yg] = ndgrid(x,x);
param3d1(xg,yg, list(z,-9*ones(1,n)), flag=[0 0])
xtitle("Bilinear interpolation of 2sin(x)sin(y)")
legends("interpolation points",-9,1)
xselect()

// example 3 : bilinear interpolation and experimentation
//             with all the outmode features
nx = 20; ny = 30;
x = linspace(0,1,nx);
y = linspace(0,2, ny);
[X,Y] = ndgrid(x,y);
z = 0.4*cos(2*%pi*X).*cos(%pi*Y);
nxp = 60 ; nyp = 120;
xp = linspace(-0.5,1.5, nxp);
yp = linspace(-0.5,2.5, nyp);
[XP,YP] = ndgrid(xp,yp);
zp1 = linear_interpn(XP, YP, x, y, z, "natural");
zp2 = linear_interpn(XP, YP, x, y, z, "periodic");
zp3 = linear_interpn(XP, YP, x, y, z, "C0");
zp4 = linear_interpn(XP, YP, x, y, z, "by_zero");
zp5 = linear_interpn(XP, YP, x, y, z, "by_nan");
xbasc()
subplot(2,3,1)
   plot3d(x, y, z, leg="x@y@z", flag = [2 4 4])
   xtitle("initial function 0.4 cos(2 pi x) cos(pi y)")
subplot(2,3,2)
   plot3d(xp, yp, zp1, leg="x@y@z", flag = [2 4 4])
   xtitle("Natural")
subplot(2,3,3)
   plot3d(xp, yp, zp2, leg="x@y@z", flag = [2 4 4])
   xtitle("Periodic")
subplot(2,3,4)
   plot3d(xp, yp, zp3, leg="x@y@z", flag = [2 4 4])
   xtitle("C0")
subplot(2,3,5)
   plot3d(xp, yp, zp4, leg="x@y@z", flag = [2 4 4])
   xtitle("by_zero")
subplot(2,3,6)
   plot3d(xp, yp, zp5, leg="x@y@z", flag = [2 4 4])
   xtitle("by_nan")
xselect()

// example 4 : trilinear interpolation (see splin3d help
//             page which have the same example with
//             tricubic spline interpolation)
getf("SCI/demos/interp/interp_demo.sci")
func =  "v=(x-0.5).^2 + (y-0.5).^3 + (z-0.5).^2";
deff("v=f(x,y,z)",func);
n = 5;
x = linspace(0,1,n); y=x; z=x;
[X,Y,Z] = ndgrid(x,y,z);
V = f(X,Y,Z);
// compute (and display) the linear interpolant on some slices
m = 41;
dir = ["z="  "z="  "z="  "x="  "y="];
val = [ 0.1   0.5   0.9   0.5   0.5];
ebox = [0 1 0 1 0 1];

XF=[]; YF=[]; ZF=[]; VF=[];
for i = 1:length(val)
   [Xm,Xp,Ym,Yp,Zm,Zp] = slice_parallelepiped(dir(i), val(i), ebox, m, m, m);
   Vm = linear_interpn(Xm,Ym,Zm, x, y, z, V);
   [xf,yf,zf,vf] = nf3dq(Xm,Ym,Zm,Vm,1);
   XF = [XF xf]; YF = [YF yf]; ZF = [ZF zf]; VF = [VF vf];
   Vp =  linear_interpn(Xp,Yp,Zp, x, y, z, V);
   [xf,yf,zf,vf] = nf3dq(Xp,Yp,Zp,Vp,1);
   XF = [XF xf]; YF = [YF yf]; ZF = [ZF zf]; VF = [VF vf];
end
nb_col = 128;
vmin = min(VF); vmax = max(VF);
color = dsearch(VF,linspace(vmin,vmax,nb_col+1));
xset("colormap",jetcolormap(nb_col));
xbasc()
xset("hidden3d",xget("background"))
colorbar(vmin,vmax)
plot3d(XF, YF, list(ZF,color), flag=[-1 6 4])
xtitle("tri-linear interpolation of "+func)
xselect()

    See Also

    interpln , splin , splin2d , splin3d ,

    Author

    B. Pincon


linspace

Scilab Function
Last update : 19/04/2006

linspace - vecteur de valeurs équidistantes

Calling Sequence

[v]=linspace(x1,x2 [,n])

Parameters

  • x1,x2 : scalaire réel ou complexe
  • n : entier (nombre de valeurs, 100 par défaut)
  • v : vecteur ligne réel ou complexe

Description

linspace(x1, x2) renvoie un vecteur ligne de n valeurs régulièrement espacées entre x1 et x2 . Si x1 ou x2 sont complexes alors linspace(x1,x2) renvoie un vecteur ligne de n valeurs complexes dont les partie réels (resp. imaginaires) sont regulierement espacées entre les partie réels (resp. imaginaires) de x1 et x2

Examples

linspace(1,2,10)

See Also

logspace ,


log10

Scilab Function
Last update : 16/06/2004

log10 - logarithme en base 10

Calling Sequence

y=log10(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)

Description

log10(x) calcule le logarithme en base 10 élément par élément : y(i,j)=log10(x(i,j)) .

Examples

10.^(log10([1,%i,-1,-%i]))

See Also

log , log2 , hat , exp , frexp , logm , ieee ,


log1p

Scilab Function
Last update : 12/01/2004

log1p - computes with accuracy the natural logarithm of its argument added by one

Calling Sequence

y=log1p(x)

Parameters

  • x : real scalar, vector or matrix
  • y : real scalar, vector or matrix

Description

logp1(x) is the "element-wise" log(1+x) function. y(i,j)=log(1 + x(i,j)) . This function, defined for x > -1, must be used if we want to compute log(1+x) with accuracy for |x| << 1.

Examples

format("e",24)
log(1.001)
log1p(0.001)
log(1 + 1.e-7)
log1p(1.e-7)
log(1 + 1.e-20)
log1p(1.e-20)
format("v") //reset default format

See Also

log ,

Author

B.P.;


log2

Scilab Function
Last update : 16/06/2004

log2 - logarithme en base 2

Calling Sequence

y=log2(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)

Description

log2(x) calcule le logarithme en base 2 élément par élément : y(i,j)=log2(x(i,j)) .

Examples

2.^(log2([1,%i,-1,-%i]))

See Also

log , log10 , hat , exp , frexp , logm , ieee ,


logm

Scilab Function
Last update : 16/06/2004

logm - logarithme matriciel d'une matrice carrée

Calling Sequence

y=logm(x)

Parameters

  • x : matrice carrée

Description

logm(x) est le logarithme matriciel de x . Le résultat est complexe si x n'est pas positive ou définie positive. Si x est une matrice symétrique, le calcul est fait en utilisant la forme de Schur. Sinon, x est supposée diagonalisable. On a expm(logm(x))=x

Examples

A=[1,2;3,4];
logm(A)
expm(logm(A))
A1=A*A';
logm(A1)
expm(logm(A1))
A1(1,1)=%i;
expm(logm(A1))

See Also

expm , log ,


logspace

Scilab Function
Last update : 16/06/2004

logspace - vecteur de valeurs logarithmiquement équidistantes.

Calling Sequence

logspace(d1,d2, [n])

Parameters

  • d1,d2 : scalaire réel ou complexe (une signification particulière est donnée à la valeur %pi )
  • n : entier (nombre de valeurs, 50 par défaut)
  • v : vecteur ligne réel ou complexe

Description

Renvoie un vecteur ligne n de valeurs logarithmiquement équidistantes entre 10^d1 et 10^d2 . Si d2=%pi alors les valeurs sont comprises entre 10^d1 et pi .

Examples

logspace(1,2,10)

See Also

linspace ,


log

Scilab Function
Last update : 16/06/2004

log - logarithme naturel

Calling Sequence

y=log(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)

Description

log(x) calcule le logarithme élément par élément : y(i,j)=log(x(i,j)) . Pour le logarithme matriciel voir la fonction logm .

Examples

exp(log([1,%i,-1,-%i]))

See Also

log2 , log10 , hat , exp , frexp , logm , ieee ,


lsq_splin

Scilab Function
Last update : 24/03/2004

lsq_splin - weighted least squares cubic spline fitting

Calling Sequence

[y, d] = lsq_splin(xd, yd [, wd], x)

Parameters

  • xd, yd : vectors of the same size, datas to be fitted by a cubic spline
  • wd : (optionnal) a vector of same format than xd and yd , weights of the least square fit.
  • x : a strictly increasing (row or column) vector, breakpoints of the cubic spline
  • y, d : vectors of same format than x , the triplet (x,y,d) defines the approximated cubic spline.

Description

This function computes an approximated cubic spline s for the datas xd, yd, wd (in the following m is supposed to be the length of these vectors) and from a choice of the spline breakpoints x (for instance if you want n breakpoints uniformly choosen you may use x=linspace(min(xd),max(xd),n))). If S is the space of all cubic splines functions with breakpoints x1 < x2 < ... < xn then the resulting spline s is such that:

     _m_                               _m_
     \                           2     \                           2
     /   wd(k) (s(xd(k)) - yd(k))  <=  /   wd(k) (f(xd(k)) - yd(k))
     ---                               ---
     k=1                               k=1

for all f in S, i.e. realizes the minimum of the sum of the squared errors over all functions of S.

The spline s is completly defined by the triplet (x,y,d) ( y and d are the vectors of the spline ordinates and first derivatives at the xi 's : yi=s(xi) and di=s'(xi)) and its evaluation at some points must be done by the interp function.

Remarks

When wd is not given, all the points have the same weight 1.

A point (xd(k),yd(k)) is considered in the fit if xd(k) in [x1,xn] and wd(k) > 0. In particular you can put a null (or even negative) weight to all data points you want to ignore in the fitting. When the total number of points taken into account in the fit procedure is (strictly) less than 4 an error is issued.

The vector xd do not need to be in increasing order.

Depending on the number and on the positions of the xd(k) 's and on the choice of the x(i) 's there may be several solutions but only one is selected. When this occurs a warning message is displayed in the Scilab command window. This function is intended to be used when m is much larger than n and in this case no such problem may occured.

Examples

// this is an artifical example where the datas xd and yd
// are build from a perturbed sin function
a = 0; b = 2*%pi;
sigma = 0.1;  // standard deviation of the gaussian noise
m = 200;       // number of experimental points
xd = linspace(a,b,m)';
yd = sin(xd) + grand(xd,"nor",0,sigma);

n = 6; // number of breakpoints
x = linspace(a,b,n)';

// compute the spline
[y, d] = lsq_splin(xd, yd, x);  // use equal weights

// plotting
ye = sin(xd);
ys = interp(xd, x, y, d);
xbasc()
plot2d(xd,[ye yd ys],style=[2 -2 3], ...
       leg="exact function@experimental measures (gaussian perturbation)@fitted spline")
xtitle("a least square spline")
xselect()

See Also

interp , splin ,

Authors

C. De Boor, A.H. Morris (code from the NSWC fortran lib)
B. Pincon (scilab interface and slight modifications)


lstsize

Fonction Scilab
Last update : 16/06/2004

lstsize - nombre d'éléments des objets list, tlist et mlist

Calling Sequence

n=lstsize(x)

Parameters

  • l : un object de type list, tlist ou mlist
  • n : un entier, le nombre d'éléments de la liste

Description

lstsize(x) retourne le nombre d'élément d'un objet de type list, tlist ou mlist. Cette fonction est plus efficace que la fonction size et à la même signification pour tous les objets de type list tandis que size est surcharge pour les objets de type mlist .

Examples

lstsize(list(1,'aqsdf'))
x=ssrand(3,2,4);
[ny,nu]=size(x)
lstsize(x)

See Also

length , size , list , tlist , mlist ,


maxi

Scilab Function
Last update : 14/12/2005

maxi - maximum

Calling Sequence

[m [,k]]=maxi(A)
[m [,k]]=maxi(A,'c')
[m [,k]]=maxi(A,'r')
[m [,k]]=maxi(A,'m')
[m [,k]]=maxi(A1,A2,...,An)
[m [,k]]=maxi(list(A1,A2,...,An))

Parameters

  • A : vecteur ou matrice réelle.
  • A1,...,An : un ensemble de vecteurs ou de matrices toutes de même taille.

Description

Pour A , un vecteur ou une matrice réelle, maxi(A) est son plus grand élément. [m,k]=maxi(A) donne la position du maximum dans A . Le deuxième argument peut être la chaîne de caractère 'r' ou 'c' : 'r' permet d'obtenir un vecteur ligne m tel que m(j) contient le maximum de la j -ième colonne de A ( A(:,j) ), k(j) donne le numéro de la ligne qui contient le maximum pour la colonne j . 'c' est utilisé pour l'opération duale sur les lignes de A . 'm' est utilisé pour la compatibilité avec Mtalab.

m=maxi(A1,A2,...,An) , où tous les Aj sont des matrices de même taille, renvoie un vecteur ou une matrice m de taille size(m)=size(A1) telle que m(i)= maxi( Aj(i)), j=1,...,n . [m,k]=maxi(A1,A2,...,An) donne de plus le vecteur ou la matrice k . Pour un i donné, k(i) est le numéro de la première Aj(i) réalisant le maximum.

[m,k]=maxi(list(A1,...,An)) est une syntaxe équivalente de [m,k]=maxi(A1,A2,...,An)

Examples

    [m,n]=maxi([1,3,1])
    [m,n]=maxi([3,1,1],[1,3,1],[1,1,3])
    [m,n]=maxi([3,-2,1],1)
    [m,n]=maxi(list([3,1,1],[1,3,1],[1,1,3]))
    [m,n]=maxi(list(1,3,1))

See Also

sort , find , max ,


max

Scilab Function
Last update : 14/12/2005

max - maximum

Calling Sequence

[m [,k]]=max(A)
[m [,k]]=max(A,'c')
[m [,k]]=max(A,'r')
[m [,k]]=max(A,'m')
[m [,k]]=max(A1,A2,...,An)
[m [,k]]=max(list(A1,A2,...,An))

Parameters

  • A : vecteur ou matrice réelle.
  • A1,...,An : un ensemble de vecteurs ou de matrices toutes de même taille.

Description

Pour A , un vecteur ou une matrice réelle, max(A) est son plus grand élément. [m,k]=max(A) donne la position du maximum dans A . Le deuxième argument peut être la chaîne de caractère 'r' ou 'c' : 'r' permet d'obtenir un vecteur ligne m tel que m(j) contient le maximum de la j -ième colonne de A ( A(:,j) ), k(j) donne le numéro de la ligne qui contient le maximum pour la colonne j . 'c' est utilisé pour l'opération duale sur les lignes de A . 'm' est utilisé pour la compatibilité avec Mtalab.

m=max(A1,A2,...,An) , où tous les Aj sont des matrices de même taille, renvoie un vecteur ou une matrice m de taille size(m)=size(A1) telle que m(i)= max( Aj(i)), j=1,...,n . [m,k]=max(A1,A2,...,An) donne de plus le vecteur ou la matrice k . Pour un i donné, k(i) est le numéro de la première Aj(i) réalisant le maximum.

[m,k]=max(list(A1,...,An)) est une syntaxe équivalente de [m,k]=max(A1,A2,...,An)

Examples

    [m,n]=max([1,3,1])
    [m,n]=max([3,1,1],[1,3,1],[1,1,3])
    [m,n]=max([3,-2,1],1)
    [m,n]=max(list([3,1,1],[1,3,1],[1,1,3]))
    [m,n]=max(list(1,3,1))

See Also

sort , find , max ,


meshgrid

Scilab Function
Last update : 28/10/2005

meshgrid - construit des matrices ou des tableaux 3-D

Calling Sequence

[X, Y] = meshgrid(x)
[X, Y] = meshgrid(x,y)
[X, Y, Z] = meshgrid(x,y,z)

Parameters

  • x, y, z : des vecteurs
  • X, Y, Z : des matrices dans le cas de 2 arguments d'entrées, sinon des tableaux des tableaux 3-D dans le cas de 3 arguments d'entrées

Description

...

Examples

//

See Also

ndgrid ,

Author

Farid Belahcene


mini

Scilab Function
Last update : 14/12/2005

mini - minimum

Calling Sequence

[m [,k]]=mini(A)
[m [,k]]=mini(A,'c')
[m [,k]]=mini(A,'r')
[m [,k]]=mini(A,'m')
[m [,k]]=mini(A1,A2,...,An)
[m [,k]]=mini(list(A1,A2,...,An))

Parameters

  • A : vecteur ou matrice réelle.
  • A1,...,An : un ensemble de vecteurs ou de matrices toutes de même taille.

Description

Pour A , un vecteur ou une matrice réelle, mini(A) est son plus grand élément. [m,k]=mini(A) donne la position du minimum dans A . Le deuxième argument peut être la chaîne de caractère 'r' ou 'c' : 'r' permet d'obtenir un vecteur ligne m tel que m(j) contient le minimum de la j -ième colonne de A ( A(:,j) ), k(j) donne le numéro de la ligne qui contient le minimum pour la colonne j . 'c' est utilisé pour l'opération duale sur les lignes de A . 'm' est utilisé pour la compatibilité avec Matlab.

m=mini(A1,A2,...,An) , où tous les Aj sont des matrices de même taille, renvoie un vecteur ou une matrice m de taille size(m)=size(A1) telle que m(i)= mini( Aj(i)), j=1,...,n . [m,k]=mini(A1,A2,...,An) donne de plus le vecteur ou la matrice k . Pour un i donné, k(i) est le numéro de la première Aj(i) réalisant le minimum.

[m,k]=mini(list(A1,...,An)) est une syntaxe équivalente de [m,k]=mini(A1,A2,...,An)

Examples

    [m,n]=mini([1,3,1])
    [m,n]=mini([3,1,1],[1,3,1],[1,1,3])
    [m,n]=mini([3,-2,1],1)
    [m,n]=mini(list([3,1,1],[1,3,1],[1,1,3]))
    [m,n]=mini(list(1,3,1))

See Also

sort , find , max ,


minus (-)

Scilab Function
Last update : 16/06/2004

minus (-) - opérateur de soustraction, changement de signe

Calling Sequence

X-Y
-Y

Parameters

  • X : scalaire, vecteur ou matrice de nombres, polynômes ou fractions rationnelles, ou liste de type syslin .
  • Y : scalaire, vecteur ou matrice de nombres, polynômes ou fractions rationnelles, ou liste de type syslin .

Description

Soustraction

Pour les opérandes numériques la signification est celle de la soustraction habituelle. Si l'un des opérandes est une matrice (ou un vecteur) et l'autre un scalaire l'opération est effectuée pour chaque élément de la matrice. Si Y==[] le résultat est X . Si X==[] le résultat est -Y .

La soustraction peut être aussi définie pour d'autres types de données via la surcharge d'opérateurs (voir overloading).

Examples

[1,2]-1
[]-2

%s-2
1/%s-2
"cat"+"enate"

See Also

overloading , addf , mtlb_mode ,


min

Scilab Function
Last update : 14/12/2005

min - minimum

Calling Sequence

[m [,k]]=min(A)
[m [,k]]=min(A,'c')
[m [,k]]=min(A,'r')
[m [,k]]=min(A,'m')
[m [,k]]=min(A1,A2,...,An)
[m [,k]]=min(list(A1,A2,...,An))

Parameters

  • A : vecteur ou matrice réelle.
  • A1,...,An : un ensemble de vecteurs ou de matrices toutes de même taille.

Description

Pour A , un vecteur ou une matrice réelle, min(A) est son plus grand élément. [m,k]=min(A) donne la position du minimum dans A . Le deuxième argument peut être la chaîne de caractère 'r' ou 'c' : 'r' permet d'obtenir un vecteur ligne m tel que m(j) contient le minimum de la j -ième colonne de A ( A(:,j) ), k(j) donne le numéro de la ligne qui contient le minimum pour la colonne j . 'c' est utilisé pour l'opération duale sur les lignes de A . 'm' est utilisé pour la compatibilité avec Matlab.

m=min(A1,A2,...,An) , où tous les Aj sont des matrices de même taille, renvoie un vecteur ou une matrice m de taille size(m)=size(A1) telle que m(i)= min( Aj(i)), j=1,...,n . [m,k]=min(A1,A2,...,An) donne de plus le vecteur ou la matrice k . Pour un i donné, k(i) est le numéro de la première Aj(i) réalisant le minimum.

[m,k]=min(list(A1,...,An)) est une syntaxe équivalente de [m,k]=min(A1,A2,...,An)

Examples

    [m,n]=min([1,3,1])
    [m,n]=min([3,1,1],[1,3,1],[1,1,3])
    [m,n]=min([3,-2,1],1)
    [m,n]=min(list([3,1,1],[1,3,1],[1,1,3]))
    [m,n]=min(list(1,3,1))

See Also

sort , find , max ,


modulopmodulo

Scilab Function
Last update : 16/06/2004

modulo - reste arithmétique symétrique modulo m

pmodulo - reste arithmétique positif modulo m

Calling Sequence

i=modulo(n,m)
i=pmodulo(n,m)

Parameters

  • n : entier
  • m : entier

Description

modulo calcule i= n (modulo m) c'est à dire le reste de n divisé par m ( n et m sont entiers).

i = n - m .* int (n ./ m). Ici la réponse peut être négative si n et/ou m sont négatifs.

pmodulo calcule i = n - m .* floor (n ./ m) , la réponse est positive ou nulle.

Examples

n=[1,2,10,15];m=[2,2,3,5];
modulo(n,m)

modulo(-3,9)
pmodulo(-3,9)


mps2linpro

Scilab Function
Last update : 12/01/2004

mps2linpro - convert lp problem given in MPS format to linpro format

Calling Sequence

lp = mps2linpro(mps)
[p,C,b,ci,cs,mi] = mps2linpro(mps)

Parameters

  • mps : either a character string, path of the MPS file, or an mps data structure returned by readmps
  • lp : a linpro data tlist with following fields:
    • p : real (column) vector (dimension n )
    • C : real matrix (dimension (mi + md) x n ) (If no constraints are given, you can set C = [] )
    • b : RHS vector (dimension 1 x (mi + md) )
    • ci : (column) vector of lower-bounds (dimension n ). If there are no lower bound constraints, put ci = [] . If some components of x are bounded from below, set the other (unconstrained) values of ci to a very large negative number (e.g. ci(j) = -(% eps)^(-1) .
    • cs : (column) vector of upper-bounds. (Same remarks as above).
    • mi : number of equality constraints (i.e. C(1:mi,:)*x = b(1:mi) )

Description

mps2linpro forms Linear programing data compatible with linpro out of MPS data format.

See Also

linpro , readmps ,


mtlb_sparse

Scilab Function
Last update : 12/01/2004

mtlb_sparse - convert sparse matrix

Calling Sequence

Y=mtlb_sparse(X)

Parameters

  • X : sparse matrix
  • Y : sparse matrix in Matlab format

Description

Y=mtlb_sparse(X) is used to convert X , a Scilab sparse matrix, to Matlab format. Y is the a variable with type 7, i.e. type(Y) is equal to 7. This function should be used in mexfiles (a Matlab mexfile containing sparse matrices can be used only if the Scilab sparse matrices are converted to that format). The functions full and spget work with this format.

Other operations and functions using this format can be overloaded with Scilab functions using the prefix "%msp". For instance the function %msp_p(x) (see SCIDIR/macros/percent directory) is used to display such "type 7" objects.

Examples

X=sparse(rand(2,2)); Y=mtlb_sparse(X);
Y, full(Y), [ij,v,mn]=spget(Y)

See Also

full , spget ,


mulf

Scilab Function
Last update : 16/06/2004

mulf - multiplication symbolique

Calling Sequence

mulf('d','c')

Description

Renvoie la chaîne de caractères 'c*d' . Des simplifications triviales du type '1*c' = 'c' sont effectuées.

Examples

mulf('1','a')
mulf('0','a')
'a'+'b'   // attention ...

See Also

rdivf , addf , subf ,


ndgrid

Scilab Function
Last update : 24/03/2004

ndgrid - arrays for multidimensional function evaluation on grid

Calling Sequence

[X, Y] = ndgrid(x,y)
[X, Y, Z] = ndgrid(x,y,z)
[X, Y, Z, T] = ndgrid(x,y,z,t)
[X1, X2, ..., Xm] = ndgrid(x1,x2,...,xm)

Parameters

  • x, y, z, ... : vectors
  • X, Y, Z, ... : matrices in case of 2 input arguments, or else hypermatrices

Description

This is an utility routine useful to create arrays for function evaluation on 2, 3, ..., n dimensional grids. For instance in 2d, a grid is defined by two vectors, x and y of length nx and ny, and you want to evaluate a function (says f) on all the grid points, that is on all the points of coordinates (x(i),y(j)) with i=1,..,nx and j=1,..,ny. In this case, this function can compute the two matrices X,Y of size nx x ny such that :

      X(i,j) = x(i)   for all i in [1,nx]
      Y(i,j) = y(j)       and j in [1,ny]

and the evaluation may be done with Z=f(X,Y) (at the condition that you have coded f for evaluation on vector arguments, which is done (in general) by using the element-wise operators .* , ./ and .^ in place of * , / and ^ ).

In the 3d case, considering 3 vectors x,y,z of length nx, ny and nz, X,Y,Z are 3 hypermatrices of size nx x ny x nz such that :

      X(i,j,k) = x(i)
      Y(i,j,k) = y(j)   for all (i,j,k) in [1,nx]x[1,ny]x[1,nz]
      Z(i,j,k) = z(k)

In the general case of m input arguments x1, x2, .., xm , then the m output arguments X1, X2, .., Xm are hypermatrices of size nx1 x nx2 x ... x nxm and :

    Xj(i1,i2,...,ij,...,im) = xj(ij)
    for all (i1,i2,...,im) in [1,nx1]x[1,nx2]x...x[1,nxm]

Examples

// create a simple 2d grid
nx = 40; ny = 40;
x = linspace(-1,1,nx);
y = linspace(-1,1,ny);
[X,Y] = ndgrid(x,y);
// compute a function on the grid and plot it
//deff("z=f(x,y)","z=128*x.^2 .*(1-x).^2 .*y.^2 .*(1-y).^2");
deff("z=f(x,y)","z=x.^2 + y.^3")
Z = f(X,Y);
xbasc()
plot3d(x,y,Z, flag=[2 6 4]); xselect()

// create a simple 3d grid
nx = 10; ny = 6; nz = 4;
x = linspace(0,2,nx);
y = linspace(0,1,ny);
z = linspace(0,0.5,nz);
[X,Y,Z] = ndgrid(x,y,z);
// try to display this 3d grid ...
XF=[]; YF=[]; ZF=[];
for k=1:nz
   [xf,yf,zf] = nf3d(X(:,:,k),Y(:,:,k),Z(:,:,k));
   XF = [XF xf]; YF = [YF yf]; ZF = [ZF zf];
end
for j=1:ny
   [xf,yf,zf] = nf3d(matrix(X(:,j,:),[nx,nz]),...
                     matrix(Y(:,j,:),[nx,nz]),...
                     matrix(Z(:,j,:),[nx,nz]));
   XF = [XF xf]; YF = [YF yf]; ZF = [ZF zf];
end
xbasc()
plot3d(XF,YF,ZF, flag=[0 6 3], leg="X@Y@Z")
xtitle("A 3d grid !"); xselect()

See Also

kron ,

Author

B. Pincon


ndims

Scilab Function
Last update : 12/01/2004

ndims - number of dimensions of an array

Parameters

  • A : an array
  • n : integer, the number of dimensions of the array

Description

n=ndims(A) return the number of dimension of the array A . n is greater than or equal to 2.

Examples

A=rand(2,3);
ndims(A)

A=rand(2,3,2);
size(A),ndims(A)

H=[1/%s,1/(%s+1)]
ndims(H)

See Also

size ,

Author

S. Steer


nearfloat

Scilab Function
Last update : 12/01/2004

nearfloat - get previous or next floating-point number

Calling Sequence

xnear = nearfloat(dir, x)

Parameters

  • dir : string ("succ" or "pred")
  • x : real scalar, vector or matrix
  • xnear : real scalar, vector or matrix

Description

This function computes, in the element wise meaning, the corresponding neighbours of the elements of x (in the underlying floating point set, see number_properties), the successors if dir = "succ" and the predecessors if dir = "pred"

Examples

format("e",22)
nearfloat("succ",1) - 1
1 - nearfloat("pred",1)
format("v") //reset default format

See Also

number_properties , frexp ,

Author

B.P.


nextpow2

Scilab Function
Last update : 12/01/2004

nextpow2 - next higher power of 2.

Calling Sequence

t=nextpow2(x)

Parameters

  • x : real vector or matrix
  • p : integer vector or matrix

Description

If x is a scalar, nextpow2(x) returns the first p such that 2^p >= abs(x) . if x is a vector or a matrix nextpow2(x) applies element-wise.

Examples

nextpow2(127)
nextpow2(128)
nextpow2(0:10)

See Also

frexp ,


nnz

Scilab Function
Last update : 16/06/2004

nnz - nombre de termes non nuls dans une matrice

Calling Sequence

n=nnz(X)

Parameters

  • X : matrice réelle ou complexe (pleine ou creuse)
  • n : entier, le nombre de termes non nuls

Description

nnz compte le nombre de termes non nuls dans une matrice pleine ou creuse.

Examples

sp=sparse([1,2;4,5;3,10],[1,2,3]);
nnz(sp)
a=[1 0 0 0 2];
nnz(a)

See Also

spget ,


norm

Scilab Function
Last update : 16/06/2004

norm - normes matricielles

Calling Sequence

[y]=norm(x [,flag])

Parameters

  • x : vecteur ou matrice (réelle ou complexe, pleine ou creuse)
  • flag : chaîne de caractères (type de la norme, 2 par défaut)

Description

Pour les matrices

norm(x): où norm(x,2) est la plus grande valeur singulière de x ( max(svd(x)) ).
norm(x,1) renvoie: la norme l_1 de x (la plus grande somme suivant les colonnes : maxi(sum(abs(x),'r')) ).
norm(x,'inf'),norm(x,%inf): la norme infinie de x (la plus grande somme suivant les lignes : maxi(sum(abs(x),'c')) ).
norm(x,'fro'): la norme de Frobenius de x c'est à dire sqrt(sum(diag(x'*x)))

Pour les vecteurs

norm(v,p): norme l_p ( sum(v(i)^p))^(1/p) .
norm(v): =norm(v,2) : norme euclidienne
norm(v,'inf'): max(abs(v(i))) .

Examples

A=[1,2,3];
norm(A,1)
norm(A,'inf')
A=[1,2;3,4]
max(svd(A))-norm(A)

A=sparse([1 0 0 33 -1])
norm(A)

See Also

h_norm , dhnorm , h2norm , abs ,


not (~)

Scilab Function
Last update : 16/06/2004

not (~) - négation logique

Calling Sequence

~A

Description

~A renvoie la négation élément par élément de la matrice booléenne A .

Examples

~[%t %t %f]

See Also

and , or , find ,


number_properties

Scilab Function
Last update : 12/01/2004

number_properties - determine floating-point parameters

Calling Sequence

pr = number_properties(prop)

Parameters

  • prop : string
  • pr : real or boolean scalar

Description

This function may be used to get the characteristic numbers/properties of the floating point set denoted here by F(b,p,emin,emax) (usually the 64 bits float numbers set prescribe by IEEE 754). Numbers of F are of the form :

     sign * m * b^e

e is the exponent and m the mantissa :

     m = d_1 b^(-1) + d_2 b^(-2) + .... + d_p b^(-p)

d_i the digits are in [0, b-1] and e in [emin, emax] , the number is said "normalised" if d_1 ~= 0 . The following may be gotten :

prop = "radix"-> pr is the radix b of the set F
prop = "digits"-> pr is the number of digits p
prop = "huge"-> pr is the max positive float of F
prop = "tiny"-> pr is the min positive normalised float of F
prop = "denorm"-> pr is a boolean : %t if denormalised numbers are used
prop = "tiniest"-> if denorm = %t, pr is the min positive denormalised number else pr = tiny
prop = "eps"-> pr is the epsilon machine ( generally ( b^(1-p))/2 ) which is the relative max error between a real x (such than |x| in [tiny, huge] ) and fl(x) , its floating point approximation in F .
prop = "minexp"-> pr is emin
prop = "maxexp"-> pr is emax

Remarks

This function uses the lapack routine dlamch to get the machine parameters (the names (radix, digit, huge, etc...) are those recommended by the LIA 1 standard and are different from the corresponding lapack's ones) ; CAUTION : sometimes you can see the following definition for the epsilon machine : eps = b^(1-p) but in this function we use the traditionnal one (see prop = "eps" before) and so eps = (b^(1-p))/2 if normal rounding occurs and eps = b^(1-p) if not.

Examples

b = number_properties("radix")
eps = number_properties("eps")

See Also

nearfloat , frexp ,

Author

Bruno Pincon


oldbesselioldbesseljoldbesselkoldbessely

Scilab Function
Last update : 27/02/2006

oldbesseli - Modified Bessel functions of the first kind (I sub alpha).

oldbesselj - Bessel functions of the first kind (J sub alpha).

oldbesselk - Modified Bessel functions of the second kind (K sub alpha).

oldbessely - Bessel functions of the second kind (Y sub alpha).

Calling Sequence

y = oldbesseli(alpha,x)
y = oldbesseli(alpha,x,ice)
y = oldbesselj(alpha,x)
y = oldbesselk(alpha,x)
y = oldbesselk(alpha,x,ice)
y = oldbessely(alpha,x)

Parameters

  • x : real vector with non negative entries
  • alpha : real vector with non negative entries regularly spaced with increment equal to one alpha=alpha0+(n1:n2)
  • ice : integer flag, with default value 1

Description

These functions are obsolete, use besseli , besselj , besselk , bessely instead. Note however that the semantics of these two sets of functions are different.

oldbesseli(alpha,x) computes modified Bessel functions of the first kind (I sub alpha), for real, non-negative order alpha and real non negative argument x . besseli(alpha,x,2) computes besseli(alpha,x).*exp(-x) .

oldbesselj(alpha,x) computes Bessel functions of the first kind (J sub alpha), for real, non-negative order alpha and real non negative argument x .

oldbesselk(alpha,x) computes modified Bessel functions of the second kind (K sub alpha), for real, non-negative order alpha and real non negative argument x . besselk(alpha,x,2) computes besselk(alpha,x).*exp(x) .

oldbessely(alpha,x) computes Bessel functions of the second kind (Y sub alpha), for real, non-negative order alpha and real non negative argument x .

alpha and x may be vectors. The output is m -by- n with m = size(x,'*') , n = size(alpha,'*') whose (i,j) entry is oldbessel?(alpha(j),x(i)) .

Remarks

Y_alpha and J_alpha Bessel functions are 2 independant solutions of the Bessel 's differential equation :

2 2 2 x y" + x y' + (x - alpha ) y = 0 , alpha >=
    0

K_alpha and I_alpha modified Bessel functions are 2 independant solutions of the modified Bessel 's differential equation :

2 2 2 x y" + x y' - (x + alpha ) y = 0 , alpha >=
    0

Examples

// example #1: display some I Bessel functions
x = linspace(0.01,10,5000)';
y = oldbesseli(0:4,x);
ys = oldbesseli(0:4,x,2);
xbasc()
subplot(2,1,1)
   plot2d(x,y, style=2:6, leg="I0@I1@I2@I3@I4", rect=[0,0,6,10])
   xtitle("Some modified Bessel functions of the first kind")
subplot(2,1,2)
   plot2d(x,ys, style=2:6, leg="I0s@I1s@I2s@I3s@I4s", rect=[0,0,6,1])
   xtitle("Some modified scaled Bessel functions of the first kind")

// example #2 : display some J Bessel functions
x = linspace(0,40,5000)';
y = besselj(0:4,x);
xbasc()
plot2d(x,y, style=2:6, leg="J0@J1@J2@J3@J4")
xtitle("Some Bessel functions of the first kind")

// example #3 : use the fact that J_(1/2)(x) = sqrt(2/(x pi)) sin(x)
//              to compare the algorithm of besselj(0.5,x) with
//              a more direct formula
x = linspace(0.1,40,5000)';
y1 = besselj(0.5, x);
y2 = sqrt(2 ./(%pi*x)).*sin(x);
er = abs((y1-y2)./y2);
ind = find(er > 0 & y2 ~= 0);
xbasc()
subplot(2,1,1)
   plot2d(x,y1,style=2)
   xtitle("besselj(0.5,x)")
subplot(2,1,2)
   plot2d(x(ind), er(ind), style=2, logflag="nl")
   xtitle("relative error between 2 formulae for besselj(0.5,x)")

// example #4: display some K Bessel functions
x = linspace(0.01,10,5000)';
y = besselk(0:4,x);
ys = besselk(0:4,x,1);
xbasc()
subplot(2,1,1)
   plot2d(x,y, style=0:4, leg="K0@K1@K2@K3@K4", rect=[0,0,6,10])
   xtitle("Some modified Bessel functions of the second kind")
subplot(2,1,2)
   plot2d(x,ys, style=0:4, leg="K0s@K1s@K2s@K3s@K4s", rect=[0,0,6,10])
   xtitle("Some modified scaled Bessel functions of the second kind")

// example #5: plot severals Y Bessel functions
x = linspace(0.1,40,5000)'; // Y Bessel functions are unbounded  for x -> 0+
y = bessely(0:4,x);
xbasc()
plot2d(x,y, style=0:4, leg="Y0@Y1@Y2@Y3@Y4", rect=[0,-1.5,40,0.6])
xtitle("Some Bessel functions of the second kind")

Author

W. J. Cody, L. Stoltz (code from Netlib (specfun))


ones

Scilab Function
Last update : 16/06/2004

ones - matrice remplie de 1

Calling Sequence

y=ones(m1,m2,...)
y=ones(x)
y=ones()

Parameters

  • x,y : matrices
  • m1, m2,.. : entiers

Description

Renvoie une matrice dont tous les termes valent 1.

ones(m1,m2) Renvoie une matrice de taille (m1,m2) remplie de 1.
ones(m1,m2,..,mn): renvoie une matrice (m1,m2,..,mn) remplie de 1.
ones(x) : renvoie une matrice remplie de 1 de même taille que x .
ones(x)est aussi valide si x est une liste de type syslin (système dynamique linéaire sous forme d'une fonction de transfert ou d'une représentation d'état).

Notez que ones(3) est équivalent à ones(a) avec a=3 et donc n'est PAS une matrice 3x3 !

ones() est équivalent à ones(1,1).

Examples

ones(3)
ones(3,3)
ones(2,3,2)

See Also

eye , zeros ,


or |

Scilab Function
Last update : 16/06/2004

or | - disjonction logique

Calling Sequence

or(A), or(A,'*')
or(A,'r'), or(A,1)
or(A,'c'), or(A,2)
A|B

Description

or(A) donne la disjonction (ou) logique des éléments de la matrice booléenne A . or(A) est vrai ( %t ) si au moins un terme de A est %t .

y=or(A,'r') (ou y=or(A,1) ) est la disjonction suivant l'indice de ligne. Chaque élément du vecteur ligne y contient la disjonction de chaque colonne de x ( y(j)= or(A(i,j),i=1,m) ).

y=or(A,'c') (ou y=or(A,2) ) est la disjonction suivant l'indice de colonne. Chaque élément du vecteur colonne y contient la disjonction de chaque ligne de x ( y(i)= or(A(i,j),j=1,n) )).

A|B renvoie la disjonction logique élément par élément des matrices booléennes A et B . A et B doivent être des matrices de mêmes dimensions ou l'une d'elles doit être un simple booléen.

Examples

or([%t %t %f])
[%t %t %f]|[%f %t %t]
[%t %t %f]|%f

See Also

and , not , find ,


pen2ea

Scilab Function
Last update : 16/06/2004

pen2ea - Conversion faisceau vers deux matrices E,A

Calling Sequence

[E,A]=pen2ea(Fs)

Parameters

  • Fs : faisceau de matrices s*E-A
  • E,A : deux matrices telles que Fs=s*E-A

Description

Fonction utilitaire. Etant donné le faisceau Fs=s*E-A , renvoie les matrices E et A .

Examples

E=[1,0];A=[1,2];s=poly(0,'s');
[E,A]=pen2ea(s*E-A)


perms

Scilab Function
Last update : 09/11/2006

perms - retourne toutes les permutations des composantes d'un vecteur

Calling Sequence

y=iscellstr(x)

Parameters

  • x : un scalaire ou un vecteur.
  • x : un scalaire ou une matrice.

Description

Etant donné un vecteur x de longueur n , la fonction perms retourne toutes les permutations des n composantes de x , soit n! permutations. La matrice y est de taille n! x n .

Examples

// exemple 1 :
x=[4 7 10];
y=perms(x)

// exemple 2 :
x=[1 5 2 5];
y=perms(x)

See Also

permute ,


permute

Scilab Function
Last update : 09/12/2005

permute - permute the dimensions of an array

Calling Sequence

y=permute(x,dims)

Parameters

  • dims : a scalar or a vector of positive reals.
  • x : a scalar, a vector, a matrix or a mutlti-array.

Description

y=permute(x,dims) :

Examples

//example 1:
x=[1 2 3;4 5 6];
y=permute(x,[2 1]);

//example 2:
x=matrix(1:12,[2,3,2]);
y=permute(x,[3 1 2]);

See Also

pertrans , quote , cat ,

Author

Farid Belahcene


pertrans

Scilab Function
Last update : 12/01/2004

pertrans - pertranspose

Calling Sequence

[Y]=pertrans(X)

Parameters

  • X : real or complex matrix
  • Y : real or complex matrix

Description

Y=pertrans(X) returns the pertranspose of X , i.e. the symmetric of X w.r.t the second diagonal (utility function).

Examples

A=[1,2;3,4]
pertrans(A)


prod

Scilab Function
Last update : 14/12/2005

prod - produit des termes d'une matrice

Calling Sequence

y=prod(x)
y=prod(x,'r') ou y=prod(x,1)
y=prod(x,'c') ou y=prod(x,2)
y=prod(x,'m')

Parameters

  • x : vecteur ou matrice (réelle ou complexe)
  • y : scalaire ou vecteur

Description

Pour un vecteur ou une matrice x , y=prod(x) renvoie un scalaire y égal au produit des termes de x .

y=prod(x,'r') (ou y=prod(x,1) ) effectue le produit suivant l'indice de ligne. Chaque composante du vecteur ligne y contient le produit de la colonne correspondante x ( y(j)=prod(x(i,j),i=1,m) ).

y=prod(x,'c') (ou y=prod(x,2) ) effectue le produit suivant l'indice de colonne. Chaque composante du vecteur colonne y contient le produit de la ligne correspondante de x ( y(i)= prod(x(i,j),j=1,n) )).

y=prod(x,'m') effectue le produit suivant la première dimension plus grande que 1 (compatibilité avec Matlab).

Examples

A=[1,2;0,100];
prod(A)
prod(A,'c')
prod(A,'r')

See Also

cumprod , sum ,


rand

Scilab Function
Last update : 19/11/2004

rand - générateur de nombres aléatoires

Calling Sequence

rand(m1,m2,.. [,key])
rand(x [, key])
rand()
rand(key)
rand("seed" [,n])
rand("info")

Parameters

  • mi : entiers
  • key : chaîne de caractères, "uniform" ou "normal" ("uniform" par défaut)
  • x : une matrice, dont uniquement les dimensions sont prises en compte.

Description

Générateur de nombres aléatoires.

Sans l'argument key la syntaxe ci-dessous produit une matrice aléatoire dont chaque élément est la réalisation d'une variable aléatoire suivant une loi donnée (par défaut uniforme sur [0,1]).

rand(m1,m2) est une matrice aléatoire de dimensions m1 x m2 .
rand(m1,m2,..,mn) est une matrice aléatoire de dimensions m1 x m2 ,.. x mn .
rand(a) est une matrice aléatoire de mêmes dimensions que a. rand(a) est complexe si a est une matrice complexe.
rand() : sans argument, renvoie un scalaire aléatoire.

S'il est présent, l'argument key permet de spécifier la loi suivie par défaut par la variable aléatoire.

rand('uniform') La loi par défaut est uniforme sur l'intervalle [0,1].
rand('normal') La loi par défaut est une loi normale centrée réduite (moyenne 0, variance 1).
str=rand('info') renvoie 'uniform' ou 'normal' suivant la loi définie par défaut (voir ci-dessus).

Il est possible de réinitialiser l'état interne du générateur aléatoire (spécifié par un entier de l'intervalle [0,2^31-1]) ):

rand('seed') Renvoie la valeur courante de l'état interne.
rand('seed',n) Impose la valeur n pour l'état interne (par défaut l'état est initialisé à n=0 au premier appel).

Remarque

Il est conseillé d'utiliser plutôt la fonction grand qui permet aussi de simuler les lois les plus classiques (binomiale, poisson, ....).

Examples

x=rand(10,10,'uniform')
rand('normal')
rand('info')
y=rand(x,'normal');
x=rand(2,2,2)

See Also

grand , ssrand ,


rat

Scilab Function
Last update : 16/06/2004

rat - approximation rationnelle d'un flottant

Calling Sequence

[N,D]=rat(x [,tol])
y=rat(x [,tol])

Parameters

  • x : vecteur ou matrice réelle
  • n : vecteur ou matrice d'entiers
  • d : vecteur ou matrice d'entiers
  • y : vecteur ou matrice réelle

Description

[N,D] = rat(x,tol) renvoie deux matrices entières telles que N./D est proche de x au sens où abs(N./D - X) <= tol*abs(x) . Les approximations rationnelles sont obtenues par troncature d'un développement en fraction continue. tol = 1.e-6*norm(X,1) est la valeur de la tolérance par défaut. y = rat(x,tol) renvoie le quotient N./D

Examples

[n,d]=rat(%pi)
[n,d]=rat(%pi,1.d-12)
n/d-%pi

See Also

int , round ,


rdivf

Scilab Function
Last update : 16/06/2004

rdivf - division symbolique à droite

Calling Sequence

["r"]=ldivf("d","c")

Parameters

  • "d","c","r" : strings

Description

Renvoie la chaîne de caractères "c/d" Des simplifications triviales du type "c/1" = "c" sont effectuées.

Examples

ldivf('c','d')
ldivf('1','2')
ldivf('a','0')

See Also

ldivf ,


real

Scilab Function
Last update : 16/06/2004

real - partie réelle

Calling Sequence

[y]=real(x)

Parameters

  • x : matrice réelle ou complexe.
  • y : matrice réelle.

Description

real(x) renvoie la partie réelle de x (voir %i pour entrer des nombres complexes).

See Also

imag ,


round

Scilab Function
Last update : 16/06/2004

round - arrondi

Calling Sequence

y=round(x)

Parameters

  • x : matrice réelle ou complexe
  • y : matrice entière (ou complexe avec parties réelle et imaginaire entières)

Description

round(x) arrondit les éléments de x aux entiers les plus proches.

Examples

round([1.9 -2.5])-[2,-3]
round(1.6+2.1*%i)-(2+2*%i)
round(-%inf)
x=rand()*10^20;round(x)-x

See Also

int , floor , ceil ,


setdiff

Scilab Function
Last update : 12/01/2004

setdiff - returns components of a vector which do not belong to another one

Calling Sequence

v=setdiff(a,b)
[v,ka]=setdiff(a,b)

Parameters

  • a : vector of real numbers or strings
  • b : vector of real numbers or strings
  • v : vector of real numbers or strings with same orientation than a
  • ka : row vector of integers, ka(i) is the location of v(i) in a

Description

setdiff(a,b) returns a sorted vector which retains the a entries which are not in b

[v,ka]=setdiff(a,b) returns a sorted vector which retains the a entries which are not in b and the location of these entries in a.

Examples

 a = [223;111;2;4;2;2];
 b = [2;3;21;223;123;22];
 setdiff(a,b)
 [v,k]=setdiff(string(a),string(b))

See Also

unique , sort , union ,


signm

Scilab Function
Last update : 16/06/2004

signm - fonction signe matriciel

Description

Pour les matrices symétriques et hermitiennes X=signm(A) calcule la fonction signe matriciel.

Examples

A=rand(4,4);B=A+A';X=signm(B);spec(B),spec(X)

See Also

sign ,


sign

Scilab Function
Last update : 16/06/2004

sign - fonction signe

Description

X=sign(A) renvoie la matrice contenant les signes de termes A(i,j) . Pour les matrices complexes, sign(A) = A./abs(A) .

Examples

sign(rand(2,3))
sign(1+%i)

See Also

abs ,


sinc

Scilab Function
Last update : 12/01/2004

sinc - sinc function

Calling Sequence

t=sinc(x)

Parameters

  • x : real or complex vector or matrix
  • t : real or complex vector or matrix

Description

If x is a vector or a matrix, t=sinc(x) is the vector or matrix such that t(i)=sin(x(i))/x(i) if x(i)~=0 and t(i)=1 if x(i)==0

Examples

x=linspace(-10,10,3000);
plot2d(x,sinc(x))

See Also

sin , cos ,


sinhm

Scilab Function
Last update : 16/06/2004

sinhm - sinus hyperbolique matriciel

Calling Sequence

t=sinhm(x)

Parameters

  • x,t : matrice carrée réelle ou complexe

Description

sinhm(x) est le sinus hyperbolique matriciel de la matrice x. t=(expm(x)+expm(-x))/2 . Le résultat peut être imprécis pour les matrices non symétriques.

Examples

A=[1,2;2,4]
asinhm(sinhm(A))
A(1,1)=%i;sinhm(A)-(expm(A)-expm(-A))/2   // cas complexe

See Also

sinh , expm ,


sinh

Scilab Function
Last update : 16/06/2004

sinh - sinus hyperbolique

Calling Sequence

[y]=sinh(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)

Description

Pour un vecteur ou une matrice, les éléments de sinh(x) sont les sinus hyperboliques des éléments de x. Pour le sinus hyperbolique matriciel utiliser la fonction sinhm(X) .

Examples

asinh(sinh([0,1,%i]))

See Also

sinhm , asinh ,


sinm

Scilab Function
Last update : 16/06/2004

sinm - sinus matriciel

Calling Sequence

t=sinm(x)

Parameters

  • x : matrice réelle ou complexe

Description

sinm(x) est le sinus matriciel de la matrice x.

Examples

A=[1,2;2,4];
sinm(A)+0.5*%i*(expm(%i*A)-expm(-%i*A))

See Also

sin , asinm ,


sin

Scilab Function
Last update : 16/06/2004

sin - sinus

Calling Sequence

[y]=sin(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)

Description

Pour un vecteur ou une matrice, les éléments de sin(x) sont les sinus des éléments de x. Pour le sinus matriciel utiliser la fonction sinm(X) .

Examples

asin(sin([1,0,%i]))

See Also

sinm ,


size

Scilab Function
Last update : 16/06/2004

size - taille d'un objet

Calling Sequence

y=size(x [,sel])
[nr,nc]=size(x)

Parameters

  • x : matrice, liste ou liste de type syslin
  • y : un entier ou un vecteur d'entiers 1x2
  • sel : un entier ou une chaîne de caractères
  • nr,nc : deux entiers

Description

Appliquée à :une matrice (constante, polynomiale, de chaînes de caractères, booléenne, rationnelle) x , avec un seul argument en sortie, size renvoie un vecteur 1 x 2 [nombre de lignes, nombre de colonnes]. Appelée avec deux arguments en sortie, size renvoie nr,nc = [nombre de lignes, nombre de colonnes]. sel peut être utilisé pour indiquer la dimension désirée
1 ou 'r': pour obtenir le nombre de lignes
2 ou 'c': pour obtenir le nombre de colonnes
'*': pour obtenir le produit du nombre de lignes et de colonnes
Appliquée à :une liste, size en renvoie le nombre d'éléments. Dans ce cas seule la syntaxe y=size(x) peut être utilisée.
Appliquée à :un système dynamique linéaire, y=size(x) renvoie le vecteur ligne y = [nombre de sorties, nombre d'entrées] c'est à dire les dimensions de la matrice de transfert correspondante. La syntaxe [nr,nc]=size(x) est aussi valide (avec (nr,nc)=(y(1),y(2) ). Si x est un système dynamique linéaire donnée par sa représentation d'état, alors [nr,nc,nx]=size(x) renvoie de plus nx la dimension de la matrice A de x (la dimension de l'état).
Appliquée à :une hypermatrice, y=size(x) renvoie le vecteur de ses dimensions. La syntaxe [n1,n2,...nn]=size(x) est aussi acceptée. ni=size(x,i) renvoie la ième dimension et size(x,'*') renvoie le produit des dimensions.

Examples

[n,m]=size(rand(3,2))
[n,m]=size(['a','b';'c','d'])
x=ssrand(3,2,4);[ny,nu]=size(x)
[ny,nu]=size(ss2tf(x))
[ny,nu,nx]=size(x)

See Also

length , syslin ,


smooth

Scilab Function
Last update : 16/06/2004

smooth - interpolation par une spline

Calling Sequence

[pt]=smooth(ptd [,pas])

Parameters

  • ptd : vecteur réel à deux colonnes
  • pas : réel (pas de discrétisation des abscisses)
  • pt : vecteur réel à deux colonnes

Description

Cette fonction calcule les valeurs d'une spline d'interpolation dont les points de référence sont donnés par (ptd(1,i),ptd(2,i)) . Les abscisses ptd(1,:) doivent être classés par ordre croissant. La valeur par défaut du pas est égale à abs(maxi(ptd(1,:))-mini(ptd(1,:)))/100

Examples

x=[1 10 20 30 40];
y=[1 30 -10 20 40];
plot2d(x',y',[3],"011"," ",[-10,-40,50,50]);
yi=smooth([x;y],0.1);
plot2d(yi(1,:)',yi(2,:)',[1],"000");

See Also

splin , interp , interpln ,


solve

Scilab Function
Last update : 16/06/2004

solve - solveur symbolique de système linéaire

Calling Sequence

[x]=solve(A,b)

Parameters

  • A,b,x : matrices (resp. vecteurs) de chaînes de caractères

Description

Résout A*x = b quand A est une matrice triangulaire supérieure de chaînes de caractères.

Examples

A=['1','a';'0','2'];   //  matrice triangulaire supérieure
b=['x';'y'];
w=solve(A,b)
a=1;x=2;y=5;
evstr(w)
inv([1,1;0,2])*[2;5]

See Also

trianfml ,


sort

Scilab Function
Last update : 16/06/2004

sort - tri par ordre décroissant

Calling Sequence

[s, [k]]=sort(v)
[s, [k]]=sort(v,'r')
[s, [k]]=sort(v,'c')

Parameters

  • v,s : vecteur (plein ou creux) ou matrice de nombres réels ou de chaînes de caractères.
  • k : vecteur ou matrice de nombres entiers.

Description

s=sort(v) trie v par ordre décroissant. Si v est une matrice, cette instruction produit un tri de la matrice v vue comme un vecteur v(:) (les colonnes sont empilées). [s,k]=sort(v) donne de plus les indices des termes de s dans v , c'est à dire que v(k(:)) est le vecteur s .

s=sort(v,'r') effectue le tri par ordre décroissant de v suivant l'indice de ligne : chaque colonne de s est obtenue à partir de la colonne de v correspondante triée par ordre décroissant. [s,k]=sort(v,'r') renvoie de plus dans chaque colonne de k les indices tels que v(k(:,i),i)=s(:,i) pour chaque indice de colonne i .

s=sort(v,'c') effectue le tri par ordre décroissant de v suivant l'indice de colonne : chaque ligne de s est obtenue à partir de la ligne de v correspondante triée par ordre décroissant.

[s,k]=sort(v,'c') renvoie de plus dans chaque ligne de k les indices tels que v(i,k(i,:))=s(i,:) pour chaque indice de ligne i .

Les matrices ou vecteurs complexes sont triés par rapport au module complexe.

y=sort(A) est valide quand A est un vecteur creux. le tri suivant les lignes ou les colonnes n'est pas implémenté pour les matrices creuses.

Examples

[s,p]=sort(rand(1,10));
// p est une permutation aléatoire de 1:10
A=[1,2,5;3,4,2];
[A_trie,q]=sort(A);A(q(:))-A_trie(:)
v=1:10;
sort(v)
sort(v')
sort(v,'r')  // ne fait rien pour les vecteurs lignes
sort(v,'c')

See Also

find ,


sp2adj

Scilab Function
Last update : 16/06/2004

sp2adj - converts sparse matrix into adjacency form

Parameters

  • A : real or complex sparse matrix (nz non-zero entries)
  • xadj : integer vector of length (n+1).
  • adjncy : integer vector of length nz containing the row indices for the corresponding elements in anz
  • anz : column vector of length nz, containing the non-zero elements of A

Description

sp2adj converts a sparse matrix into its adjacency form (utility fonction). A = n x m sparse matrix. xadj, adjncy, anz = adjacency representation of A i.e:

xadj(j+1)-xadj(j) = number of non zero entries in row j. adjncy = column index of the non zeros entries in row 1, row 2,..., row n. anz = values of non zero entries in row 1, row 2,..., row n. xadj is a (column) vector of size n+1 and adjncy is an integer (column) vector of size nz=nnz(A) . anz is a real vector of size nz=nnz(A) .

Examples

A = sprand(100,50,.05);
[xadj,adjncy,anz]= sp2adj(A);
[n,m]=size(A);
p = adj2sp(xadj,adjncy,anz,[n,m]);
A-p,

See Also

adj2sp , sparse , spcompack , spget ,


sparse

Scilab Function
Last update : 12/01/2004

sparse - sparse matrix definition

Calling Sequence

sp=sparse(X)
sp=sparse(ij,v [,mn])

Parameters

  • X : real or complex full (or sparse) matrix
  • ij : two columns integer matrix (indices of non-zeros entries)
  • v : vector
  • mn : integer vector with two entries (row-dimension, column-dimension)
  • sp : sparse matrix

Description

sparse is used to build a sparse matrix. Only non-zero entries are stored.

sp = sparse(X) converts a full matrix to sparse form by squeezing out any zero elements. (If X is already sparse sp is X ).

sp=sparse(ij,v [,mn]) builds an mn(1) -by- mn(2) sparse matrix with sp(ij(k,1),ij(k,2))=v(k) . ij and v must have the same column dimension. If optional mn parameter is not given the sp matrix dimensions are the max value of ij(:,1) and ij(:,2) respectively.

Operations (concatenation, addition, etc,) with sparse matrices are made using the same syntax as for full matrices.

Elementary functions are also available ( abs,maxi,sum,diag,... ) for sparse matrices.

Mixed operations (full-sparse) are allowed. Results are full or sparse depending on the operations.

Examples

sp=sparse([1,2;4,5;3,10],[1,2,3])
size(sp)
x=rand(2,2);abs(x)-full(abs(sparse(x)))

See Also

full , spget , sprand , speye , lufact ,


spcompack

Scilab Function
Last update : 14/04/2005

spcompack - converts a compressed adjacency representation

Parameters

  • xadj : integer vector of length (n+1).
  • xlindx : integer vector of length n+1 (pointers).
  • lindx : integer vector
  • adjncy : integer vector

Description

Utility fonction spcompak is used to convert a compressed adjacency representation into standard adjacency representation.

Examples

// A is the sparse matrix:
A=[1,0,0,0,0,0,0;
   0,1,0,0,0,0,0;
   0,0,1,0,0,0,0;
   0,0,1,1,0,0,0;
   0,0,1,1,1,0,0;
   0,0,1,1,0,1,0;
   0,0,1,1,0,1,1];
A=sparse(A);
//For this matrix, the standard adjacency representation is given by:
xadj=[1,2,3,8,12,13,15,16];
adjncy=[1, 2, 3,4,5,6,7, 4,5,6,7, 5, 6,7, 7];
//(see sp2adj).
// increments in vector xadj give the number of non zero entries in each column
// ie there is 2-1=1 entry in the column 1
//    there is 3-2=1 entry in the column 2
//    there are 8-3=5 entries in the column 3
//              12-8=4                      4
//etc
//The row index of these entries is given by the adjncy vector
// for instance,
// adjncy (3:7)=adjncy(xadj(3):xadj(4)-1)=[3,4,5,6,7]
// says that the 5=xadj(4)-xadj(3) entries in column 3 have row
// indices 3,4,5,6,7.
//In the compact representation, the repeated sequences in adjncy
//are eliminated.
//Here in adjncy the sequences 4,5,6,7  and 7 are eliminated.
//The standard structure (xadj,adjncy) takes the compressed form (lindx,xlindx)
lindx=[1, 2, 3,4,5,6,7, 5, 6,7];
xlindx=[1,2,3,8,9,11];
//(Columns 4 and 7 of A are eliminated).
//A can be reconstructed from (xadj,xlindx,lindx).
[xadj,adjncy,anz]= sp2adj(A);
adjncy-spcompack(xadj,xlindx,lindx)

See Also

sp2adj , adj2sp , spget ,


speye

Scilab Function
Last update : 16/06/2004

speye - matrice identité creuse

Calling Sequence

Isp=speye(nrows,ncols)
Isp=speye(A)

Parameters

  • nrows : entier (nombre de lignes)
  • ncols : entier (nombre de colonnes)
  • A : matrice creuse
  • sp : matrice identité creuse

Description

Isp=speye(nrows,ncols) renvoie une matrice identité creuse Isp avec nrows lignes et ncols colonnes.

Isp=speye(A) renvoie une matrice identité creuse de même taille que A . Si [m,n]=size(A) , les commandes speye(m,n) et speye(A) sont équivalentes. En particulier speye(3) n'est pas équivalent à speye(3,3) .

Examples

eye(3,3)-full(speye(3,3))

See Also

sparse , full , eye , spzeros , spones ,


spget

Scilab Function
Last update : 12/01/2004

spget - retrieves entries of sparse matrix

Calling Sequence

[ij,v,mn]=spget(sp)

Parameters

  • sp : real or complex sparse matrix
  • ij : two columns integer matrix (indices of non-zeros entries)
  • mn : integer vector with two entries (row-dimension, column-dimension)
  • v : column vector

Description

spget is used to convert the internal representation of sparse matrices into the standard ij, v representation.

Non zero entries of sp are located in rows and columns with indices in ij .

Examples

sp=sparse([1,2;4,5;3,10],[1,2,3])
[ij,v,mn]=spget(sp);

See Also

sparse , sprand , speye , lufact ,


splin2d

Scilab Function
Last update : 24/03/2004

splin2d - bicubic spline gridded 2d interpolation

Calling Sequence

C = splin2d(x, y, z, [,spline_type])

Parameters

  • x,y : strictly increasing row vectors (with at least 2 components) defining the interpolation grid
  • z : nx x ny matrix (nx being the length of x and ny the length of y )
  • spline_type : (optionnal) a string selecting the kind of bicubic spline to compute
  • C : a big vector with the coefficients of the bicubic patches

Description

This function computes a bicubic spline or sub-spline s which interpolates the (xi,yj,zij) points, ie, we have s(xi,yj)=zij for all i=1,..,nx and j=1,..,ny. The resulting spline s is defined by the triplet (x,y,C) where C is the vector (of length 16(nx-1)(ny-1)) with the coefficients of each of the (nx-1)(ny-1) bicubic patches : on [x(i) x(i+1)]x[y(j) y(j+1)], s is defined by :

             _3_   _3_
             \     \                    k         l
    s(x,y) = /     /    C (k,l) (x - xi)  (y - yj)
             ---   ---   ij
             k=0   l=0

The evaluation of s at some points must be done by the interp2d function. Several kind of splines may be computed by selecting the appropriate spline_type parameter. The method used to compute the bicubic spline (or sub-spline) is the old fashionned one 's, i.e. to compute on each grid point (xi,yj) an approximation of the first derivatives ds/dx(xi,yj) and ds/dy(xi,yj) and of the cross derivative d2s/dxdy(xi,yj). Those derivatives are computed by the mean of 1d spline schemes leading to a C2 function (s is twice continuously differentiable) or by the mean of a local approximation scheme leading to a C1 function only. This scheme is selected with the spline_type parameter (see splin for details) :

  • "not_a_knot" : this is the default case.
  • "natural"
  • "periodic" : to use if the underlying function is periodic : you must have z(1,j) = z(nx,j) for all j in [1,ny] and z(i,1) = z(i,ny) for i in [1,nx] but this is not verified by the interface.
  • "monotone"
  • "fast"
  • "fast_periodic"

    • Remarks

    From an accuracy point of view use essentially the not_a_knot type or periodic type if the underlying interpolated function is periodic.

    The natural, monotone, fast (or fast_periodic) type may be useful in some cases, for instance to limit oscillations (monotone being the most powerfull for that).

    Examples

    // example 1 : interpolation of cos(x)cos(y)
n = 7;  // a regular grid with n x n interpolation points
        // will be used
x = linspace(0,2*%pi,n); y = x;
z = cos(x')*cos(y);
C = splin2d(x, y, z, "periodic");
m = 50; // discretisation parameter of the evaluation grid
xx = linspace(0,2*%pi,m); yy = xx;
[XX,YY] = ndgrid(xx,yy);
zz = interp2d(XX,YY, x, y, C);
emax = max(abs(zz - cos(xx')*cos(yy)));
xbasc()
plot3d(xx, yy, zz, flag=[2 4 4])
[X,Y] = ndgrid(x,y);
param3d1(X,Y,list(z,-9*ones(1,n)), flag=[0 0])
str = msprintf(" with %d x %d interpolation points. ermax = %g",n,n,emax)
xtitle("spline interpolation of cos(x)cos(y)"+str)

// example 2 : different interpolation functions on random datas
n = 6;
x = linspace(0,1,n); y = x;
z = rand(n,n);
np = 50;
xp = linspace(0,1,np); yp = xp;
[XP, YP] = ndgrid(xp,yp);
ZP1 = interp2d(XP, YP, x, y, splin2d(x, y, z, "not_a_knot"));
ZP2 = linear_interpn(XP, YP, x, y, z);
ZP3 = interp2d(XP, YP, x, y, splin2d(x, y, z, "natural"));
ZP4 = interp2d(XP, YP, x, y, splin2d(x, y, z, "monotone"));
xset("colormap", jetcolormap(64))
xbasc()
subplot(2,2,1)
   plot3d1(xp, yp, ZP1, flag=[2 2 4])
   xtitle("not_a_knot")
subplot(2,2,2)
   plot3d1(xp, yp, ZP2, flag=[2 2 4])
   xtitle("bilinear interpolation")
subplot(2,2,3)
   plot3d1(xp, yp, ZP3, flag=[2 2 4])
   xtitle("natural")
subplot(2,2,4)
   plot3d1(xp, yp, ZP4, flag=[2 2 4])
   xtitle("monotone")
xselect()

// example 3 : not_a_knot spline and monotone sub-spline
//             on a step function
a = 0; b = 1; c = 0.25; d = 0.75;
// create interpolation grid
n = 11;
x = linspace(a,b,n);
ind = find(c <= x & x <= d);
z = zeros(n,n); z(ind,ind) = 1;  // a step inside a square
// create evaluation grid
np = 220;
xp = linspace(a,b, np);
[XP, YP] = ndgrid(xp, xp);
zp1 = interp2d(XP, YP, x, x, splin2d(x,x,z));
zp2 = interp2d(XP, YP, x, x, splin2d(x,x,z,"monotone"));
// plot
xbasc()
xset("colormap",jetcolormap(128))
subplot(1,2,1)
   plot3d1(xp, xp, zp1, flag=[-2 6 4])
   xtitle("spline (not_a_knot)")
subplot(1,2,2)
   plot3d1(xp, xp, zp2, flag=[-2 6 4])
   xtitle("subspline (monotone)")

    See Also

    cshep2d , linear_interpn , interp2d ,

    Author

    B. Pincon


splin3d

Scilab Function
Last update : 06/07/2004

splin3d - spline gridded 3d interpolation

Calling Sequence

tl = splin3d(x, y, z, v, [order])

Parameters

  • x,y,z : strictly increasing row vectors (each with at least 3 components) defining the 3d interpolation grid
  • v : nx x ny x nz hypermatrix (nx, ny, nz being the length of x , y and z )
  • order : (optionnal) a 1x3 vector [kx,ky,kz] given the order of the tensor spline in each direction (default [4,4,4], i.e. tricubic spline)
  • tl : a tlist of type splin3d defining the spline

Description

This function computes a 3d tensor spline s which interpolates the (xi,yj,zk,vijk) points, ie, we have s(xi,yj,zk)=vijk for all i=1,..,nx, j=1,..,ny and k=1,..,nz. The resulting spline s is defined by tl which consists in a B-spline-tensor representation of s. The evaluation of s at some points must be done by the interp3d function (to compute s and its first derivatives) or by the bsplin3val function (to compute an arbitrary derivative of s) . Several kind of splines may be computed by selecting the order of the spline in each direction order=[kx,ky,kz] .

Remark

This function works under the conditions:

       nx, ny, nz >= 3
       2 <= kx < nx
       2 <= ky < ny
       2 <= kz < nz

an error being issued when they are not respected.

Examples

// example 1
func =  "v=cos(2*%pi*x).*sin(2*%pi*y).*cos(2*%pi*z)";
deff("v=f(x,y,z)",func);
n = 10;  // n x n x n  interpolation points
x = linspace(0,1,n); y=x; z=x; // interpolation grid
[X,Y,Z] = ndgrid(x,y,z);
V = f(X,Y,Z);
tl = splin3d(x,y,z,V,[5 5 5]);
m = 10000;
// compute an approximated error
xp = grand(m,1,"def"); yp = grand(m,1,"def"); zp = grand(m,1,"def");
vp_exact = f(xp,yp,zp);
vp_interp = interp3d(xp,yp,zp, tl);
er = max(abs(vp_exact - vp_interp))
// now retry with n=20 and see the error

// example 2 (see linear_interpn help page which have the
//            same example with trilinear interpolation)
getf("SCI/demos/interp/interp_demo.sci")
func =  "v=(x-0.5).^2 + (y-0.5).^3 + (z-0.5).^2";
deff("v=f(x,y,z)",func);
n = 5;
x = linspace(0,1,n); y=x; z=x;
[X,Y,Z] = ndgrid(x,y,z);
V = f(X,Y,Z);
tl = splin3d(x,y,z,V);
// compute (and display) the 3d spline interpolant on some slices
m = 41;
dir = ["z="  "z="  "z="  "x="  "y="];
val = [ 0.1   0.5   0.9   0.5   0.5];
ebox = [0 1 0 1 0 1];
XF=[]; YF=[]; ZF=[]; VF=[];
for i = 1:length(val)
   [Xm,Xp,Ym,Yp,Zm,Zp] = slice_parallelepiped(dir(i), val(i), ebox, m, m, m);
   Vm = interp3d(Xm,Ym,Zm, tl);
   [xf,yf,zf,vf] = nf3dq(Xm,Ym,Zm,Vm,1);
   XF = [XF xf]; YF = [YF yf]; ZF = [ZF zf]; VF = [VF vf];
   Vp = interp3d(Xp,Yp,Zp, tl);
   [xf,yf,zf,vf] = nf3dq(Xp,Yp,Zp,Vp,1);
   XF = [XF xf]; YF = [YF yf]; ZF = [ZF zf]; VF = [VF vf];
end
nb_col = 128;
vmin = min(VF); vmax = max(VF);
color = dsearch(VF,linspace(vmin,vmax,nb_col+1));
xset("colormap",jetcolormap(nb_col));
xbasc(); xset("hidden3d",xget("background"));
colorbar(vmin,vmax)
plot3d(XF, YF, list(ZF,color), flag=[-1 6 4])
xtitle("3d spline interpolation of "+func)
xselect()

See Also

linear_interpn , interp3d , bsplin3val ,

Authors

R.F. Boisvert, C. De Boor (code from the CMLIB fortran lib)
B. Pincon (scilab interface)


splin

Scilab Function
Last update : 24/03/2004

splin - cubic spline interpolation

Calling Sequence

d = splin(x, y [,spline_type [, der]])

Parameters

  • x : a strictly increasing (row or column) vector (x must have at least 2 components)
  • y : a vector of same format than x
  • spline_type : (optionnal) a string selecting the kind of spline to compute
  • der : (optionnal) a vector with 2 components, with the end points derivatives (to provide when spline_type="clamped")
  • d : vector of the same format than x ( di is the derivative of the spline at xi )

Description

This function computes a cubic spline or sub-spline s which interpolates the (xi,yi) points, ie, we have s(xi)=yi for all i=1,..,n. The resulting spline s is completly defined by the triplet (x,y,d) where d is the vector with the derivatives at the xi : s'(xi)=di (this is called the Hermite form). The evaluation of the spline at some points must be done by the interp function. Several kind of splines may be computed by selecting the appropriate spline_type parameter:

  • "not_a_knot" : this is the default case, the cubic spline is computed by using the following conditions (considering n points x1,...,xn):
        s'''(x2-) = s'''(x2+)
    s'''(x{n-1}-) = s'''(x{n-1}+)
  • "clamped" : in this case the cubic spline is computed by using the end points derivatives which must be provided as the last argument der :
        s'(x1) = der(1)
    s'(xn) = der(2)
  • "natural" : the cubic spline is computed by using the conditions:
        s''(x1) = 0
    s''(xn) = 0
  • "periodic" : a periodic cubic spline is computed ( y must verify y1=yn) by using the conditions:
        s'(x1) = s'(xn)
    s''(x1) = s''(xn)
  • "monotone" : in this case a sub-spline (s is only one continuously differentiable) is computed by using a local scheme for the di such that s is monotone on each interval:
        if y(i) <= y(i+1)  s is increasing on [x(i), x(i+1)]
    if y(i) >= y(i+1)  s is decreasing on [x(i), x(i+1)]
  • "fast" : in this case a sub-spline is also computed by using a simple local scheme for the di : d(i) is the derivative at x(i) of the interpolation polynomial of (x(i-1),y(i-1)), (x(i),y(i)),(x(i+1),y(i+1)), except for the end points (d1 being computed from the 3 left most points and dn from the 3 right most points).
  • "fast_periodic" : same as before but use also a centered formula for d1 = s'(x1) = dn = s'(xn) by using the periodicity of the underlying function ( y must verify y1=yn).

    • Remarks

    From an accuracy point of view use essentially the clamped type if you know the end point derivatives, else use not_a_knot. But if the underlying approximated function is periodic use the periodic type. Under the good assumptions these kind of splines got an O(h^4) asymptotic behavior of the error. Don't use the natural type unless the underlying function have zero second end points derivatives.

    The monotone, fast (or fast_periodic) type may be useful in some cases, for instance to limit oscillations (these kind of sub-splines have an O(h^3) asymptotic behavior of the error).

    If n=2 (and spline_type is not clamped) linear interpolation is used. If n=3 and spline_type is not_a_knot, then a fast sub-spline type is in fact computed.

    Examples

    // example 1
deff("y=runge(x)","y=1 ./(1 + x.^2)")
a = -5; b = 5; n = 11; m = 400;
x = linspace(a, b, n)';
y = runge(x);
d = splin(x, y);
xx = linspace(a, b, m)';
yyi = interp(xx, x, y, d);
yye = runge(xx);
xbasc()
plot2d(xx, [yyi yye], style=[2 5], leg="interpolation spline@exact function")
plot2d(x, y, -9)
xtitle("interpolation of the Runge function")

// example 2 : show behavior of different splines on random datas
a = 0; b = 1;        // interval of interpolation
n = 10;              // nb of interpolation  points
m = 800;             // discretisation for evaluation
x = linspace(a,b,n)'; // abscissae of interpolation points
y = rand(x);          // ordinates of interpolation points
xx = linspace(a,b,m)';
yk = interp(xx, x, y, splin(x,y,"not_a_knot"));
yf = interp(xx, x, y, splin(x,y,"fast"));
ym = interp(xx, x, y, splin(x,y,"monotone"));
xbasc()
plot2d(xx, [yf ym yk], style=[5 2 3], strf="121", ...
       leg="fast@monotone@not a knot spline")
plot2d(x,y,-9, strf="000")  // to show interpolation points
xtitle("Various spline and sub-splines on random datas")
xselect()

    See Also

    interp , lsq_splin ,

    Authors

    B. Pincon
    F. N. Fritsch (pchim.f Slatec routine is used for monotone interpolation)


spones

Scilab Function
Last update : 16/06/2004

spones - matrice creuse dont les termes valent 1

Parameters

  • A : matrice creuse
  • sp : matrice creuse

Description

sp=spones(A) génère une matrice creuse de même structure que A , mais où les termes non-nuls ont été remplacés par la valeur 1.

Examples

A=sprand(10,12,0.1);
sp=spones(A)
B = A~=0
bool2s(B)

See Also

sparse , full , eye , speye , spzeros ,


sprand

Scilab Function
Last update : 16/06/2004

sprand - matrice creuse aléatoire

Calling Sequence

sp=sprand(nrows,ncols,fill [,typ])

Parameters

  • nrows : entier (nombre de lignes)
  • ncols : entier (nombre de colonnes)
  • fill : coefficient de remplissage (densité)
  • typ : chaîne de caractères ( 'uniform' (par défaut) ou 'normal' )
  • sp : matrice creuse

Description

sp=sprand(nrows,ncols,fill) renvoie une matrice creuse sp avec nrows lignes, ncols colonnes et approximativement fill*nrows*ncols termes non-nuls.

Si typ='uniform' les termes non nuls suivent une loi uniforme sur [0,1]. Si typ='normal' les termes non nuls suivent une loi normale centrée réduite.

Examples

W=sprand(100,1000,0.001);

See Also

sparse , full , rand , speye ,


spzeros

Scilab Function
Last update : 28/06/2006

spzeros - sparse zero matrix

Calling Sequence

sp=spzeros(nrows,ncols)
sp=spzeros(A)

Parameters

  • nrows : integer (number of rows)
  • ncols : integer (number os columns)
  • A : sparse matrix
  • sp : sparse zero matrix

Description

sp=spzeros(nrows,ncols) returns a sparse zero matrix sp with nrows rows, ncols columns. (Equivalent to sparse([],[],[nrow,ncols]) )

sp=spzeros(A) returns a sparse zero matrix with same dimensions as A . If [m,n]=size(A) , spzeros(m,n) and spzeros(A) are equivalent. In particular spzeros(3) is not equivalent to spzeros(3,3) .

Examples

sum(spzeros(1000,1000))

See Also

sparse , full , eye , speye , spones ,


sqrtm

Scilab Function
Last update : 16/06/2004

sqrtm - racine carrée matricielle

Calling Sequence

y=sqrtm(x)

Parameters

  • x : matrice carrée réelle ou complexe

Description

y=sqrt(x) est la racine carrée matricielle de la matrice x ( x=y^2 ) Le résultat peut être imprécis si x n'est pas symétrique.

Examples

x=[0 1;2 4]
w=sqrtm(x);
norm(w*w-x)
x(1,2)=%i;
w=sqrtm(x);norm(w*w-x,1)

See Also

expm , sqroot ,


sqrt

Scilab Function
Last update : 16/06/2004

sqrt - racine carrée

Calling Sequence

y=sqrt(x)

Parameters

  • x : vecteur ou matrice (réelle ou complexe)

Description

sqrt(x) contient les racines carrées des éléments de x . Le résultat est complexe si des composantes de x sont négatives.

Examples

sqrt([2,4])
sqrt(-1)

See Also

hat , sqrtm ,


squarewave

Scilab Function
Last update : 16/06/2004

squarewave - génère un signal carré de période 2*%pi

Calling Sequence

x=squarewave(t [,percent)

Parameters

  • t : vecteur réel, valeurs des instants
  • x : vecteur réel, valeurs du signal dans l'intervalle [-1,1]
  • percent : scalaire positif réel, pourcentage de la période pendant lequel le signal est positif (50 par défaut)

Description

squarewave(t) génère le vecteur des valeurs d'un signal carré de période 2*%pi à chaque instant donné dans le vecteur t .

squarewave(t,percent) génère un signal carré où percent est le pourcentage de la période pendant lequel le signal est positif.

Examples

t=(0:0.1:5*%pi)';
plot2d1('onn',t,[2*sin(t),1.5*squarewave(t),squarewave(t,10)])

See Also

sin , cos ,


ssprint

Scilab Function
Last update : 12/01/2004

ssprint - pretty print for linear system

Calling Sequence

ssprint(sl [,out])

Parameters

  • sl : list ( syslin list)
  • out : output (default value out=%io(2) )

Description

pretty print of a linear system in state-space form sl=(A,B,C,D) syslin list.

Examples

 a=[1 1;0 1];b=[0 1;1 0];c=[1,1];d=[3,2];
 ssprint(syslin('c',a,b,c,d))
 ssprint(syslin('d',a,b,c,d))

See Also

texprint ,


ssrand

Scilab Function
Last update : 12/01/2004

ssrand - random system generator

Calling Sequence

sl=ssrand(nout,nin,nstate)
[sl,U]=ssrand(nout,nin,nstate,flag)

Parameters

  • nout : integer (number of output)
  • nin : integer (number of input)
  • nstate : integer (dimension of state-space)
  • flag : list made of one character string and one or several integers
  • sl : list ( syslin list)
  • U square (nstate x nstate) nonsingular matrix

Description

sl=ssrand(nout,nin,nstate) returns a random strictly proper ( D=0 ) state-space system of size [nout,nint] represented by a syslin list and with nstate state variables.

[sl,U]=ssrand(nout,nin,nstate,flag) returns a test linear system with given properties specified by flag . flag can be one of the following:

flag=list('co',dim_cont_subs)
flag=list('uo',dim_unobs_subs)
flag=list('ncno',dim_cno,dim_ncno,dim_co,dim_nco)
flag=list('st',dim_cont_subs,dim_stab_subs,dim_stab0)
flag=list('dt',dim_inst_unob,dim_instb0,dim_unobs)
flag=list('on',nr,ng,ng0,nv,rk)
flag=list('ui',nw,nwu,nwui,nwuis,rk)

The complete description of the Sys is given in the code of the ssrand function (in SCIDIR/macros/util ). For example with flag=list('co',dim_cont_subs) a non-controllable system is return and dim_cont_subs is the dimension of the controllable subspace of Sys . The character strings 'co','uo','ncno','st','dt','on','ui' stand for "controllable", "unobservable", "non-controllable-non-observable", "stabilizable","detectable","output-nulling","unknown-input".

Examples

//flag=list('st',dim_cont_subs,dim_stab_subs,dim_stab0)
//dim_cont_subs<=dim_stab_subs<=dim_stab0
//pair (A,B) U-similar to:
//    [*,*,*,*;     [*;
//    [0,s,*,*;     [0;
//A=  [0,0,i,*;   B=[0;
//    [0,0,0,u]     [0]
//
// (A11,B1) controllable  s=stable matrix i=neutral matrix u=unstable matrix
[Sl,U]=ssrand(2,3,8,list('st',2,5,5));
w=ss2ss(Sl,inv(U)); //undo the random change of basis => form as above
[n,nc,u,sl]=st_ility(Sl);n,nc

See Also

syslin ,


sub2ind

Scilab Function
Last update : 12/01/2004

sub2ind - matrix subscript values to linear index

Calling Sequence

I = sub2ind(dims,i1,i2,...)
J = sub2ind(dims,Mi)

Parameters

  • dims : vector: the matrix dimensions
  • i1,i2,... : the subscript value arrays(same matrix shape as I )
  • Mi : matrix whose columns contains the subscript values.
  • I : the linear index array

Description

sub2ind is used to determine the equivalent single index corresponding to a given set of subscript values. I = sub2ind(dims,i1,i2,..) returns the linear index equivalent to the row, column, ... subscripts in the arrays i1 , i2 ,.. for an matrix of size dims . In this case i1 , i2 ,.. must have the same shape and the result I has the same matrix shape. I = sub2ind(dims,Mi) returns the linear index equivalent to the subscripts in the columns of the matrix Mi for a matrix of size dims . in this case I is a column vector

Examples

i=[1 2 1 1 2 1 1];
j=[1 2 3 1 2 3 3];
k=[1 2 1 2 1 2 1];
sub2ind([2,3,2],i,j,k)

sub2ind([2,3,2],[i',j',k'])
</EXAMPLE>

See Also

ind2sub , extraction , insertion ,

Author

Serge Steer, INRIA


subf

Scilab Function
Last update : 16/06/2004

subf - soustraction symbolique

Calling Sequence

["c"]=subf("a","b")

Parameters

  • "a","b","c" : strings

Description

Renvoie la chaîne de caractères c = "a-b" . Des simplifications triviales du type subf("0","a") et subf("1","2") sont effectuées.

Examples

subf('0','a')
subf('2','1')
subf('a','0')

See Also

mulf , ldivf , rdivf , eval , evstr ,


sum

Scilab Function
Last update : 14/12/2005

sum - somme des vecteurs et matrices

Calling Sequence

y=sum(x)
y=sum(x,'r') ou y=sum(x,1)
y=sum(x,'c') ou y=sum(x,2)
y=sum(x,'m')

Parameters

  • x : vecteur ou matrice (entière, réelle ou complexe)
  • y : vecteur ou matrice (entière, réelle ou complexe)

Description

Si x est un vecteur ou une matrice, y=sum(x) retourne le scalaire y contenant la somme de tous les élements de x .

y=sum(x,'r') (ou y=sum(x,1) ) retourne le vecteur ligne y : y(j)= sum(x(:,j)) .

y=sum(x,'c') (ou y=sum(x,2) ) retourve le vecteur colonne y : y(i)= sum(x(i,:)) )).

y=sum(x,'m') effectue la somme selon la première dimension plus grande que 1 (compatibilité avec Matlab).

Examples

A=[1,2;3,4];
trace(A)-sum(diag(A))
sum(A,'c')-A*ones(2,1)
sum(A+%i)
A=sparse(A);sum(A,'c')-A*ones(2,1)
s=poly(0,'s');
M=[s,%i+s;s^2,1];
sum(M),sum(M,2)

See Also

cumsum , prod ,


sysconv

Scilab Function
Last update : 12/01/2004

sysconv - system conversion

Calling Sequence

[s1,s2]=sysconv(s1,s2)

Parameters

  • s1,s2 : list (linear syslin systems)

Description

Converts s1 and s2 into common representation in order that system interconnexion operations can be applied. Utility function for experts. The conversion rules in given in the following table.

"c": continuous time system
"d": discrete time system
n: sampled system with sampling period n
[]: system with undefined time domain For mixed systems s1 and s2 are put in state-space representation.

 s1\s2|    "c"     |     "d"     |      n2        |     []     |
 ---------------------------------------------------------------
 "c"   | nothing    |uncompatible | c2e(s1,n2)     |  c(s2)     |
 ---------------------------------------------------------------
 "d"   |uncompatible| nothing     | e(s1,n2)       |  d(s2)     |
 ---------------------------------------------------------------
 n1    | c2e(s2,n1) | e(s2,n1)    | n1<>n2 uncomp  |  e(s2,n1)  |
       |            |             | n1=n2  nothing |            |
 ---------------------------------------------------------------
 []    | c(s1)      | d(s1)       | e(s1,n2)       |  nothing   |
 ---------------------------------------------------------------

With the following meaning:

n1,n2: sampling period
c2e(s,n): the continuous-time system s is transformed into a sampled system with sampling period n.
c(s): conversion to continuous (time domain is "c" )
d(s): conversion to discrete (time domain is "d" )
e(s,n): conversion to samples system with period n

Examples

s1=ssrand(1,1,2);
s2=ss2tf(s1);
[s1,s2]=sysconv(s1,s2);

See Also

syslin , ss2tf , tf2ss ,


sysdiag

Scilab Function
Last update : 12/01/2004

sysdiag - block diagonal system connection

Calling Sequence

r=sysdiag(a1,a2,...,an)

Description

Returns the block-diagonal system made with subsystems put in the main diagonal

ai: subsystems (i.e. gains, or linear systems in state-space or transfer form)

Used in particular for system interconnections.

Remark

At most 17 arguments.

Examples

 s=poly(0,'s')
 sysdiag(rand(2,2),1/(s+1),[1/(s-1);1/((s-2)*(s-3))])
 sysdiag(tf2ss(1/s),1/(s+1),[1/(s-1);1/((s-2)*(s-3))])

 s=poly(0,'s')
 sysdiag(rand(2,2),1/(s+1),[1/(s-1);1/((s-2)*(s-3))])
 sysdiag(tf2ss(1/s),1/(s+1),[1/(s-1);1/((s-2)*(s-3))])

See Also

brackets , insertion , feedback ,


syslin

Scilab Function
Last update : 16/06/2004

syslin - définition d'un système dynamique linéaire

Calling Sequence

[sl]=syslin(dom,A,B,C [,D [,x0] ])
[sl]=syslin(dom,N,D)
[sl]=syslin(dom,H)

Parameters

  • dom : chaîne de caractères ( 'c' , 'd' ), ou [] ou un scalaire.
  • A,B,C,D : matrices de la représentation d'état ( D est optionnelle, matrice nulle par défaut). Pour les systèmes impropres D est une matrice polynomiale.
  • x0 : vecteur (état initial, vecteur nul par défaut)
  • N, D : matrices polynomiales
  • H : matrice rationnelle
  • sl : tlist (liste de type " syslin ") représentant le système dynamique

Description

syslin définit un système dynamique linéaire en temps que liste typée, et vérifie la consistance des données.

dom spécifie le domaine temporel :

dom='c' pour un système à temps continu, dom='d' pour un système à temps discret, n pour un système échantillonné à la période n (en secondes).

dom=[] si le domaine temporel n'est pas défini

Représentation d'état :

sl=syslin(dom,A,B,C [,D [,x0] ])

représente le système :

      s x  = A*x + B*u
        y  = C*x + D*u
      x(0) = x0

La sortie de syslin est une liste de la forme suivante : sl=tlist(['lss','A','B','C','D','X0','dt'],A,B,C,D,x0,dom) Notez que D peut être une matrice polynomiale (systèmes impropres).

Représentation sous forme de matrice de transfert :

sl=syslin(dom,N,D)
sl=syslin(dom,H)

La sortie de syslin est une liste de la forme : sl=tlist(['r','num','den','dt'],N,D,dom) ou sl=tlist(['r','num','den','dt'],H(2),H(3),dom) .

Les systèmes linéaires obtenus en sortie de syslin peuvent être manipulés comme des matrices usuelles (concaténation, extraction, transposition, multiplication, etc.) dans les deux types de représentation (représentation d'état ou matrice de transfert).

La plupart des fonctions de la librairie de contrôle acceptent les listes de type syslin en argument au lieu des quatre matrices de la représentation d'état.

Examples

A=[0,1;0,0];B=[1;1];C=[1,1];
S1=syslin('c',A,B,C)   // Définition du système
S1.A    // La matrice A
S1.X0, S1.dt // affichage de X0 et du domaine temporel
s=poly(0,'s');
D=s;
S2=syslin('c',A,B,C,D)
H1=(1+2*s)/s^2, S1bis=syslin('c',H1)
H2=(1+2*s+s^3)/s^2, S2bis=syslin('c',H2)
S1+S2
[S1,S2]
ss2tf(S1)-S1bis
S1bis+S2bis
S1*S2bis
size(S1)

See Also

tlist , lsslist , rlist , ssrand , ss2tf , tf2ss , dscr , abcd ,


tanhm

Scilab Function
Last update : 16/06/2004

tanhm - tangente hyperbolique matricielle

Calling Sequence

[t]=tanhm(x)

Parameters

  • x,t : matrice carrée réelle ou complexe

Description

tanhm(x) est la tangente matricielle hyperbolique de la matrice carrée x.

Examples

A=[1,2;3,4];
tanhm(A)

See Also

tan , tanm , expm , sinm , cosm , atanhm ,


tanh

Scilab Function
Last update : 16/06/2004

tanh - tangente hyperbolique

Calling Sequence

t=tanh(x)

Parameters

  • x,t : vecteur ou matrice (réelle ou complexe)

Description

Les éléments de t sont les tangentes hyperboliques des éléments de x .

Examples

x=[1,%i,-1,-%i]
tanh(x)
sinh(x)./cosh(x)

See Also

atanh , tan , tanhm ,


tanm

Scilab Function
Last update : 16/06/2004

tanm - tangente matricielle

Calling Sequence

[t]=tanm(x)

Parameters

  • x,t : matrice carrée réelle ou complexe

Description

tanm(x) est la tangente matricielle de la matrice carrée x.

Examples

A=[1,2;3,4];
tanm(A)

See Also

tan , tanhm , expm , sinm , cosm , atanhm ,


tan

Scilab Function
Last update : 16/06/2004

tan - tangente

Calling Sequence

t=tan(x)

Parameters

  • x,t : vecteur ou matrice (réelle ou complexe)

Description

Les éléments de t sont les tangentes des éléments de x .

Examples

x=[1,%i,-1,-%i]
tan(x)
sin(x)./cos(x)

See Also

atan , tanh , tanm ,


toeplitz

Scilab Function
Last update : 16/06/2004

toeplitz - matrice de Toeplitz

Calling Sequence

A=toeplitz(c [,r])

Parameters

  • a,c,r : matrice complexe, réelle, polynomiale ou de chaînes de caractères.

Description

Renvoie la matrice de Toeplitz dont la première ligne est r et la première colonne est c . c(1) doit être égal à r(1) . toeplitz(c) renvoie la matrice de Toeplitz symétrique.

Examples

A=toeplitz(1:5);
//
T=toeplitz(1:5,1:2:7);T1=[1 3 5 7;2 1 3 5;3 2 1 3;4 3 2 1;5 4 3 2];
T-T1
//
s=poly(0,'s');
t=toeplitz([s,s+1,s^2,1-s]);
t1=[s,1+s,s*s,1-s;1+s,s,1+s,s*s;s*s,1+s,s,1+s;1-s,s*s,1+s,s]
t-t1
//
t=toeplitz(['1','2','3','4']);
t1=['1','2','3','4';'2','1','2','3';'3','2','1','2';'4','3','2','1']

See Also

matrix ,


trfmod

Scilab Function
Last update : 12/01/2004

trfmod - poles and zeros display

Calling Sequence

[hm]=trfmod(h [,job])

Description

To visualize the pole-zero structure of a SISO transfer function h .

job='p': visualization of polynomials (default)
job='f': visualization of natural frequencies and damping

Interactive simplification of h . trfmod opens a dialog window.

See Also

poly , simp ,


trianfml

Scilab Function
Last update : 16/06/2004

trianfml - triangularisation symbolique

Calling Sequence

[f [,sexp]]=trianfml(f [,sexp])

Description

Triangularisation symbolique de la matrice f . La triangularisation est faite par manipulations élémentaires de lignes et de colonnes. sexp est un ensemble d'expressions communes stockées par l'algorithme.

Examples

A=['1','2';'a','b']
W=trianfml([A,string(eye(2,2))])
U=W(:,3:4)
a=5;b=6;
A=evstr(A)
U=evstr(U)
U*A
evstr(W(:,1:2))

See Also

addf , mulf , solve , trisolve ,


tril

Scilab Function
Last update : 16/06/2004

tril - partie triangulaire inférieure d'une matrice

Calling Sequence

tril(x [,k])

Parameters

  • x : matrice de tout type
  • k : entier (0 par défaut)

Description

Partie triangulaire inférieure d'une matrice. tril(x,k) est composée des termes sous une diagonale : k>0 (diagonale supérieure) et k<0 (diagonale sous la diagonale principale).

Examples

s=poly(0,'s');
tril([s,s;s,1])
tril([1/s,1/s;1/s,1])

See Also

triu , ones , eye , diag ,


trisolve

Scilab Function
Last update : 16/06/2004

trisolve - solveur symbolique de système linéaire

Calling Sequence

[x [,sexp]] = trisolve(A,b [,sexp])

Parameters

  • A,b,x : matrices (resp. vecteurs) de chaînes de caractères

Description

Résout A*x = b quand A est une matrice triangulaire supérieure de chaînes de caractères.

sexp est un ensemble d'expressions communes dans A , b et x .

Examples

A=['x','y';'0','z'];b=['0';'1'];
w=trisolve(A,b)
x=5;y=2;z=4;
evstr(w)
inv(evstr(A))*evstr(b)

See Also

trianfml , solve ,

Author

F.D, S.S


triu

Scilab Function
Last update : 16/06/2004

triu - partie triangulaire supérieure d'une matrice

Calling Sequence

triu(x [,k])

Parameters

  • x : matrice de tout type
  • k : entier (0 par défaut)

Description

Partie triangulaire supérieure d'une matrice. triu(x,k) est composée des termes au dessus d'une diagonale : k>0 (diagonale supérieure) et k<0 (diagonale sous la diagonale principale).

Examples

s=poly(0,'s');
triu([s,s;s,1])
triu([1/s,1/s;1/s,1])

See Also

tril , ones , eye , diag ,


typeof

Scilab Function
Last update : 12/01/2004

typeof - object type

Calling Sequence

[t]=typeof(object)

Parameters

  • object : Scilab object
  • t : string

Description

t=typeof(object) returns one of the following strings:

"constant"if object is a real or complex constant matrix
"polynomial"if object is a polynomial matrix
"function"if object is a function
"handle"if object is an handle
"string"if object is a matrix made of character strings
"boolean"if object is a boolean matrix
"list"if object is a list
"rational"if object is a rational matrix (transfer matrix)
"state-space"if object is a state-space model (see syslin )
"sparse"if object is a (real) sparse matrix.
"boolean sparse"if object is a boolean sparse matrix.
if object is a tlist or mlist, t is the firststring in the first list entry.

Examples

typeof(1)
typeof(poly(0,'x'))

typeof(1/poly(0,'x'))
typeof(%t)

w=sprand(100,100,0.001);
typeof(w)
typeof(w==w)

deff('y=f(x)','y=2*x');
typeof(f)

L=tlist(['V','a','b'],18,'Scilab');
typeof(L)

See Also

type , strings , syslin , poly ,


union

Scilab Function
Last update : 16/06/2004

union - extrait les composantes distinctes issues de l'union de deux vecteurs

Calling Sequence

[v, [ka,kb]]=union(a,b)

Parameters

  • a, b, v : vecteurs réels ou vecteurs de chaînes de caractères
  • ka, kb : vecteurs lignes d'entiers

Description

union(a,b) renvoie un vecteur contenant les valeurs distinctes (classées par ordre croissant) contenues dans les termes de [a(:);b(:)] .

[v,ka,kb]=union(a,b) renvoie aussi les vecteurs d'indices ka et kb tels que v est une combinaison triée des termes de a(ka) et b(kb) .

Examples

A=round(5*rand(10,1));
B=round(5*rand(7,1));

union(A,B)
[N,ka,kb]=union(A,B)

union('a'+string(A),'b'+string(B))

See Also

unique , sort ,


unique

Scilab Function
Last update : 16/06/2004

unique - extrait les composantes distinctes d'un vecteur

Calling Sequence

[N, [k]]=unique(M)

Parameters

  • M,N : vecteur réel ou vecteur de chaînes de caractères
  • k : vecteur d'entiers

Description

unique(M) renvoie un vecteur contenant les valeurs distinctes contenues dans les termes de M classées par ordre croissant.

S'il est présent l'argument de sortie k contient la position de la première occurrence de chaque valeur distincte dans M .

Examples

M=round(2*rand(20,1));

unique(M)
[N,k]=unique(M)

unique(string(M))
[N,k]=unique(string(M))

See Also

union , sort , lex_sort ,


vectorfind

Scilab Function
Last update : 12/01/2004

vectorfind - finds in a matrix rows or columns matching a vector

Calling Sequence

ind = vectorfind(m,v,job)

Parameters

  • m : a matrix of any type
  • v : vector of any type
  • job : string flag with possible values "r" to look for matching rows or "c" to look for matching columns
  • ind : row vector containing indices of matching rows or columns

Description

finds in a matrix rows or columns matching a vector

Examples

      alr=[1,2,2;
       1,2,1;
       1,1,2;
       1,1,1;
       1,2,1];
      ind = vectorfind(alr,[1,2,1],'r')
      ind = vectorfind(string(alr),string([1,2,1]),'r')

See Also

find , gsort ,

Author

R. Nikoukhah, S. Steer INRIA


zeros

Scilab Function
Last update : 16/06/2004

zeros - matrice nulle

Calling Sequence

y=zeros(m1,m2,...)
y=zeros(x)
y=zeros()

Parameters

  • x,y : matrices
  • m1, m2,.. : entiers

Description

Renvoie une matrice dont tous les termes sont nuls.

zeros(m1,m2)Renvoie une matrice nulle de taille (m1,m2) .
zeros(m1,m2,..,mn): renvoie une matrice nulle de taille (m1,m2,..,mn) .
zeros(x): renvoie une matrice nulle de même taille que x .
zeros(x)est aussi valide si x est une liste de type syslin (système dynamique linéaire sous forme d'une fonction de transfert ou d'une représentation d'état).

Notez que zeros(3) est équivalent à zeros(a) avec a=3 et donc n'est PAS une matrice 3x3 !

zeros() est équivalent à zeros(1,1).

Examples

zeros(3)
zeros(3,3)
zeros(2,3,2)

See Also

eye , ones , spzeros ,


Entrées-sorties
diary - diary of session
dir - get file list
disp - displays variables
dispfiles - display opened files properties
file - file management
fileinfo - Provides information about a file
fileparts - returns the path, filename and extension for a file path
fprintf - Emulator of C language fprintf function
fprintfMat - print a matrix in a file.
fscanf - Converts formatted input read on a file
fscanfMat - Reads a Matrix from a text file.
fullfile - Construit un nom de fichier complet
getio - get Scilab input/output logical units
input - prompt for user input
isdir - checks if argument is a directory path
lines - rows and columns used for display
listvarinfile - list the contents of a saved data file
load - load saved variable
loadmatfile - loads a Matlab V6 MAT-file (binary or ASCII) into Scilab
ls - show files
manedit - editing a manual item
matfile2sci - convertit un fichier Matlab .mat en un fichier binaire Scilab
mclearerr - reset binary file access errors
mclose - close an opened file
mdelete - Delete file(s)
meof - check if end of file has been reached
merror - tests the file access errors indicator
mfscanf - interface to the C fscanf function
mscanf - interface to the C scanf function
msscanf - interface to the C sscanf function
mget - reads byte or word in a given binary format and convert to double
mgeti - reads byte or word in a given binary format return an int type
mgetl - read lines from an ascii file
mgetstr - read a character string
mopen - open a file
mfprintf - converts, formats, and writes data to a file
mprintf - converts, formats, and writes data to the main scilab window
msprintf - converts, formats, and writes data in a string
mput - writes byte or word in a given binary format
mputl - writes strings in an ascii file
mputstr - write a character string in a file
mseek - set current position in binary file.
mtell - binary file management
newest - returns newest file of a set of files
oldload - load saved variable in 2.4.1 and previous formats
oldsave - saving variables in 2.4.1 and previous format
print - prints variables in a file
printf - Emulator of C language printf function
printf_conversion - printf, sprintf, fprintf conversion specifications
read - matrices read
read4b - fortran file binary read
readb - fortran file binary read
readc_ - read a character string
readmps - reads a file in MPS format
readxls - reads an Excel file
save - saving variables in binary files
save_format - format of files produced by "save"
savematfile - write a Matlab MAT-file (binary or ASCII)
scanf - Converts formatted input on standard input
scanf_conversion - scanf, sscanf, fscanf conversion specifications
sprintf - Emulator of C language sprintf function
sscanf - Converts formatted input given by a string
startup - startup file
tk_getdir - dialog to get a directory path
tk_getfile - dialog to get one or more file paths
tk_savefile - dialog to get a file path for writing
warning - warning messages
writb - fortran file binary write
write - write in a formatted file
write4b - fortran file binary write
xgetfile - dialog to get a file path
xls_open - Open an Excel file for reading
xls_read - read a sheet in an Excel file


diary

Scilab Function
Last update : 12/01/2004

diary - diary of session

Calling Sequence

diary('file-name')

Description

diary creates a file which contains a copy of the current Scilab session. diary(0) interrupts the diary.

See Also

exec , unix ,


dir

Scilab Function
Last update : 13/07/2005

dir - get file list

Calling Sequence

dir path
S=dir([path])

Parameters

  • path : a string matrix giving a directory pathname (eventually ended by a pattern built with * ). Default value is .
  • S : a tlist of type dir with fields : name , date and isdir

Description

dir can be used to get the files which match the patterns given by the path argument. Patterns are given to the unix ls or to the windows dir commands in order to get information on files. Thus in order to write portable Scilab script valid wildcard patterns for both os are to be given. Note that Pathname conversion is performed and for example SCI/macros/util/*.sci is a valid pattern for both unix and windows.

The name field of the returned variable is the column vector of the file names.

The date field of the returned variable is the column vector of integers containing a last modification date coded in second from 1 Jan 1970).

The isdir field of the returned variable is the column vector of boolean true if the corresponding name is a directory.

The default display of the returned structure is a column formatted list of files. It can be changed redefining the function %dir_p

Examples

    dir
    dir SCI/macros/util/base*.sci
    x=dir('SCI/macros/util/base*.sci')
    dt=getdate(x.date);
    mprintf("%s: %d-%d-%d %d:%d:%d\n",x.name,dt(:,[3 2 1 7:9]))

See Also

listfiles , ls , fileinfo , date ,


dispfiles

Scilab Function
Last update : 12/01/2004

dispfiles - display opened files properties

Calling Sequence

dispfiles([units])

Parameters

  • units : a vector of numbers, the file's logical units. By default all opened files.

Description

dispfiles displays properties of currently opened files.

Examples

dispfiles()

See Also

file , mopen ,

Author

S. Steer


disp

Scilab Function
Last update : 04/10/2004

disp - displays variables

Calling Sequence

disp(x1,[x2,...xn])

Description

displays xi with the current format. xi 's are arbitrary objects (matrices of constants, strings, functions, lists, ...)

Display of objects defined by tlist may be overloaded by the definition of a function. This function must have no output argument a single input argument ant it's name is formed as follow %<tlist_type>_p where %<tlist_type> stands for the first entry of the tlist type component.

The lines function may be used to control the ouput.

Examples

disp([1 2],3)
deff('[]=%t_p(l)','disp(l(3),l(2))')
disp(tlist('t',1,2))

See Also

lines , write , read , print , string , tlist ,


fileinfo

Scilab Function
Last update : 12/01/2004

fileinfo - Provides information about a file

Calling Sequence

[x,ierr]=fileinfo(file)

Parameters

  • file : a character string, the file pathname
  • x : an integer vector of size 6 containing information or an empty matrix if file does not exist.
  • ierr : error indicator, 0, if no error has occured

Description

x=fileinfo(file) returns

x(1): The file size
x(2): The file mode
x(3): The user id
x(4): the group id
x(5): The device number
x(6): The date of last modification
x(7): The date of last change
x(8): The date of last access
x(9): The device type (if inode device)
x(10): The blocksize for filesystem I/O
x(11): The number of blocks allocated
x(12): The inode
x(13): The number of hard links

Reference

This function is an interface to the C function stat.

Examples

w=fileinfo(SCI+'/scilab.star')
getdate(w(6))

See Also

getdate , file , dispfiles , newest , isdir ,

Author

S. Steer INRIA


fileparts

Scilab Function
Last update : 28/07/2004

fileparts - returns the path, filename and extension for a file path

Calling Sequence

[path,fname,extension]=fileparts(fullpath)
v=fileparts(fullpath,sel)

Parameters

  • fullpath : a character string, the given file path
  • sel : a optional character string selector, with posible values: 'path' 'fname' or 'extension'
  • path : a character string, the path of the directory pointed to by fullpath
  • fname : a character string, the filename part is any or ''
  • extension : a character string, the extension part is any or ''
  • value : a character string, depending on sel value

Description

[path,fname,extension]=fileparts(fullpath) splits the fullpath character string in its three parts: the path of the directory pointed to, the filename part, the extension part including the dot.

Examples

   [path,fname,extension]=fileparts('SCI/scilab.star')
   fileparts('SCI/scilab.star','extension')

See Also

pathconvert , basename , fullfile ,

Author

Serge Steer, INRIA


file

Scilab Function
Last update : 20/04/2004

file - file management

Calling Sequence

[unit [,err]]=file('open', file-name [,status] [,access [,recl]] [,format])
file(action,unit)
[units [,typ [,nams [,mod [,swap]]]]] = file([unit])

Parameters

  • file-name : string, file name of the file to be opened
  • status : string, The status of the file to be opened
    • "new" : file must not exist new file (default)
    • "old" : file must already exists.
    • "unknown" : unknown status
    • "scratch" : file is to be deleted at end of session
  • access : string, The type of access to the file
    • "sequential" : sequential access (default)
    • "direct" : direct access.
  • format : string,
    • "formatted" : for a formatted file (default)
    • "unformatted" : binary record.
  • recl : integer,is the size of records in bytes when access="direct"
  • unit : integer, logical unit descriptor of the opened file
  • units : integer vector, logical unit descriptor of the opened files. Units 1 5 and 6 are reserved by the system for history file , input and output devices.
  • typs : Character string vector, type (C or Fortran) of opened files.
  • nams : Character string vector, pathnames of opened files.
  • mod : file opening mode. Formed by three digits abc
    • Fortran files
      • a : 0 stands for formatted and 1 for unformatted (binary)
      • b 0 stands for sequential acces and 1 for direct access
      • c : 0 stands for "new", 1 for "old", 2 for "scratch" and 3 for "unknown"
    • C files
      • a : is 1 if file has been opened with a "b" (binary) mode
      • b : is 1 if file has been opened with a "+" (updating) mode
      • c : 1 stands for "r" (read), 2 stands for "w" (write) and 3 for "a" (append)
  • swap : automatic swap switch. swap=1 if automatic swap is on. swap is always 0 for Fortran files.
  • err : integer, error message number (see error), if open fails. If err is omitted an error message is issued.
  • action : is one of the following strings:
    • "close" : closes the file(s) given by the logical unit descriptors given in units
    • "rewind" : puts the pointer at beginning of file
    • "backspace" : puts the pointer at beginning of last record.
    • "last" : puts the pointer after last record.

Description

selects a logical unit unit and manages the file file-name .

[unit [,err]]=file('open', file-name [,status] [,access [,recl]] [,format]) allows to open a file with specified properties and to get the associated unit number unit . This unit number may be used for further actions on this file or as file descriptor in read , write , readb , writb , save , load function calls.

file(action,unit) allows to close the file , or move the current file pointer .

file() returns the logical unit descriptors of the opened files. So file('close',file() ) closes all user opened files (C or Fortran type).

Examples

u=file('open',TMPDIR+'/foo','unknown')
for k=1:4
  a=rand(1,4)
  write(u,a)
end
file('rewind',u)
x=read(u,2,4)
file('close',u)
//
u1=file('open',TMPDIR+'/foo','unknown')
u2=mopen(TMPDIR+'/foo1','wb')
[units,typs,nams]=file()
file('close',u1);
mclose(u2);

See Also

save , load , write , read , writb , readb , xgetfile , mopen , mclose ,


fprintf

Scilab Function
Last update : 15/06/2005

fprintf - Emulator of C language fprintf function

Calling Sequence

fprintf(file,format,value_1,..,value_n)

Parameters

  • format : a Scilab string. Specifies a character string combining literal characters with conversion specifications.
  • value_i : Specifies the data to be converted according to the format parameter.
  • str : column vector of character strings
  • file : a Scilab string specifying a file name or a logical unit number (see file )

Description

Obsolete function, use preferabily the mfprintf function which is much more compatible with the C fprintf functionalities.

The fprintf function converts, formats, and writes its value parameters, under control of the format parameter, to the file specified by its file parameter.

The format parameter is a character string that contains two types of objects:

Literal characters: which are copied to the output stream.
Conversion specifications: each of which causes zero or more items to be fetched from the value parameter list. see printf_conversion for details

If any value s remain after the entire format has been processed, they are ignored.

Examples

u=file('open','results','unknown') //open the result file
t=0:0.1:2*%pi;
for tk=t
 fprintf(u,'time = %6.3f value = %6.3f',tk,sin(tk)) // write a line
end
file('close',u) //close the result file

See Also

mfprintf , string , print , write , format , disp , file , printf , sprintf ,


fprintfMat

Scilab Function
Last update : 01/04/2004

fprintfMat - print a matrix in a file.

Calling Sequence

fprintfMat(fil,M [,format,text])

Parameters

  • fil : a string, the pathname of the file to be scanned.
  • M : A matrix of real numbers.
  • format : a character string, a C like format. This is an optional parameter, the default value is "%f"
  • text : a string matrix giving non numerical comments stored at the beginning of the file.

Description

The fprintfMat function prints a matrix in a formated file. Each row of the matrix give a line in the file. If text is given then the elements of text are inserted columnwise at the beginning of the file one element per line.

Examples

n=50;
a=rand(n,n,'u');
fprintfMat(TMPDIR+'/Mat',a,'%5.2f');
a1=fscanfMat(TMPDIR+'/Mat');

See Also

mclose , meof , mfprintf , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


fscanf

Scilab Function
Last update : 12/01/2004

fscanf - Converts formatted input read on a file

Calling Sequence

[v_1,...v_n]=fscanf (file,format)

Parameters

  • format :Specifies the format conversion.
  • file :Specifies the input file name or file number.

Description

The fscanf functions read character data on the file specified by the file argument , interpret it according to a format, and returns the converted results.

The format parameter contains conversion specifications used to interpret the input.

The format parameter can contain white-space characters (blanks, tabs, newline, or formfeed) that, except in the following two cases, read the input up to the next nonwhite-space character. Unless there is a match in the control string, trailing white space (including a newline character) is not read.

-Any character except % (percent sign), which must match the next character of the input stream.
-A conversion specification that directs the conversion of the next input field. see scanf_conversion for details.

See Also

printf , read , scanf , sscanf , mfscanf ,


fscanfMat

Scilab Function
Last update : 01/04/2004

fscanfMat - Reads a Matrix from a text file.

Calling Sequence

M=fscanfMat(filename);
[M,text]=fscanfMat(filename);

Parameters

  • filename : a character string giving the name of the file to be scanned.
  • M : Output variable. A matrix of real numbers.
  • text : Output variable. A string matrix.

Description

The fscanfMat function is used to read a scalar matrix from a text file. The first non-numeric lines of the file are returned in text if requested and all the remaining lines must have the same number of columns (column separator are assumed to be white spaces or tab characters). The number of columns of the matrix will follow the number of columns found in the file and the number of lines is fetched by detecting eof in the input file. This function can be used to read back numerical data saved with the fprintfMat .

Examples

fd=mopen(TMPDIR+'/Mat','w');
mfprintf(fd,'Some text.....\n');
mfprintf(fd,'Some text again\n');
a=rand(6,6);
for i=1:6 ,
 for j=1:6, mfprintf(fd,'%5.2f ',a(i,j));end;
 mfprintf(fd,'\n');
end
mclose(fd);
a1=fscanfMat(TMPDIR+'/Mat')

See Also

mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


fullfile

Scilab Function
Last update : 28/07/2004

fullfile - Construit un nom de fichier complet

Calling Sequence

f = fullfile(varargin)

Parameters

  • varargin : tous les répertoires et le nom de fichier utilisés pour créer le nom de fichier complet (au moins un répertoire et un nom de fichier)
  • f : nom de fichier complet

Description

f = fullfile(varargin) construit un nom de fichier complet en prenant en compte la plateforme actuelle et en gérant les cas où les noms de répertoires commencent ou finissent par un séparateur de répertoire.

Examples

   f=fullfile("/home/","\scilab","macros","\util","fullfile.sci")
   f=fullfile("C:","\scilab","macros","\util","fullfile.sci")

See Also

pathconvert , fileparts ,

Authors

V.C.


getio

Scilab Function
Last update : 12/01/2004

getio - get Scilab input/output logical units

Calling Sequence

ios=getio()

Parameters

  • ios : a vector [rio rte wio wte]
    • rio : current logical unit for reading instructions
    • rte : logical unit assigned for input in main scilab window
    • wio : logical unit relative to the diary file if any. wio=0 stands for no diary file opened
    • wte : logical unit assigned for output in main scilab window

Description

getio returns logical units assigned for main scilab input and output

See Also

file , exec ,


input

Scilab Function
Last update : 15/12/2003

input - prompt for user input

Calling Sequence

[x]=input(message,["string"])

Parameters

  • message : character string
  • "string" : the character string "string" (may be abbreviated to "s" )
  • x : real number (or character string if "string" is in the calling sequence)

Description

input(message) gives the user the prompt in the text string and then waits for input from the keyboard. The input can be expression which is evaluated by evstr . If nothing but a carriage return is entered at the prompt input(message) returns an empty matrix

Invoked with two arguments, the output is a character string which is the expression entered at keyboard. If nothing but a carriage return is entered at the prompt input(message) returns an empty string

Examples

//x=input("How many iterations?")
//x=input("What is your name?","string")

See Also

evstr , x_dialog , x_mdialog ,


isdir

Scilab Function
Last update : 12/01/2004

isdir - checks if argument is a directory path

Calling Sequence

r=isdir(path)

Parameters

  • path : a character string, the file pathname
  • r : a boolean, true if path is a path to a directory.

Description

r=isdir(path) checks if path is a path to a directory.

Reference

This function is based on the C function stat. The SCI and ~ shortcuts for Scilab directory and home directory are handled.

Examples

isdir(TMPDIR)
isdir SCI/scilab.star

See Also

fileinfo ,

Author

S. Steer INRIA


lines

Scilab Function
Last update : 12/01/2004

lines - rows and columns used for display

Calling Sequence

lines([nl [,nc]])
ncl=lines()

Parameters

  • nl : an integer, the number of lines for vertical paging control. If 0 no vertical paging control is done.
  • nc : an integer, the number of column of output. Used for formatting output
  • ncl : a 1x2 vector [nc,nl]

Description

lines handles Scilab display paging.

lines() returns the vector [# columns, # rows] currently used by Scilab for displaying the results.

lines(nl) sets the number of displayed lines (before user is asked for more) to nl .

lines(0) disables vertical paging

lines(nl,nc) changes also the size of the output to nc columns.

When Scilab is launched without -nw option, the lines parameters are automatically set according to the output window size, these parameters are also automaticaly modified when the window is resized.

See Also

disp , print ,


listvarinfile

Scilab Function
Last update : 27/09/2005

listvarinfile - list the contents of a saved data file

Calling Sequence

listvarinfile(filename)
[nams,typs,dims,vols]=listvarinfile(filename)

Parameters

  • filename : character string, the pathname of the file to be inspected
  • nams : character array, names of the variables saved in the file
  • dims : list, dimensions of the variables saved in the file
  • typs : numeric array, types of the variables saved in the file
  • vols : numeric array, size in bytes of the variables saved in the file

Description

This utility function lists "a la whos " the variables contained in a Scilab data file produced by save .

Remark: hypermatrices are reported as plain mlists; rationals and state-spaces are reported as plain tlists; graphic handles are not recognized.

Examples

   a=eye(2,2); b=int16(ones(a)); c=rand(2,3,3);
   save("vals.dat",a,b,c)
   listvarinfile("vals.dat")

See Also

whos , save , load , save_format , type ,

Authors

Serge Steer 31 Jan 2001; reediting by Enrico Segre


loadmatfile

Scilab Function
Last update : 09/03/2005

loadmatfile - loads a Matlab V6 MAT-file (binary or ASCII) into Scilab

Calling Sequence

loadmatfile(format,filename[,var1[,var2[,...]]])
loadmatfile(filename[,format[,var1[,var2[,...]]]])
loadmatfile(filename[,var1[,var2,[,...[,format]]]])

Parameters

  • filename : character string containing the path of the file (needed)
  • format : file format (if not given and file has extension ".mat", file is considered to be binary)
    • "-mat" : binary file
    • "-ascii" : option to force Scilab to read file as an ASCII file
  • var1, var2 : character strings containing the name of the variables to load (only for binary files)

Description

loads a Matlab MAT-file into Scilab. The Matlab data types are converted into the Scilab equivalents.

See Also

load , savematfile , save , mfile2sci , matfile2sci ,

Authors

Serge Steer (INRIA)
V.C

Bibliography

This function has been developped following the "MAT-File Format" description: www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/matfile_format.pdf


load

Scilab Function
Last update : 27/09/2005

load - load saved variable

Calling Sequence

load(filename [,x1,...,xn])
load(fd [,x1,...,xn])

Parameters

  • filename : character string containing the path of the file
  • fd : a file descriptor given by a call to mopen
  • xi : arbitrary Scilab variable name(s) given as strings.

Description

The load command can be used to reload in the Scilab session variables previously saved in a file with the save command. If the file contains graphic handle variables, the corresponding graphics_entities are drawn.

load(filename) loads the variables saved in file given by its path filename .

load(fd) loads the variables saved in file given by its descriptor fd .

load(filename,'x','y') or load(fd,'x','y') loads only variables x,y .

Even if the binary file format has changed with 2.5 version, load(filename,...) is able to read old format files. Previous file format can be accessed for a while using function oldsave ans oldload.

Examples

a=eye(2,2);b=ones(a);
save('vals.dat',a,b);
clear a
clear b
load('vals.dat','a','b');

See Also

save , listvarinfile , save_format , getf , mopen ,


ls

Scilab Function
Last update : 23/06/2004

ls - show files

Calling Sequence

ls path options
files=ls( [path) [,options])

Parameters

  • path : a string matrix giving a directory pathname (eventually ended by a pattern built with * ). Default value is .
  • options : a sequence of strings which can be added under Unix systems: the Unix ls command options. (default value '-C' ).
  • files : a string column vector. By default it contains a column formatted output. if one of the option is '-1' . files contains an entry for each files

Description

ls can be used to list the files which match the patterns given by the path argument. Patterns are given to the unix ls or to the windows dir commands in order to get information on files. Thus in order to write portable Scilab script valid wildcard patterns for both os are to be given. Note that Pathname conversion is performed and for example SCI/macros/util/*.sci is a valid pattern for both unix and windows.

Under Unix systems it is possible to add options to rule the output (see the unix manual about the ls command)

If you want to get a vector of all files matching a pattern use preferabily the listfiles or the dir function.

Examples

    ls
    ls SCI/macros/util/*.sci
    x=ls('SCI/macros/util/f*.sci')

See Also

listfiles , dir , fileinfo ,


manedit

Scilab Function
Last update : 18/05/2005

manedit - editing a manual item

Calling Sequence

manedit(manitem)

Parameters

  • manitem : character string (usually, name of a function)

Description

edit(manitem) opens the xml file associated to manitem in the scipad editor.

If there is no xml file associated with manitem and manitem is the name of a Scilab function scipad opens with the skeleton of the xml file produced by help_skeleton . This file is located in TMPDIR.

Examples

manedit('manedit')

function [x,y,z]=foo123(a,b),
x=a+b,y=a-b,z=a==b
endfunction
manedit foo123

See Also

help , help_skeleton ,


matfile2sci

Scilab Function
Last update : 16/06/2004

matfile2sci - convertit un fichier Matlab .mat en un fichier binaire Scilab

Calling Sequence

matfile2sci(mat_file_path,sci_file_path)

Parameters

  • mat_file_path : Chaîne de caractères contenant le chemin du fichier d'entrée
  • sci_file_path : Chaîne de caractères contenant le chemin du fichier résultant

Description

convertit un fichier Matlab .mat en un fichier binaire compatible avec la fonction load . Les types de données Matlab sont convertis en leur équivalent Scilab.

See Also

loadmatfile , load , mfile2sci ,

Author

Serge Steer (INRIA)

Bibliography

Cette fonction a été développée en suivant le document "MAT-File Format": www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/matfile_format.pdf


mclearerr

Scilab Function
Last update : 12/01/2004

mclearerr - reset binary file access errors

Calling Sequence

mclearerr([fd])

Parameters

  • fd : scalar. The fd parameter returned by the function mopen . -1 stands for last opened file. Default value is -1.

Description

The function clearerr is used to resets the error indicator and EOF indicator to zero.

See Also

merror , mclose , mopen , mput , mget , mgetstr , mputstr , meof , mseek , mtell ,


mclose

Scilab Function
Last update : 01/04/2004

mclose - close an opened file

Calling Sequence

err=mclose([fd])
mclose('all')

Parameters

  • fd : scalar. The fd parameter returned by the function mopen is used as a file descriptor (it's a positive integer).
  • err : a scalar. Error indicator : vector

Description

mclose must be used to close a file opened by mopen . If fd is omitted mclose closes the last opend file.

mclose('all') closes all files opened by file('open',..) or mopen

See Also

meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , file , mdelete ,


mdelete

Scilab Function
Last update : 01/04/2004

mdelete - Delete file(s)

Calling Sequence

mdelete(filename)

Parameters

  • filename : a character string. The pathname of the file(s) to delete.

Description

mdelete may be used to delete a file or a set of files if filename contains meta-charaters.

Note that mdelete does not ask for confirmation when you enter the delete command. To avoid accidentally losing files, make sure that you have accurately specified the items you want deleted.

See Also

mopen , mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell ,


meof

Scilab Function
Last update : 01/04/2004

meof - check if end of file has been reached

Calling Sequence

err=meof(fd)

Parameters

  • fd : scalar. The fd parameter returned by the function mopen . -1 stands for last opened file. Default value is -1.
  • err : scalar. Error indicator

Description

The function meof will return a non null value if end of file has been reached in a previous call to mget or mgetstr . The function clearerr is used to reset the error flag and EOF flag to zero.

See Also

mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


merror

Scilab Function
Last update : 12/01/2004

merror - tests the file access errors indicator

Calling Sequence

merror([fd])

Parameters

  • fd : scalar. The fd parameter returned by the function mopen . -1 stands for last opened file. Default value is -1.

Description

The function merror is used to tests the file access errors indicator. returning non-zero if it is set. The error indicator can only be reset by the mclearerr function.

See Also

mclearerr , mclose , mopen , mput , mget , mgetstr , mputstr , meof , mseek , mtell ,


mscanfmfscanfmsscanf

Scilab Function
Last update : 07/04/2006

mscanf - interface to the C scanf function

mfscanf - interface to the C fscanf function

msscanf - interface to the C sscanf function

Calling Sequence

[n,v_1,...v_n]=mfscanf([niter,]fd,format)
L=mfscanf([niter,] fd,format)
[n,v_1,...v_n]=mscanf([niter,] format)
L=mscanf([niter,]format)
[n,v_1,...v_m]=msscanf([niter,]str,format)
L=msscanf([niter,] str,format)

Parameters

  • format : a Scilab string describing the format to use to write the remaining operands. The format operand follows, as close as possible, the C printf format operand syntax.
  • fd :The fd parameter returned by the function mopen is used as a file descriptor (it's a positive integer). The value -1 refers to the last opened file.
  • str : a Scilab string or string vector.
  • niter : an integer, the number of times the format as to be used.
  • n : an integer, the number of data read or -1 if EOL has been encountered before any datum has been read.
  • v_i : Each function reads characters, interprets them according to a format, and stores the results in its output arguments. If more than $n$ output arguments are provided, the last ones v_n+1,...v_m are set to empty matrices.
  • L : if all data are homogeneous they are stored in a unique vector which is returned, otherwise subsequences of same data type are stored in matrices and an mlist (with type cblock ) containing all the built matrices is returned.

Description

The mfscanf function reads characters from the stream fd .

The mscanf function reads characters from Scilab window.

The msscanf function reads characters from the Scilab string str .

The niter optional argument specifies how many time the format has to used. One iteration produces one line in the output matrix. If niter==-1 the function iterates up to the end of file. The niter default value is 1.

Examples

    //--    Simple use                                        --
    //----------------------------------------------------------
    s='1 1.3'  //a string
    [n,a,b]=msscanf(s,"%i %e")
    L=msscanf(s,"%i %e")

    //--    Formats samples                                   --
    //----------------------------------------------------------

    msscanf(" 12\n",'%c%c%c%c') //scan characters

    msscanf('0xabc','%x') //scan with hexadecimal format

    msscanf('012345abczoo','%[0-9abc]%s')  //[] notation

    // reading float and double
    msscanf('4345.988','%g')-4345.988 // scan as float
    msscanf('4345.988','%lg')-4345.988 // scan as double

    //--    scanning multi-line data files                    --
    //----------------------------------------------------------
    //create a file with data
    u=mopen(TMPDIR+'/foo','w');
    t=(0:0.1:%pi)';mfprintf(u,"%6.3f %6.3f\n",t,sin(t))
    mclose(u);

    u=mopen(TMPDIR+'/foo','r'); // open the file for reading
    //read the file line by line
    [n,a,b]=mfscanf(u,'%e %e') //first line using mutiple LHS syntax
    l=mfscanf(u,'%e %e')       //second one using single LHS syntax
    //use niter to read 5 more lines
    l=mfscanf(5,u,'%e %e')

    //use niter=-1 to read up to the end of file
    l=mfscanf(-1,u,'%e %e')

    mclose(u); //close the file

    //--    scanning multi-line  strings vectors              --
    //----------------------------------------------------------

    //use niter to scan a string vector
    [n,Names,Ages]=msscanf(-1,["Alain 19";"Pierre 15";"Tom 12"],'%s %d')
    D=msscanf(-1,["Alain 19";"Pierre 15";"Tom 12"],'%s %d')
    typeof(D)
    Names=D(:,1) //strings
    Age=D(:,2)   //numerical values

See Also

mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


mgetl

Scilab Function
Last update : 12/01/2004

mgetl - read lines from an ascii file

Calling Sequence

txt=mgetl(file_desc [,m])

Parameters

  • file_desc :a character string giving the file name or a logical unit returned by mopen
  • m : an integer scalar. Default value is -1.
  • txt : a column vector of string

Description

mgetl function allows to read a lines from an ascii file.

If m is omitted or is -1 all lines till end of file occurs are read.

If m is given mgetl tries to read exactly m lines. This option is useful to sequentialy read part of a file. In this case if an end of file (EOF) occurs before m lines are read the read lines are returned (it is possible to check if EOF had occured using the meof function) issued.

mgetl allows to read files coming from Unix, Windows, or Mac operating systems.

Examples

mgetl('SCI/scilab.star',5)

mgetl SCI/macros/elem/erf.sci

fd=mopen('SCI/scilab.star','r')
mgetl(fd,10)
mclose(fd)

See Also

mputl , mclose , mfscanf , mget , mgetstr , mopen , read ,

Author

S. Steer


mgetstr

Scilab Function
Last update : 01/04/2004

mgetstr - read a character string

Calling Sequence

str=mgetstr(n [,fd] )

Parameters

  • n :a positive scalar: The number of character to read.
  • fd : scalar. The fd parameter returned by the function mopen . -1 stands for last opened file. Default value is -1.
  • str : a character string

Description

mgetstr function allows to read a character string in a binary file. If EOF is reached before read completion only the properly read values will be returned.

See Also

mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


mgetmgeti

Scilab Function
Last update : 28/06/2006

mget - reads byte or word in a given binary format and convert to double

mgeti - reads byte or word in a given binary format return an int type

Calling Sequence

x=mget([n,type,fd])
x=mgeti([n,type,fd])

Parameters

  • n :a positive scalar: The number of items to be read.
  • fd : scalar. The fd parameter returned by the function mopen . -1 stands for last opened file. Default value is -1.
  • type : a string. Give the binary format used to write all the entries of x.
  • x : a vector of floating point or integer type numbers

Description

The mget function reads data in the input specified by the stream parameter fd and returns a vector of floating point data. The mgeti function reads data in the input specified by the stream parameter fd and returns a vector of integer data.

Data is read at the position at which the file pointer is currently pointing and advances the indicator appropriately.

The type parameter is a conversion specifier which may be set to any of the following flag characters (with default value "l"):

WARNING, when reading binary files under Windows to not forget to open the file with the b option like fd1=mopen(file1,'rb') if not the file will be interpreted as text file and the bytes with value 13 will be interpreted as newlines and ommitted.

"l", "i", "s", "ul", "ui", "us", "d", "f", "c", "uc": for reading respectively a long, an int, a short, an unsigned long, an unsigned int, an unsigned short, a double, a float, a char and an unsigned char. The bytes which are read are automatically swapped if necessary (by checking little-endian status). This default swapping mode can be suppressed by adding a flag in the mopen function. Format "l", "d" and "f" are valid only with the mget function.
"..l" or "..b": It is also possible to read in little-endian or big-endian mode by adding a 'l' or 'b' character at the end of a type specification. For example "db" will read a double in big-endian mode.

Examples

    file1 = 'test1.bin';
    file2 = 'test2.bin';
    fd1=mopen(file1,'wb');
    fd2=mopen(file2,'wb');
    mput(1996,'ull',fd1);
    mput(1996,'ull',fd2);
    mclose(fd1);
    mclose(fd2);

    fd1=mopen(file1,'rb');
    if 1996<>mget(1,'ull',fd1) ;write(%io(2),'Bug');end;
    fd2=mopen(file2,'rb');
    if 1996<>mget(1,'ull',fd2) ;write(%io(2),'Bug');end;
    mclose(fd1);
    mclose(fd2);

See Also

mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


mopen

Scilab Function
Last update : 01/04/2004

mopen - open a file

Calling Sequence

[fd,err]=mopen(file [, mode, swap ])

Parameters

  • file : a character string. The pathname of the file to open.
  • mode : a character string that controls whether the file is opened for reading (r), writing (w), or appending (a) and whether the file is opened for updating (+). The mode can also include a b parameter to indicate a binary file.
  • swap : a scalar. If swap is present and swap=0 then automatic bytes swap is disabled.
  • err : a scalar. Error indicator
  • fd : scalar. The fd parameter returned by the function mopen is used as a file descriptor (it's a positive integer).

Description

mopen may be used to open a file in a way compatible with the C fopen procedure. Without swap argument the file is supposed to be coded in "little endian IEEE format" and data are swaped if necessary to match the IEEE format of the processor.

The mode parameter controls the access allowed to the stream. The parameter can have one of the following values. In this list of values, the b character indicates a binary file

r or rb: Opens the file for reading.
w or wb: Creates a new file for writing, or opens and truncates a file to zero length.
a or ab: Appends (opens a file for writing at the end of the file, or creates a file for writing).
r+ or r+b: Opens a file for update (reading and writing).
w+ or w+b: Truncates to zero length or creates a file for update.
a+ or a+b:Appends (opens a file for update, writing at the end of the file, or creates a file for writing).

When you open a file for update, you can perform both input and output operations on the resulting stream. However, an output operation cannot be directly followed by an input operation without a file-positioning operation (mseek() function). Also, an input operation cannot be directly followed by an output operation without an intervening file positioning operation, unless the input operation encounters the end of the file.

When you open a file for append (that is, when the mode parameter is a or a+), it is impossible to overwrite information already in the file. You can use the fseek() function to reposition the file pointer to any position in the file, but when output is written to the file, the current file pointer is ignored. All output is written at the end of the file and the file pointer is repositioned to the end of the output.

To open files in a way compatible with Fortran like functions use function file .

See Also

mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


mfprintfmprintfmsprintf

Scilab Function
Last update : 01/04/2004

mfprintf - converts, formats, and writes data to a file

mprintf - converts, formats, and writes data to the main scilab window

msprintf - converts, formats, and writes data in a string

Calling Sequence

mfprintf(fd,format,a1,...,an);
mprintf(format,a1,...,an);
str=msprintf(format,a1,...,an);

Parameters

  • fd : scalar, file descriptor given by mopen (it's a positive integer). The value -1 refers to the default file ( i.e the last opened file).
  • format : a Scilab string describing the format to use to write the remaining operands. The format operand follows, as close as possible, the C printf format operand syntax.
  • str : a character string, string to be scanned.
  • a1,...,an : Specifies the data to be converted and printed according to the format parameter.

Description

The mprintf , mfprintf , and msprintf functions are interface for C-coded version of printf , fprintf and sprintf functions.

The mprintf function writes formatted operands to the standard Scilab output (i.e the Scilab window). The argument operands are formatted under control of the format operand.

The mfprintf function writes formatted operands to the file specified by the file desciptor fd . The argument operands are formatted under control of the format operand.

The msprintf writes formatted operands in its returned value (a Scilab string). The argument operands are formatted under control of the format operand. Note that, in this case, the escape sequences ( "\n, \t,.." ) are treated as a normal sequence of characters.

All these functions may be used to output column vectors of numbers and string vectors without an explicit loop on the elements. In that case these functions iterates on the rows. The shortest vector gives the number of time the format has to be iterated.

An homogeneous sequence of identical type parameters can be replaced by a matrix

Examples

mprintf('At iteration %i, Result is:\nalpha=%f',33,0.535)

msprintf('%5.3f %5.3f',123,0.732)
msprintf('%5.3f\n%5.3f',123,0.732)

A=rand(5,2);
// vectorized forms: the format directive needs
// two operand, each column of A is used as an operand.
// and the mprintf function is applied on each row of A
mprintf('%5.3f\t%5.3f\n',A)

colors=['red';'green';'blue';'pink';'black'];
RGB=[1 0 0;0 1 0;0 0 1;1 0.75 0.75;0 0 0];
mprintf('%d\t%s\t%f\t%f\t%f\n',(1:5)',colors,RGB)

See Also

mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


mputl

Scilab Function
Last update : 12/01/2004

mputl - writes strings in an ascii file

Calling Sequence

mputl(txt [,file_desc])

Parameters

  • file_desc :a character string giving the file name or a logical unit returned by mopen. If omitted lines are written in the last file opened by mopen.
  • txt : a vector of strings.

Description

mputl function allows to write a vector of strings as a sequence of lines in an ascii file.

See Also

mputl , mclose , mfprintf , mput , mputstr , mopen , write ,

Author

S. Steer


mputstr

Scilab Function
Last update : 01/04/2004

mputstr - write a character string in a file

Calling Sequence

mputstr(str [, fd]);

Parameters

  • fd : scalar. The fd parameter returned by the function mopen . -1 stands for last opened file. Default value is -1.
  • str : a character string

Description

mputstr function allows to write a character string in a binary file.

See Also

mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


mput

Scilab Function
Last update : 01/04/2004

mput - writes byte or word in a given binary format

Calling Sequence

mput(x [,type,fd])

Parameters

  • x : a vector of floating point or integer type numbers
  • fd : scalar. The fd parameter returned by the function. Default value is -1 which stands for the last ( mopen ) opened file.
  • type : a string. Give the binary format used to write all the entries of x.

Description

The mput function writes data to the output specified by the stream parameter fd . Data is written at the position at which the file pointer is currently pointing and advances the indicator appropriately.

The type parameter is a conversion specifier which may be set to any of the following flag characters (with default value "l"):

"l","i","s","ul","ui","us","d","f","c","uc": for writing respectively a long, an int, a short, an unsigned long, an unsigned int, an unsigned short, a double, a float, a char and an unsigned char. The bytes which are wrote are automatically swapped if necessary (by checking little-endian status) in order to produce machine independent binary files ( in little-endian mode). This default swapping mode can be suppressed by adding a flag in the mopen function.
"..l" or "..b": It is also possible to write in little-endian or big-endian mode by adding a 'l' or 'b' character at the end of a type specification. For example "db" will write a double in big-endian mode.

Examples

  filen = 'test.bin';
  mopen(filen,'wb');
  mput(1996,'l');mput(1996,'i');mput(1996,'s');mput(98,'c');
// force little-endian
  mput(1996,'ll');mput(1996,'il');mput(1996,'sl');mput(98,'cl');
// force big-endian
  mput(1996,'lb');mput(1996,'ib');mput(1996,'sb');mput(98,'cb');
//
  mclose();
  mopen(filen,'rb');
  if 1996<>mget(1,'l') then pause,end
  if 1996<>mget(1,'i') then pause,end
  if 1996<>mget(1,'s') then pause,end
  if   98<>mget(1,'c') then pause,end
  // force little-endian
  if 1996<>mget(1,'ll') then pause,end
  if 1996<>mget(1,'il') then pause,end
  if 1996<>mget(1,'sl') then pause,end
  if   98<>mget(1,'cl') then pause,end
  // force big-endian
  if 1996<>mget(1,'lb') then pause,end
  if 1996<>mget(1,'ib') then pause,end
  if 1996<>mget(1,'sb') then pause,end
  if   98<>mget(1,'cb') then pause,end
  //
  mclose();

See Also

mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


mseek

Scilab Function
Last update : 01/04/2004

mseek - set current position in binary file.

Calling Sequence

mseek(n [,fd, flag])

Parameters

  • n :a positive scalar: The offset from origin in number of bytes.
  • fd : scalar. The fd parameter returned by the function mopen . -1 stands for last opened file. Default value is -1.
  • flag : a string. specifies the origin. Default value 'set'.

Description

The function mseek() sets the position of the next input or output operation on the stream fd . The new position is at the signed distance given by n bytes from the beginning, from the current position, or from the end of the file, according to the flag value which can be 'set' , 'cur' or 'end' .

mseek() allows the file position indicator to be set beyond the end of the existing data in the file. If data is later written at this point, subsequent reads of data in the gap will return zero until data is actually written into the gap. mseek() , by itself, does not extend the size of the file.

Examples

file3='test3.bin'
fd1= mopen(file3,'wb');
for i=1:10, mput(i,'d'); end
mseek(0);
mput(678,'d');
mseek(0,fd1,'end');
mput(932,'d');
mclose(fd1)
fd1= mopen(file3,'rb');
res=mget(11,'d')
res1=[1:11]; res1(1)=678;res1($)=932;
if res1<>res ;write(%io(2),'Bug');end;
mseek(0,fd1,'set');
// trying to read more than stored data
res1=mget(100,'d',fd1);
if res1<>res ;write(%io(2),'Bug');end;
meof(fd1)
mclearerr(fd1)
mclose(fd1);

See Also

mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


mtell

Scilab Function
Last update : 01/04/2004

mtell - binary file management

Calling Sequence

mtell([fd])

Parameters

  • fd : scalar. The fd parameter returned by the function mopen . -1 stands for last opened file. Default value is -1.

Description

The function mtell() returns the offset of the current byte relative to the beginning of the file associated with the named stream fd .

See Also

mclose , meof , mfprintf , fprintfMat , mfscanf , fscanfMat , mget , mgetstr , mopen , mprintf , mput , mputstr , mscanf , mseek , mtell , mdelete ,


newest

Scilab Function
Last update : 12/01/2004

newest - returns newest file of a set of files

Calling Sequence

k=newest(paths)
k=newest(path1,path2,...,pathn)

Parameters

  • k : the index of the newest file
  • paths : a character string vector (or list), paths(i) is the pathname of ith file
  • pathi : a character string, the pathname of ith file

Description

Given a set of pathnames newest returns the index of the newest one. Non existant files are supposed to be the oldest.

Examples

newest('SCI/macros/xdess/bode.sci','SCI/macros/xdess/bode.bin')
newest('SCI/macros/xdess/bode.'+['sci','bin'])

See Also

fileinfo ,


oldload

Scilab Function
Last update : 12/01/2004

oldload - load saved variable in 2.4.1 and previous formats

Calling Sequence

oldload('file-name' [,x1,...,xn])

Parameters

  • file-name : character string
  • xi : arbitrary Scilab variable name(s) given as strings.

Description

The oldload function is obsolete and is retained only for compatibility purpose.

The oldload command can be used to reload in the Scilab session variables previously saved in a file with the save command.

oldload('file-name') loads the variables saved in file 'file-name' .

oldload('file-name','x','y',...,'z') loads only variables x,y,...,z stored in file 'file-name' .

Examples

a=eye(2,2);b=ones(a);
oldsave(TMPDIR+'/vals.dat',a,b);
clear a
clear b
oldload(TMPDIR+'/vals.dat','a','b');

See Also

save , getf ,


oldsave

Scilab Function
Last update : 12/01/2004

oldsave - saving variables in 2.4.1 and previous format

Calling Sequence

oldsave(filename [,x1,x2,...,xn])

Parameters

  • filename : character string or a logical unit returned by file('open',...)
  • xi : arbitrary Scilab variable(s)

Description

The oldsave function is obsolete and is retained only for compatibility purpose.

The oldsave command can be used to save Scilab current variables in binary form in a file.

oldsave(filename) saves all current variables in the file defined by filename .

oldsave(file-name,x,y) saves only named variables x and y .

Saved variables can be reloaded by the load or oldload command.

Examples

a=eye(2,2);b=ones(a);
oldsave('TMPDIR/val.dat',a,b);
clear a
clear b
oldload('TMPDIR/val.dat','a','b');

See Also

load , file ,


printf_conversion

Scilab Documentation
Last update : 12/01/2004

printf_conversion - printf, sprintf, fprintf conversion specifications

Description

Each conversion specification in the printf , sprintf , fprintf format parameter has the following syntax:

-A % (percent) sign.
-Zero or more options , which modify the meaning of the conversion specification. The following list contains the option characters and their meanings:
-: Left align, within the field, the result of the conversion.
+: Begin the result of a signed conversion with a sign (+ or -).
"space": Prefix a space character to the result if the first character of a signed conversion is not a sign. If both the (space) and + options appear, the (space) option is ignored.
#

: Convert the value to an alternate form. For c , d , i , s , and u conversions, the # option has no effect. For o conversion, # increases the precision to force the first digit of the result to be a 0 (zero). For x and X conversions, a nonzero result has 0x or 0X prefixed to it. For e, E, f, g, and G conversions, the result always contains a decimal point, even if no digits follow it. For g and G conversions, trailing zeros are not removed from the result.

0

: Pad to the field width, using leading zeros (following any indication of sign or base) for d , i , o , u , x , X , e , E , f , g , and G conversions; no space padding is performed. If the 0 and \- (dash) flags both appear, the 0 flag is ignored. For d , i , o u , x , and X conversions, if a precision is specified, the 0 flag is also ignored.

An optional decimal digit string that specifies the minimum field width. If the converted value has fewer characters than the field width, the field is padded on the left to the length specified by the field width. If the left-adjustment option is specified, the field is padded on the right.

An optional precision. The precision is a . (dot) followed by a decimal digit string. If no precision is given, the parameter is treated as 0 (zero). The precision specifies:

-The minimum number of digits to appear for d , u , o , x , or X conversions
-The number of digits to appear after the decimal point for e , E , and f conversions
-The maximum number of significant digits for g and G conversions
-The maximum number of characters to be printed from a string in an s conversion
-A character that indicates the type of conversion to be applied:
%: Performs no conversion. Displays %.
d,i:Accepts an integer value and converts it to signed decimal notation. The precision specifies the minimum number of digits to appear. If the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is a null string. Specifying a field width with a zero as a leading character causes the field width value to be padded with leading zeros.
u:Accepts an integer value and converts it to unsigned decimal notation. The precision specifies the minimum number of digits to appear. If the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is a null string. Specifying a field width with a zero as the leading character causes the field width value to be padded with leading zeros.
o:Accepts an integer value and converts it to unsigned octal notation. The precision specifies the minimum number of digits to appear. If the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is a null string. Specifying a field width with a zero as the leading character causes the field width value to be padded with leading zeros. An octal value for field width is not implied.
x, X:Accepts an integer value and converts it to unsigned hexadecimal notation. The letters ``abcdef'' are used for the x conversion; the letters ``ABCDEF'' are used for the X conversion. The precision specifies the minimum number of digits to appear. If the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is a null string. Specifying a field width with a zero as the leading character causes the field width value to be padded with leading zeros.
f: Accepts a float or double value and converts it to decimal notation in the format %[\-] ddd.ddd . The number of digits after the decimal point is equal to the precision specification.
-If no precision is specified, six digits are output.
-If the precision is zero, no decimal point appears and the system outputs a number rounded to the integer nearest to value .
-If a decimal point is output, at least one digit is output before it.
e, E:Accepts a real and converts it to the exponential form %[\-] d.ddde +/\- dd . There is one digit before the decimal point, and the number of digits after the decimal point is equal to the precision specification.
-If no precision is specified, , six digits are output.
-If the precision is zero, , no decimal point appears.
-The E conversion character produces a number with E instead of e before the exponent. The exponent always contains at least two digits. If the value is zero, the exponent is zero.
g, G: Accepts a real and converts it in the style of the e , E , or f conversion characters, with the precision specifying the number of significant digits. Trailing zeros are removed from the result. A decimal point appears only if it is followed by a digit. The style used depends on the value converted. Style e ( E , if G is the flag used) results only if the exponent resulting from the conversion is less than -4, or if it is greater or equal to the precision.
c:Accepts and displays an integer value converted to a character.
s:Accepts a string value and displays characters from the string to the end or the number of characters indicated by the precision is reached. If no precision is specified, all characters up to the end are displayed.

A field width or precision can be indicated by an * (asterisk) instead of a digit string. In this case, an integer value parameter supplies the field width or precision. The value parameter converted for output is not fetched until the conversion letter is reached, so the parameters specifying field width or precision must appear before the value to be converted (if any).

If the result of a conversion is wider than the field width, the field is expanded to contain the converted result.

The representation of the plus sign depends on whether the + or (space) formatting option is specified.

See Also

printf , fprintf , sprintf ,


printf

Scilab Function
Last update : 12/01/2004

printf - Emulator of C language printf function

Calling Sequence

printf(format,value_1,..,value_n)

Parameters

  • format : a Scilab string. Specifies a character string combining literal characters with conversion specifications.
  • value_i : Specifies the data to be converted according to the format parameter.
  • str : column vector of character strings
  • file : a Scilab string specifying a file name or a logical unit number (see file )

Description

The printf function converts, formats, and writes its value parameters, under control of the format parameter, to the standard output.

The format parameter is a character string that contains two types of objects:

Literal characters: which are copied to the output stream.
Conversion specifications: each of which causes zero or more items to be fetched from the value parameter list. see printf_conversion for details

If any value s remain after the entire format has been processed, they are ignored.

Examples

printf('Result is:\nalpha=%f",0.535)

See Also

string , print , write , format , disp , file , fprintf , sprintf ,


print

Scilab Function
Last update : 12/01/2004

print - prints variables in a file

Calling Sequence

print('file-name',x1,[x2,...xn])

Description

prints xi on file 'file-name' with the current format, i.e. the format used by scilab to display the variables. All types of variables may be " print "'ed

Note : xi must be a named variable, with expressions variable name part of the display is unpredictable.

print(%io(2),...) prints on Scilab's window. this syntax may be used to display variables within a macro.

Examples

a=rand(3,3);p=poly([1,2,3],'s');l=list(1,'asdf',[1 2 3]);
print(%io(2),a,p,l)
write(%io(2),a)

See Also

write , read , format , printf , disp ,


read4b

Scilab Function
Last update : 12/01/2004

read4b - fortran file binary read

Calling Sequence

x=read4b(file-name,m,n [,rec])

Parameters

  • file-name : string or integer
  • m, n : integers (dimensions of the matrix x). Set m=-1 if you do not know the numbers of rows, so all the file is read
  • rec : vector of positive integers. the selected records for direct access. This vector size must be equal to the number of rows of desired x .

Description

binary read of the matrix x in the file file-name . Matrix entries are supposed to have been stored on 4 byte words.

For direct record access, file must have been previously opened using file function to set the record_length. file-name must be the result of the file function.

See Also

file , write , writb , mget , write4b ,


readb

Scilab Function
Last update : 12/01/2004

readb - fortran file binary read

Calling Sequence

x=readb(file-name,m,n [,rec])

Parameters

  • file-name : string or integer
  • m, n : integers (dimensions of the matrix x). Set m=-1 if you do not know the numbers of rows, so all the file is read
  • rec : vector of positive integers. the selected records for direct access. This vector size must be equal to the number of rows of desired x .

Description

binary read of the matrix x in the file file-name . Matrix entries are supposed to have been stored on 8 byte words.

For direct record access, file must have been previously opened using file function to set the record_length. file-name must be the result of the file function.

See Also

file , write , writb , mget , read4b ,


readc_

Scilab Function
Last update : 12/01/2004

readc_ - read a character string

Calling Sequence

[c]=readc_(unit)
[c]=readc_()

Description

readc_ reads a character string. This function allows one to interrupt an exec file without pause ; the exec file stops until carriage return is made.

See Also

read ,


readmps

Scilab Function
Last update : 12/01/2004

readmps - reads a file in MPS format

Calling Sequence

mps= readmps (file-name,bounds [,maxsizes]);

Parameters

  • file-name : character string, path of the MPS file
  • bounds : 2-vector [lowbound,upbound] , default lower ans upper bounds
  • maxsizes : 3-vector [maxm,maxn,maxnza] Maximum number of contraints and variables, maximum number of nonzeros entries in the LP constraint matrix. If omitted readmps reads the file once just to compute these numbers.
  • mps : tlist with following fields
    • irobj : integer (index of the objective row).
    • namec : character string (Name of the objective).
    • nameb : character string (Name of the right hand side).
    • namran : character string (Name of the ranges section).
    • nambnd : character string (Name of the bounds section).
    • name : character string (Name of the LP problem).
    • rownames : character string column vector (Name of the rows). colnames : character string row vector (Name of the columns).
    • rowstat : integer vector, row types:
      • 1 row type is "="
      • 2 : row type is ">="
      • 3 : row type is "<="
      • 4 : objective row
      • 5 : other free row
    • rowcode : real matrix [hdrowcd,lnkrow] with
      • hdrowcd : real vector (Header to the linked list of rows with the same codes).
      • lnkrow : integer vector (Linked list of rows with the same codes).
    • colcode : real matrix [hdcolcd,lnkcol] with
      • hdcolcd : integer vector (Header to the linked list of columns with the same codes).
      • lnkcol : integer vector (Linked list of columns with the same codes).
    • rownmbs : integer vector (Row numbers of nonzeros in columns of matrix A.)
    • colpnts : integer vector (Pointers to the beginning of columns of matrix A).
    • acoeff : real vector (Array of nonzero elements for each column).
    • rhs :real vector ( Right hand side of the linear program).
    • ranges : real vector of constraint ranges.
    • bounds : real matrix [lbounds,ubounds] with
      • ubounds : full column vector of upper bounds
      • lbounds : full column vector of lower bounds
    • stavar : full column vector of variable status
      • 0 :standard (non negative) variable
      • 1 : upper bounded variable
      • 2 : lower bounded variable
      • 3 : lower and upper bounded variable
      • 4 : minus infinity type variable i.e -inf<x<=u
      • 5 : plus infinity type variable i.e l<=x< inf
      • 6 : fixed type variable i.e l=x=u
      • -k : free variable

Description

readmps . Utility function: reads a file containing description of an LP problem given in MPS format. It is an interface with the program rdmps1.f of hopdm (J. Gondzio). For a description of the variables, see the file rdmps1.f.

MPS format is a standard ASCII medium for LP codes. MPS format is described in more detail in Murtagh's book:

Murtagh B. (1981). Advanced Linear Programming, McGrew-Hill, New York, 1981.

Examples

//Let the LP problem:
//objective:
//   min     XONE + 4 YTWO + 9 ZTHREE
//constraints:
//  LIM1:    XONE +   YTWO            < = 5
//  LIM2:    XONE +            ZTHREE > = 10
// MYEQN:         -   YTWO  +  ZTHREE   = 7
//Bounds
//  0 < = XONE < = 4
// -1 < = YTWO < = 1

//Generate MPS file
txt=['NAME          TESTPROB'
     'ROWS'
     ' N  COST'
     ' L  LIM1'
     ' G  LIM2'
     ' E  MYEQN'
     'COLUMNS'
     '    XONE      COST                 1   LIM1                 1'
     '    XONE      LIM2                 1'
     '    YTWO      COST                 4   LIM1                 1'
     '    YTWO      MYEQN               -1'
     '    ZTHREE    COST                 9   LIM2                 1'
     '    ZTHREE    MYEQN                1'
     'RHS'
     '    RHS1      LIM1                 5   LIM2                10'
     '    RHS1      MYEQN                7'
     'BOUNDS'
     ' UP BND1      XONE                 4'
     ' LO BND1      YTWO                -1'
     ' UP BND1      YTWO                 1'
     'ENDATA'];
mputl(txt,TMPDIR+'/test.mps')
//Read the MPS file
P=readmps(TMPDIR+'/test.mps',[0 10^30])
//Convert it to linpro format
LP=mps2linpro(P)
//Solve it with linpro
[x,lagr,f]=linpro(LP(2:$))

See Also

mps2linpro ,


readxls

Scilab Function
Last update : 06/04/2005

readxls - reads an Excel file

Calling Sequence

sheets = readxls(file_path)

Parameters

  • file_path : a character string: the path of the Excel file.
  • sheets : an mlist of type xls , with one field named sheets

Description

Given an Excel file path this function returns an mlist data structure of type xls , with one field named sheets . The sheets field itself contains a list of sheet data structure.

sheet=mlist(['xlssheet','name','text','value'],sheetname,Text,Value) where sheetname is a character string containing the name of the sheet, Text is a matrix of string which contains the cell's strings and Value is a matrix of numberswhich contains the cell's values.

Warning only BIFF8 Excel files (last Excel file version) are handled

Examples

    Sheets = readxls('SCI/demos/excel/t1.xls')
    // some basic operations on Sheets
    typeof(Sheets)
    s1=Sheets(1) //get the first sheet
    typeof(s1)
    s1.value //get the first sheet value field
    s1.text  //get the first sheet text field
    s1(2,:)  //get the 2 row of the sheet
    typeof(s1(2,:))

    editvar s1

See Also

xls_open , xls_read ,

Authors

Pierrick Mode INRIA
Serge Steer INRIA

Used Function

This function is based on the Scilab functions xls_open and xls_read


read

Scilab Function
Last update : 08/11/2004

read - matrices read

Calling Sequence

[x]=read(file-desc,m,n,[format])
[x]=read(file-desc,m,n,k,format)

Parameters

  • file-desc : character string specifying the file name or integer value specifying logical unit (see file).
  • m, n : integers (dimensions of the matrix x). Set m=-1 if you do not know the numbers of rows, so the whole file is read.
  • format : character string, specifies a "Fortran" format. This character string must begin with a right parenthesis and end with a left parenthesis. Formats cannot mix floating point or character edition modes.
  • k : integer or vector of integer

Description

reads row after row the mxn matrix x ( n=1 for character chain) in the file file-desc (string or integer). Each row of the matrix x begin in a new line of file-desc file. Depending on format , a given row of the x matrix may be read from more than one line of file-desc file.

The type of the result will depend on the specified format. If format contains only (d,e,f,g) descriptors the function tries to read numerical data (the result is matrix of real numbers).

If format contains only a descriptors the function tries to read character strings (the result is a character string column vector). In this case n must be equal to 1. Warning: The character strings are truncated when they are longuer than 4093.

Examples for format :

(1x,e10.3,5x,3(f3.0))
(10x,a20)

When format is omitted datas are read using numerical free format: blank, comma and slash may be used as data separators, n*v may be use to represent n occurrences of value n.

A direct access file can be used if using the parameter k which is is the vector of record numbers to be read (one record per row), thus m must be m=prod(size(k)) .

To read on the keyboard use read(%io(1),...) .

Remark

Last line of data files must be terminated by a newline to be taken into account.

Examples

if MSDOS then unix('del foo');
else unix('rm -f foo'); end
A=rand(3,5); write('foo',A);
B=read('foo',3,5)
B=read('foo',-1,5)
read(%io(1),1,1,'(a)')  // waits for user's input

See Also

file , readb , write , x_dialog , mscanf , mfscanf , msscanf , fscanfMat ,


savematfile

Scilab Function
Last update : 28/10/2004

savematfile - write a Matlab MAT-file (binary or ASCII)

Calling Sequence

savematfile('filename')
savematfile('filename', 'var1', 'var2', ...)
savematfile('filename', '-struct', 's')
savematfile('filename', '-struct', 's', 'f1', 'f2', ...)
savematfile(..., 'format')
savematfile filename var1 var2 ...

Parameters

  • filename : character string containing the path of the file (needed)
  • format : data format to use
    • "-mat" : binary MAT-file (default)
    • "-ascii" : 8-bit ASCII format
    • "-ascii" "-double" : 16-bit ASCII format
    • "-ascii" "-tabs" : delimits with tabs
    • "-ascii" "-double" "-tabs" : 16-digit ASCII format, tab delimited
    • "-v4" : A format that MATLAB Version 4 can open
    • "-v6" : A format that MATLAB Version 6 and earlier can open (default)
  • var1, var2 : character strings containing the name of the variables to load (only for binary files)
  • "-struct" "s" : saves all fields of the scalar structure s as individual variables within the file filename.
  • "-struct" "s" "f1" "f2" : saves as individual variables only those structure fields specified (s.f1, s.f2, ...).

Description

saves variables in a Matlab MAT-file from Scilab. The Scilab data types are converted into the Matlab equivalents.

See Also

load , save , loadmatfile , mfile2sci ,

Authors

Serge Steer (INRIA)
V.C

Bibliography

This function has been developped following the "MAT-File Format" description: www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/matfile_format.pdf


save_format

Scilab Data Type
Last update : 29/09/2005

save_format - format of files produced by "save"

Description

Variables are saved by Scilab with the save command in this format:

each variable record is appended consecutively to the file. The variable record begins with 24 bytes holding the variable name in encoded format (see code2str ), where the name is terminated by the value 40.

After that comes the variable type (long integer), then, depending on it, for:

Floating matrices (type 1)

row size m (long integer), column size n (long integer), it (long integer);

data (8*n*m*(it+1) bytes)

Polynomials (type 2) and Size implicit indices (?) (type 129)

row size m (long integer), column size n (long integer), it (long integer);

formal variable name (16 bytes); pointer table (m*n+1 long integers);

data (8*(N-1)*(it+1) bytes, where N is the last entry of the pointer table)

Booleans (type 4)

row size m (long integer), column size n (long integer);

data (4*n*m bytes)

Floating sparse matrices (type 5)

row size m (long integer), column size n (long integer), it (long integer), nel (long integer);

index (4*m+nel bytes);

non-zero values (8*nel*(it+1) bytes)

Boolean sparse matrices (type 6)

row size m (long integer), column size n (long integer), it (long integer), nel (long integer);

index (4*m+nel bytes);

non-zero values (4*nel*(it+1) bytes)

Integer matrices (type 8)

row size m (long integer), column size n (long integer),

integer type (long integer): 1,2,4, or 11,12,14 for signed and unsigned 1,2,4 bytes integers;

data (n*m*(it modulo 10) bytes)

handles (type 9) ??
Strings (type 10)

row size m (long integer), column size n (long integer),

total number of characters nc+1 (long integer);

pointer table (n*m+1 bytes);

data (4*nc bytes)

Uncompiled functions (type 11)

nout (long integer), lhs names (24*nout bytes),

nin (long integer), rhs names (24*nin bytes);

code length N (long integer),

code (4*N bytes)

Compiled functions (type 13)

nout (long integer), lhs names (24*nout bytes),

nin (long integer), rhs names (24*nin bytes);

code length N (long integer),

pseudocode (4*N bytes)

Libraries (type 14)

path length np (long integer), path name (4*np bytes),

number of names nn (long integer),

class pointers (120 bytes);

names (24*nn bytes);

Lists (type 15), tlists (type 16), mlists (type 17)

number of fields n (long integer),

pointers (4*(n+1) bytes);

variables (each one written according to its format)

Pointers (type 128) ??

See Also

save , load , listvarinfile , type , typeof ,

Authors

compiled by Enrico Segre


save

Scilab Function
Last update : 27/09/2005

save - saving variables in binary files

Calling Sequence

save(filename [,x1,x2,...,xn])
save(fd [,x1,x2,...,xn])

Parameters

  • filename : character string containing the path of the file
  • fd : a file descriptor given by a call to mopen
  • xi : arbitrary Scilab variable(s)

Description

The save command can be used to save Scilab current variables in a binary file. If a variable is a graphic handle, the save function saves all the corresponding graphics_entities definition.

The file can be given either by its paths or by its descriptor previously given by mopen .

save(filename) saves all current variables in the file defined by filename .

save(fd) saves all current variables in the file defined by the descriptor fd .

save(filename,x,y) or save(fd,x,y) saves only named variables x and y .

Saved variables can be reloaded by the load command.

Examples

a=eye(2,2);b=ones(a);
save('val.dat',a,b);
clear a
clear b
load('val.dat','a','b');

// sequential save into a file
fd=mopen('TMPDIR/foo','wb')
for k=1:4, x=k^2;save(fd,x,k),end
mclose(fd)
fd=mopen('TMPDIR/foo','rb')
for i=1:4, load(fd,'x','k');x,k,end
mclose(fd)

// appending variables to an old save file
fd=mopen('TMPDIR/foo','r+')
mseek(0,fd,'end')
lst=list(1,2,3)
save(fd,lst)
mclose(fd)

See Also

load , save_format , mopen ,


scanf_conversion

Scilab Function
Last update : 12/01/2004

scanf_conversion - scanf, sscanf, fscanf conversion specifications

Description

Each conversion specification in the format parameter contains the following elements:

+The character % (percent sign)
+The optional assignment suppression character *
+An optional numeric maximum field width
+A conversion code

The conversion specification has the following syntax:

[*][width][size]convcode .

The results from the conversion are placed in v_i arguments unless you specify assignment suppression with * (asterisk). Assignment suppression provides a way to describe an input field that is to be skipped. The input field is a string of nonwhite-space characters. It extends to the next inappropriate character or until the field width, if specified, is exhausted.

The conversion code indicates how to interpret the input field. You should not specify the v_i parameter for a suppressed field. You can use the following conversion codes:

%:Accepts a single % (percent sign) input at this point; no assignment is done.
d, i:Accepts a decimal integer;
u:Accepts an unsigned decimal integer;
o:Accepts an octal integer;
x:Accepts a hexadecimal integer;
e,f,g:Accepts a floating-point number. The next field is converted accordingly and stored through the corresponding parameter, which should be a pointer to a float. The input format for floating-point numbers is a string of digits, with the following optional characteristics:
+It can be a signed value.
+It can be an exponential value, containing a decimal point followed by an exponent field, which consists of an E or an e followed by an (optionally signed) integer.
+It can be one of the special values INF, NaN,
s:Accepts a string of characters.
c:character value is expected. The normal skip over white space is suppressed.

See Also

scanf , scanf , fscanf ,


scanf

Scilab Function
Last update : 12/01/2004

scanf - Converts formatted input on standard input

Calling Sequence

[v_1,...v_n]=scanf (format);

Parameters

  • format :Specifies the format conversion.

Description

The scanf functions get character data on standard input (%io(1)), interpret it according to a format, and returns the converted results.

The format parameter contains conversion specifications used to interpret the input.

The format parameter can contain white-space characters (blanks, tabs, newline, or formfeed) that, except in the following two cases, read the input up to the next nonwhite-space character. Unless there is a match in the control string, trailing white space (including a newline character) is not read.

-Any character except % (percent sign), which must match the next character of the input stream.
-A conversion specification that directs the conversion of the next input field. see scanf_conversion for details.

See Also

printf , read , fscanf , sscanf ,


sprintf

Scilab Function
Last update : 12/01/2004

sprintf - Emulator of C language sprintf function

Calling Sequence

str=sprintf(format,value_1,..,value_n)

Parameters

  • format : a Scilab string. Specifies a character string combining literal characters with conversion specifications.
  • value_i : Specifies the data to be converted according to the format parameter.
  • str : column vector of character strings

Description

The sprintf function converts, formats, and stores its value parameters, under control of the format parameter.

The format parameter is a character string that contains two types of objects:

Literal characters: which are copied to the output stream.
Conversion specifications: each of which causes zero or more items to be fetched from the value parameter list. see printf_conversion for details

If there are not enough items for format in the value parameter list, sprintf generate an error. If any value s remain after the entire format has been processed, they are ignored.

Note: sprintf is obsolete, use msprintf instead.

Examples

fahr=120
sprintf('%3d Fahrenheit = %6.1f Celsius',fahr,(5/9)*(fahr-32))

See Also

string , print , write , format , disp , file , printf , fprintf , msprintf ,


sscanf

Scilab Function
Last update : 04/10/2004

sscanf - Converts formatted input given by a string

Calling Sequence

[v_1,...v_n]=sscanf (string,format)

Parameters

  • format :Specifies the format conversion.
  • string :Specifies input to be read.

Description

This function is obsolete, use preferably the msscanf function which is more efficient and is more compatible with the C sscanf procedure.

The sscanf functions interpret character string according to a format, and returns the converted results.

The format parameter contains conversion specifications used to interpret the input.

The format parameter can contain white-space characters (blanks, tabs, newline, or formfeed) that, except in the following two cases, read the input up to the next nonwhite-space character. Unless there is a match in the control string, trailing white space (including a newline character) is not read.

-Any character except % (percent sign), which must match the next character of the input stream.
-A conversion specification that directs the conversion of the next input field. see scanf_conversion for details.

See Also

mprintf , msscanf , mfscanf ,


startup

Scilab Function
Last update : 21/11/2006

startup - startup file

Description

Les fichiers de démarrage SCIHOME/.scilab et SCIHOME/scilab.ini sont automatiquement executés (s'ils existent) au démarrage de Scilab, ainsi que le fichier SCI/scilab.star présent dans le répertoire de Scilab.

Remarks

les fichiers de démarrage doivent obligatoirement comporter une nouvelle ligne en fin de fichier pour être pris en compte.

Définition de SCIHOME : Sous Windows : C:/Documents and Settings/<User>/Scilab/<Scilab-Version> Sous Linux/Unix : /home/<User>/.Scilab/<Scilab-Version>

See Also

scilab ,


tk_getdir

Scilab Function
Last update : 12/01/2004

tk_getdir - dialog to get a directory path

Calling Sequence

path=tk_getdir([title='string'])
path=tk_getdir([title='string'])
path=tk_getdir(dir,[title='string'])
path=tk_getdir(dir,'string')

Parameters

  • dir : a character string which gives the initial directory used for directory search. by default tk_getdir uses the previously selected directory.
  • path : is the user selected file path if user answers "Ok" or the " " string if user answers "Cancel"
  • title='string' :Optional argument which gives the title for the tk_getdir window.

Description

Creates a dialog window for file selection

Examples

tk_getdir()
tk_getdir('SCI/macros/xdess')
tk_getdir(title='Choose a directory name ')

See Also

tk_getfile , file , fileinfo ,


tk_getfile

Scilab Function
Last update : 06/11/2006

tk_getfile - dialog to get one or more file paths

Calling Sequence

path=tk_getfile([Title="string"])
path=tk_getfile([multip="1"])
path=tk_getfile(file_mask[,Title="string"][,multip="1"])
path=tk_getfile(file_mask,dir[,Title="string"])
path=tk_getfile(file_mask,dir[,Title="string"][,multip="1"])
path=tk_getfile(file_mask,dir,"string"[,"multip"])

Parameters

  • file_mask : a character string which gives the file mask to use for file selection. file_mask is written with Unix convention. The default value is '*'.
  • dir : a character string which gives the initial directory used for file search. By default tk_getfile uses the previously selected directory.
  • path : is the user selected file path(s) if user answers "Ok" or the " " string if user answers "Cancel".
  • Title="string" : Optional argument which gives the title for the tk_getfile window. Warning : use the variable name Title instead of title .
  • multip : Optional argument which allows to select more than one file at once in the tk_getfile window. If given, it must be the string "1". Otherwise, or if not given, this argument defaults to "0" i.e. only one file can be selected in the dialog.

Description

Creates a dialog window for file selection.

Examples

tk_getfile()
tk_getfile("*.sci","SCI/macros/xdess")
tk_getfile(Title="Choose a file name")
tk_getfile(Title="Choose many file names at once",multip="1")
tk_getfile(multip="1")

See Also

xgetfile , tk_getdir , file , fileinfo ,


tk_savefile

Scilab Function
Last update : 06/11/2006

tk_savefile - dialog to get a file path for writing

Calling Sequence

path=tk_savefile([Title='string'])
path=tk_savefile(file_mask,[Title='string'])
path=tk_savefile(file_mask,dir,[Title='string'])
path=tk_savefile(file_mask,dir,'string')

Parameters

  • file_mask : a character string which gives the file mask to use for file selection. file_mask is written with Unix convention. the default value is '*'.
  • dir : a character string which gives the initial directory used for file search. by default tk_savefile uses the previously selected directory.
  • path : is the user selected file path if user answers "Ok" or the " " string if user answers "Cancel"
  • Title='string' :Optional arguments which gives the title for the tk_savefile window. Warning : use the variable name Title intead of title .

Description

Creates a dialog window for output file selection

Examples

tk_savefile()
tk_savefile('*.sci','SCI/macros/xdess')
tk_savefile(Title='Choose a file name ')

See Also

xgetfile , tk_getdir , tk_getfile , file , fileinfo ,


warning

Scilab Function
Last update : 12/01/2004

warning - warning messages

Calling Sequence

warning('string')

Description

prints the character string 'string' in a warning message

See Also

error ,


writb

Scilab Function
Last update : 12/01/2004

writb - fortran file binary write

Calling Sequence

writb(file-name,a [,rec])

Parameters

  • file-name : string or integer
  • rec : vector of positive integers. the selected records for direct access. This vector size must be equal to the number of rows of a

Description

writes in binary format the matrix a in the file 'filename' .. Matrix entries are stored on 4 byte words

For direct record access, file must have been previously opened using file function to set the record_length. file-name must be the result of the file function.

See Also

file , readb , write , mput , write4b ,


write4b

Scilab Function
Last update : 12/01/2004

write4b - fortran file binary write

Calling Sequence

write4b(file-name,a [,rec])

Parameters

  • file-name : string or integer
  • rec : vector of positive integers. the selected records for direct access. This vector size must be equal to the number of rows of a

Description

writes in binary format the matrix a in the file 'filename' . Matrix entries are stored on 8 byte words

For direct record access, file must have been previously opened using file function to set the record_length. file-name must be the result of the file function.

See Also

file , readb , write , mput , read4b ,


write

Scilab Function
Last update : 12/01/2004

write - write in a formatted file

Calling Sequence

write(file-desc,a,[format])
write(file-desc,a,k,format)

Parameters

  • file-desc : character string specifying the file name or integer value specifying logical unit (see file).
  • a : real matrix or column vector of character strings.
  • format : character string, specifies a "Fortran" format. This character string must begin with a right parenthesis and end with a left parenthesis. Formats cannot mix floating point , integer or character edition modes
  • k : integer vector

Description

writes row-by-row a real matrix or a column vector of character strings in a formatted file. Each row of the a argument begin in a new line of file-desc file. Depending on format a given row of the a argument may be written in more than one line of file-desc file.

Format examples : (1x,e10.3,5x,3(f3.0)) , (10x,a20) ;

See a Fortran book for more precision.

Direct access files : x=write(file_desc,a,k,format) . Here k is the vector of records (one record by row, i.e. m=prod(size(k) )

write(%io(2),....) writes on Scilab's window. Note that in this case format should produce one output line per matrix row. If this contraint is not verified unpredictable behavior could happen.

Examples

if MSDOS then unix('del asave');
else unix('rm -f asave'); end
A=rand(5,3); write('asave',A); A=read('asave',5,3);
write(%io(2),A,'('' | '',3(f10.3,'' | ''))')
write(%io(2),string(1:10))
write(%io(2),strcat(string(1:10),','))
write(%io(2),1:10,'(10(i2,3x))')

if MSDOS then unix('del foo');
else unix('rm -f foo'); end
write('foo',A)

See Also

file , fileinfo , writb , read , print , string , mfprintf , mprintf , msprintf , fprintfMat ,


xgetfile

Scilab Function
Last update : 12/01/2004

xgetfile - dialog to get a file path

Calling Sequence

path=xgetfile([title='string'])
path=xgetfile(file_mask,[title='string'])
path=xgetfile(file_mask,dir,[title='string'])
path=xgetfile(file_mask,dir,'string')

Parameters

  • file_mask : a character string which gives the file mask to use for file selection. file_mask is written with Unix convention. the default value is '*'.
  • dir : a character string which gives the initial directory used for file search. by default xgetfile uses the previously selected directory.
  • path : is the user selected file path if user answers "Ok" or the " " string if user answers "Cancel"
  • title='string' :Optional arguments which gives the title for the xgetfile window.

Description

Creates a dialog window for file selection

Examples

xgetfile()
xgetfile('*.sci','SCI/macros/xdess')
xgetfile(title='Choose a file name ')

See Also

x_dialog , file , read , write , exec , getf ,


xls_open

Scilab Function
Last update : 22/03/2005

xls_open - Open an Excel file for reading

Calling Sequence

[fd,SST,Sheetnames,Sheetpos] = xls_open(file_path)

Parameters

  • file_path : a character string: the path of the Excel file.
  • fd : a number, the logical unit on the Excel stream.
  • SST : A vector of all character strings which appear in the Excel sheets.
  • Sheetnames : a vector of strings: the sheet names.
  • Sheetpos : a vector of numbers: the position of the beginning of sheets in the Excel stream.

Description

This function first analyzes the ole2 data structure associated with the given file to extract the Excel stream which is included in. After that the Excel stream is saved in the TMDIR directory and opened. The fd logical unit points to this temporary file. Then the first sheet in this stream is read to get the global informations like number of sheets, sheet names Sheetnames , sheet adresses within the stream Sheetpos and the SST which contains all the strings used in the following sheets.

The fd and Sheetpos data have to be passed to xls_read to read the data sheets.

The readxls function can be used to read all an Excel file in one function with a single function call.

Warning only BIFF8 Excel files (last Excel file version) are handled

Examples

   //Decode ole file, extract and open Excel stream
    [fd,SST,Sheetnames,Sheetpos] = xls_open('SCI/demos/excel/Test1.xls')
    //Read first data sheet
    [Value,TextInd] = xls_read(fd,Sheetpos(1))
    //close the excel stream
    mclose(fd)

See Also

xls_read , readxls ,

Authors

Pierrick Mode INRIA
Serge Steer INRIA

Bibliography

This function is based on the Microsoft ole2 file documentation (http://chicago.sourceforge.net/devel/docs/ole/) and on Excel stream description from OpenOffice (http://sc.openoffice.org/excelfileformat.pdf).

Used Function

The ripole-0.1.4 procedure (http://www.pldaniels.com/ripole) is used to extract the excel stream out of the ole file.


xls_read

Scilab Function
Last update : 22/03/2005

xls_read - read a sheet in an Excel file

Calling Sequence

[Value,TextInd] = xls_read(fd,Sheetpos)

Parameters

  • fd : a number, the logical unit on the Excel stream returned by xls_open .
  • Sheetpos : a number: the position of the beginning of the sheet in the Excel stream. This position is one of those returned by xls_open .
  • Value : a matrix of numbers, the numerical data found in the sheet. The cell without numerical data are represented by NaN values.
  • TextInd : a matrix of indices with the same size as Value . The 0 indices indicates that no string exists in the correspondin Excel cell. a positive index i points to the string SST(i) where SST is given by xls_open .

Description

This function reads an Excel sheet given a logical unit on an Excel stream ant the position of the beginning of the sheet within this stream. It returns the numerical data and the strings contained by the Excel cells.

The readxls function can be used to read all an Excel file in one function with a single function call.

Warning only BIFF8 Excel files (last Excel file version) are handled

Examples

   //Decode ole file, extract and open Excel stream
    [fd,SST,Sheetnames,Sheetpos] = xls_open('SCI/demos/excel/Test1.xls')
    //Read first data sheet
    [Value,TextInd] = xls_read(fd,Sheetpos(1))
    //close the excel stream
    mclose(fd)

See Also

xls_open , readxls ,

Authors

Pierrick Mode INRIA
Serge Steer INRIA

Bibliography

This function is based on Excel stream description from OpenOffice (http://sc.openoffice.org/excelfileformat.pdf).

Used Function

This unction uses the xls.c file which can be found in a Scilab source version in the directory SCIDIR/routines/sound


Manipulation des fonctions et des librairies
addinter - new functions interface incremental linking at run time
argn - nombre d'arguments d'appel d'une fonction
clearfun - remove primitive.
comp - pré-interprétation ou "compilation" de fonctions Scilab
deff - on-line definition of function
delbpt - delete breakpoints
dispbpt - display breakpoints
edit - function editing
funcprot - switch scilab functions protection mode
endfunction - fin de la définition d'une fonction Scilab
function - définition d'une fonction Scilab
functions - procédures Scilab et objets Scilab
genlib - build library from functions in given directory
get_function_path - get source file path of a library function
getd - chargement de toutes les fonctions contenues dans un répertoire
getf - chargement de fonctions à partir d'un fichier
lib - library definition
library - library datatype description
macr2lst - function to list conversion
macr2tree - conversion d'une fonction en arbre
macro - Scilab procedure and Scilab object
macrovar - variables of function
newfun - add a name in the table of functions
plotprofile - extracts and displays execution profiles of a Scilab function
profile - extract execution profiles of a Scilab function
setbpt - set breakpoints
showprofile - extracts and displays execution profiles of a Scilab function
varargin - variable numbers of arguments in an input argument list
varargout - variable numbers of arguments in an output argument list


addinter

Scilab Function
Last update : 12/01/2004

addinter - new functions interface incremental linking at run time

Calling Sequence

addinter(files,spname,fcts)

Parameters

  • files : a character string or a vector of character string contain object files used to define the new Scilab interface routine (interface code, user routines or libraries, system libraries).
  • spname : a character string. Name of interface routine entry point
  • fcts : vector of character strings. The name of new Scilab function implemented in the new interface (in fin the order ).

Description

addinter performs incremental linking of a compiled C or Fortran new Scilab interface routine (see intersci documentation) and define corresponding scilab functions.

For machines using dlopen functionality one can unlink an interface with ulink ( use the command link('show') to get the number of the shared library ). And to reload a new version of an interface a call to ulink is necessary to get rid of the old version.

See link for more precision on use.

See Also

link , intersci , newfun , clearfun ,


argn

Scilab Function
Last update : 16/06/2004

argn - nombre d'arguments d'appel d'une fonction

Calling Sequence

[lhs [,rhs] ]=argn()
lhs=argn(1)
rhs=argn(2)

Description

Cette fonction est utilisée à l'intérieur d'une définition de fonction. Elle donne le nombre effectif (au moment de l'appel) d'arguments d'entrée rhs et de sortie lhs . Elle permet d'utiliser des arguments optionnels.

See Also

function , varargin ,


clearfun

Scilab Function
Last update : 12/01/2004

clearfun - remove primitive.

Calling Sequence

clearfun('name')

Description

clearfun('name') removes the primitive 'name' from the set of primitives (built-in functions) . This function allows to rename a primitive : a Scilab primitive can be replaced by a user-defined function. For experts...

See Also

newfun , funptr ,


comp

Scilab Function
Last update : 08/09/2006

comp - pré-interprétation ou "compilation" de fonctions Scilab

Calling Sequence

comp(function)

Parameters

  • function : une fonction non "compilée" (type 11)

Description

comp(function) "compile" la fonction function . Les fonctions "compilées" et interprétées sont équivalentes mais les fonctions "compilées" sont plus rapides. Les fonctions fournies dans les librairies standard de Scilab sont "compilées".

La définition en line des fonction ainsi que la forme courte des fonctions getf et deff produisent des fonctions compilées. L'usage de la fonction comp est donc réservé a des usages très particuliers. Pour générer des fonction non compilées, il faut appeler les fonctions getf ou deff avec l'option "n" .

See Also

deff , getf , function ,


deff

Scilab Function
Last update : 12/01/2004

deff - on-line definition of function

Calling Sequence

deff('[s1,s2,...]=newfunction(e1,e2,....)',text [,opt])

Parameters

  • e1,e2,..., : input variables.
  • s1,s2,..., : output variables.
  • text : matrix of character strings
  • opt : optional character string
    • 'c' : function is "compiled" to be more efficient (default)
    • 'n' : function is not "compiled"

Description

On-line definition of function (user defined function): the name of the created function is newfunction . text is a sequence of instructions usually set as a vector of character strings.

This command can be used inside a function and the new function can be an input or output of any other function.

Usually, functions are defined in a file and loaded into Scilab by getf

Some time, in particular when you want to use define strings within deff text is rather difficult to write. A more tractable way may be to define your function in a file as usual, to load it into Scilab by getf (without 'c' option) and use sci2exp to get corresponding deff instructions.

Examples

deff('[x]=myplus(y,z)','x=y+z')
//
deff('[x]=mymacro(y,z)',['a=3*y+1'; 'x=a*z+y'])

See Also

getf , comp , exec , function ,


delbpt

Scilab Function
Last update : 08/06/2005

delbpt - delete breakpoints

Calling Sequence

delbpt([macroname [,linenumb]])

Parameters

  • macroname : string
  • linenumb : scalar integer or vector of integers

Description

Deletes the breakpoint at line linenumb in the function macroname .

linenumb can be a line or column vector of line numbers, or a single scalar line number.

If linenumb is omitted, all the breakpoints in function macroname are deleted.

If both macroname and linenumb are omitted, all the breakpoints in all the functions are deleted.

Examples

setbpt('foo',1),setbpt('foo',10),delbpt('foo',10),dispbpt()
delbpt('foo',1),dispbpt()

setbpt('foo1',4),setbpt('foo1',9),setbpt('foo2',6),setbpt('foo3',8),dispbpt()
delbpt('foo2'),dispbpt()
delbpt(),dispbpt()

delbpt('foo',[1,2,5,6]),dispbpt()

See Also

setbpt , dispbpt , pause , resume ,


dispbpt

Scilab Function
Last update : 08/06/2005

dispbpt - display breakpoints

Calling Sequence

dispbpt()

Description

dispbpt() displays all active breakpoints currently inserted in functions.

See Also

setbpt , delbpt , pause , resume ,


edit

Scilab Function
Last update : 26/05/2005

edit - function editing

Calling Sequence

newname=edit(functionname [, editor])

Parameters

  • functionname : character string
  • editor : character string

Description

If functionname is the name of a defined scilab function edit(functionname ,[editor]) try to open the associated file functionname.sci . If this file can't be modified edit first create a copy of this file in the TMPDIR directory.

If functionname is the name of a undefined scilab function edit create a functionname.sci file in the TMPDIR directory.

When leaving the editor the modified or defined function is loaded into Scilab under the name newname .

The editor character string can be used to specify your favourite text editor. It is generally a system command, or the string "scipad", in which case the internal editor is used.

Default editor is Emacs. This function should be customized according to your needs.

Examples

//newedit=edit('edit')  //opens editor with text of this function
//myfunction=edit('myfunction')  //opens editor for a new function

See Also

manedit , scipad ,


funcprot

Scilab Function
Last update : 12/01/2004

funcprot - switch scilab functions protection mode

Calling Sequence

prot=funcprot()
funcprot(prot)

Parameters

  • prot : integer with possible values 0,1,2

Description

Scilab functions are variable, funcprot allows the user to specify what scilab do when such variables are redefined.

*If prot==0 nothing special is done
*If prot==1 scilab issues a warning message when a function is redefined (default mode)
*If prot==2 scilab issues an error when a function is redefined

Examples

funcprot(1)
deff('[x]=foo(a)','x=a')
deff('[x]=foo(a)','x=a+1')
foo=33
funcprot(0)
deff('[x]=foo(a)','x=a')
deff('[x]=foo(a)','x=a+1')
foo=33


functions

Scilab Data type
Last update : 08/02/2005

functions - procédures Scilab et objets Scilab

Description

Les fonctions Scilab sont des procédures ("macros", "fonction" et "procédures" ont la même signification).

Définition de fonctions

Les fonctions sont tapées dans un éditeur de texte et chargées dans Scilab avec la commande getf ou via une librairie (voir lib ou genlib ). Mais elles peuvent être définies en ligne (voir deff ou function ). Une fonction est définie en deux parties :

une ligne de déclaration formelle

 function [y1,...,yn]=foo(x1,...,xm)
 function [y1,...,yn,varargout]=foo(x1,...,xm,varargin)

une suite d'instructions Scilab.

La "ligne de définition" donne la syntaxe d'appel complète de la fonction. Les yi sont les variables de sortie, calculées à partir des variables d'entrée xi et des variables existantes dans le contexte appelant lorsque la fonction est exécutée. On peut utiliser éventuellement un sous-ensemble de ces variables d'entrée et de sortie.

Appel à une fonction

LA syntaxe d'appel est habituellement [y1,...,yn]=foo(x1,...,xm) . On peut utiliser éventuellement un sous-ensemble de ces variables d'entrée et de sortie. Dans ce cas, seules les premières variables à partir de la gauche sont utilisées. La fonction argn peut être utilisée pour connaître le nombre effectif d'arguments d'appel.

Il est aussi possible d'utiliser des "arguments nommés" pour spécifier les valeurs des arguments d'entrée : supposons que la fonction fun1 est définie ainsi function y1=fun1(x1,x2,x3) alors on peut utiliser la syntaxe y=fun1(x1=33,x3=[1 2 3]) , et dans fun1 x2 ne sera pas défini. Il est possible de vérifier quelles sont les variables définies avec la fonction exists .

Quand une fonction n'a pas d'argument de sortie et est appelée avec des arguments d'entrée de type chaîne de caractère, la syntaxe d'appel peut être simplifiée : fun('a','toto','une chaîne') est alors équivalent à fun a toto 'une chaîne'

Divers

Les fonctions sont des objets Scilab (numéro de type 13 ou 11). Elles peuvent être manipulées (passées en argument, sauvées, chargées, ...) comme toute autre variable.

Un ensemble de fonctions peut être assemblé dans une librairie. Les fonctions dont le nom commence par le caractère % (exemple : %foo ) sont utilisées pour la surcharge des opérateurs (voir overloading ) ou des fonctions pour des nouveaux types de données.

Examples

// définition en ligne
function [x,y]=myfct(a,b)
x=a+b
y=a-b
endfunction

[x,y]=myfct(3,2)

// autre type de définition en ligne
deff('[x,y]=myfct(a,b)',['x=a+b';
                         'y=a-b'])
// définition dans un fichier texte (voir exec)
exec SCI/macros/elem/asinh.sci;

// définition dans un fichier texte (voir getf)
getf SCI/macros/elem/asinh.sci;

See Also

function , deff , getf , comp , lib , getd , genlib , exists , varargin , varargout ,


functionendfunction

Scilab keyword
Last update : 08/02/2005

function - définition d'une fonction Scilab

endfunction - fin de la définition d'une fonction Scilab

Description

       function <arguments_sortie>=<nom_de_la_fonction><arguments_entrée>
       <instructions>
        endfunction
où
<nom_de_la_fonction>est le nom de la fonction
<arguments_entrée>est la liste d'arguments d'entrée. Il peut s'agir de :
-une liste de noms de variables séparés par des virgules, entourée de parenthèses, comme (x1,...,xm) . Le dernier nom de variable peut être varargin (voir varargin)
-la séquence () ou rien du tout, si la fonction n'a pas d'argument d'entrée.
<arguments_sortie>Est la liste d'arguments de sortie. Il peut s'agir de
-une liste de noms de variables séparés par des virgules, entourée de crochets, comme [y1,...,ym] . Le dernier nom de variable peut être varargout (voir varargout)
-la séquence [] , si la fonction n'a pas d'argument de sortie. Dans ce cas la syntaxe d'appel peut aussi être : function <nom_de_la_fonction><arguments_entrée>
<instructions>une suite d'instructions Scilab. Cette syntaxe peut être utilisée pour définir des fonctions (voir functions) en ligne ou dans un script (voir exec). Pour raisons de compatibilité avec les anciennes versions de Scilab, les fonctions définies dans un script ne contenant que des déclarations de fonctions peuvent être chargées dans Scilab avec la fonction getf .

La séquence function <arguments_sortie>=<nom_de_la_fonction><arguments_entrée> doit apparaître sur une seule ligne. Cette suite peut être suivie d'instructions Scilab si une virgule ou un point-virgule est ajouté à la fin.

Les définitions de fonctions peuvent être imbriquées.

Examples

// définition en ligne
function [x,y]=myfct(a,b)
x=a+b
y=a-b
endfunction

[x,y]=myfct(3,2)

// définition sur une seule ligne
function y=sq(x),y=x^2,endfunction

sq(3)

// définitions imbriquées
function y=foo(x)
a=sin(x)
function y=sq(x), y=x^2,endfunction
y=sq(a)+1
endfunction

foo(%pi/3)

// définition dans un script
exec SCI/macros/elem/asinh.sci;

See Also

functions , exec , getf ,


genlib

Scilab Function
Last update : 04/07/2005

genlib - build library from functions in given directory

Calling Sequence

genlib(lib_name [[,dir_name, [ Force [,verb [,Names]]]])
genlib(lib_name [,path=dir_name] [,verbose=verb] [,force=Force] [,names=Names])

Parameters

  • lib_name: Scilab string. The variable name of the library to (re)create.
  • dir_name: Scilab string. The name of the directory to look for .sci -files.
  • Force : boolean value (default value is %f ). Set it to %f to force the sci-files recompilation.
  • verb : boolean values (default value is %f ). Set it to %f to get information.
  • Names : a vector of strings, the names of function to include in the library. By default all the sci-files are taken into account

Description

For each .sci file in dir_name (or only those specified by the Names argument), genlib executes a getf and saves the functions to the corresponding .bin file. The .sci file must not contain anything but Scilab functions. If a .bin file is newer than the associated .sci file, genlib does not translate and save the file.

This default behaviour can be changed if force is given and set to %t . In this latter case the recompilation is always performed for each .sci file.

When all .sci files have been processed, genlib creates a library variable named lib_name and saves it in the file lib in dir_name . If the Scilab variable lib_name is not protected (see predef ) this variable is updated.

If verbose is et to %t information are displayed during the build process.

If dir_name argument is not given and if lib_name Scilab variable exists and it is a library dir_name is taken equal to the lib_name library path (update mode).

Restrictions

Scilab tacitly assumes that file foo.sci defines at least a function named foo . If subsidiary functions are included, they are made known to Scilab only after the function foo had been referenced.

See Also

getd , getf , save , lib ,


getd

Scilab Function
Last update : 16/06/2004

getd - chargement de toutes les fonctions contenues dans un répertoire

Calling Sequence

getd(path)

Parameters

  • path : chaîne de caractères, chemin du répertoire

Description

Charge tous les fichiers .sci (contenant des fonctions Scilab) présents dans le répertoire path .

Examples

getd('SCI/macros/auto')

See Also

getf , lib , getcwd , pwd , chdir ,


getf

Scilab Function
Last update : 16/06/2004

getf - chargement de fonctions à partir d'un fichier

Calling Sequence

getf(file-name [,opt])

Parameters

  • filename : chaîne de caractères
  • opt : chaîne de caractères optionnelle. Si opt=="c", les fonctions sont "compilées" pour accélérer leur exécution (par défaut). Si opt=="n", les fonctions ne sont pas "compilées". Si opt=="p",les fonctions sont "compilées" et préparées pour les statistiques d'appel (voir profile )

Description

Charge une ou plusieurs fonctions (voir functions ) définies dans le fichier 'file-name' . La chaîne de caractères opt='n' signifie que les fonctions ne sont pas compilées (pré-interprétées) au chargement. Cela peut être utile en phase de mise au point (voir comp ). Par défaut les fonctions sont compilées (i.e. opt='c' est utilisée).

Dans le fichier chaque fonction doit commencer par une ligne de la forme :

function [y1,...,yn]=foo(x1,...,xm)

suivie par une suite d'instructions Scilab.

La "ligne de définition" donne la syntaxe d'appel complète de la fonction. Les yi sont les variables de sortie, calculées à partir des variables d'entrée xi et des variables existantes dans le contexte appelant lorsque la fonction est exécutée. On peut utiliser éventuellement un sous-ensemble de ces variables d'entrée et de sortie.

Il est possible d'écrire plusieurs fonctions dans un seul fichier. Une fonction est alors terminée par le mot-clé endfunction ou par la ligne de déclaration de la fonction suivante (ancienne convention) ou par la fin du fichier.

getf est une ancienne manière de charger les fonctions. Si chaque fonction est terminée par endfunction , les fonctions peuvent être chargées avec la commande exec au lieu de getf . Dans ce cas l'option par défaut opt est utilisée.

Examples

getf('SCI/macros/xdess/plot.sci')

getf SCI/macros/xdess/plot.sci

See Also

functions , function , genlib , getd , exec , edit , comp ,


get_function_path

Scilab Function
Last update : 12/01/2004

get_function_path - get source file path of a library function

Calling Sequence

path=get_function_path(fun_name)

Parameters

  • fun_name : a string, the name of the function
  • path : a string, the absolute pathname of the function source file (.sci) or [].

Description

Given the name of a function get_function_path returns the absolute pathname of the function source file if the function is defined in a Scilab library (see lib) or [] if name does not match any library function.

Examples

get_function_path('median')

See Also

lib , string ,


library

Scilab data type
Last update : 13/07/2005

library - library datatype description

Calling Sequence

Description

A library is a data type with type number 14. It contains a path-name and a set of names. It allows automatic loading of variables using the following algorithm:

Suppose the Scilab user references the variable named foo . Scilab first looks if foo is the name of a primitive or of an already defined variable. If not, it looks for foo sequentially (the newest first) in all defined library .

Suppose foo belongs to the set of names of the library xlib then Scilab tries to load the file <xlib-path-name>/foo.bin. <xlib-path-name>/foo.bin must have been created using the save function

Library are often used for collection of functions, but they can also be used for any collection of scilab variables

If a function is defined in more than one library, the default search algorithm loads thode contained in the newest. It possible to force the use of a specific library using dot notation:

xlib.foo loads the variable foo contained in xlib . if foo is a function and xlib.foo(args) executes the functions

Examples

// elemlib is a predefined library
elemlib //displays the contents of the library
A=rand(3,3);
cosm(A) //loads cosm and executes it

whos -name cosm // now cosm is a variable

elemlib.sinm //loads sinm from the library

elemlib.cosm(A) //reloads cosm and executes it

See Also

lib , string , load , save ,


lib

Scilab Function
Last update : 12/01/2004

lib - library definition

Calling Sequence

xlib = lib('lib-dir')

Parameters

  • lib-dir : character string

Description

lib-dir is a character string defining a directory that contains compiled Scilab function ( .bin ) files.

In addition to these files lib-dir must have a file called names , that contains the names of the functions defined in lib-dir . On success, all functions in lib-dir are available from within Scilab. They are loaded on demand when called for the first time.

Binary files can be created from within Scilab with the command save .

Scilab's standard libraries are defined using lib on the SCIDIR/macros/* subdirectories.

A library variable usually is saved for later loading, either on-line or from the user-specific startup file (see startup).

Restrictions

Scilab tacitly assumes that each xxxx.bin file defines a variable named xxxx .

Examples

//define some variables
function z = myplus(x, y), z = x + y,endfunction
function z = yourplus(x, y), x = x - y,endfunction
A=1:10;

//create the *.bin files in libdir
libdir=TMPDIR
save(libdir + '/myplus.bin', myplus);
save(libdir + '/yourplus.bin', yourplus);
save(libdir + '/A.bin', A);

//create the name file
mputl(['myplus';'yourplus';'A'],TMPDIR+'/names');

//build the library containing myplus and yourplus
xlib = lib(libdir+'/')

//erase the variables
clear myplus yourplus A

//Automatic loading and execution
myplus(1,2)

A

See Also

library , genlib , save , deff , getf , whereis ,


macr2lst

Scilab Function
Last update : 12/01/2004

macr2lst - function to list conversion

Calling Sequence

[txt]=macr2lst(function-name)

Description

This primitive converts a compiled Scilab function function-name into a list which codes the internal representation of the function. For use with mac2for .

See Also

macrovar ,


macr2tree

Fonction Scilab
Last update : 13/12/2005

macr2tree - conversion d'une fonction en arbre

Calling Sequence

t=macr2tree(nom-de-fonction)

Parameters

  • nom-de-fonction : une macro Scilab
  • t : un "arbre" Scilab

Description

Cette primitive convertit une fonction compilée de Scilab nom-de-fonction en arbre (tlists imbriquées) qui code la représentation interne de la fonction. A utiliser avec tree2code .

Examples

tree=macr2tree(cosh);
txt=tree2code(tree,%T);
write(%io(2),txt,'(a)');

See Also

tree2code ,

Authors

V.C.


macrovar

Scilab Function
Last update : 12/01/2004

macrovar - variables of function

Calling Sequence

vars=macrovar(function)

Parameters

  • vars : list list(in,out,globals,called,locals)
  • function : name of a function

Description

Returns in a list the set of variables used by a function. vars is a list made of five column vectors of character strings

in : input variables ( vars(1) )

out : output variables ( vars(2) )

globals : global variables ( vars(3) )

called : names of functions called ( vars(4) )

locals : local variables ( vars(5) )

Examples

deff('y=f(x1,x2)','loc=1;y=a*x1+x2-loc')
vars=macrovar(f)

See Also

string , macr2lst ,


macro

Scilab Function
Last update : 12/01/2004

macro - Scilab procedure and Scilab object

Description

Macros are Scilab procedures ("macro", "function" and "procedure" have the save meaning). Usually, they are defined in files with an editor and loaded into Scilab by getf or through a library.

They can also be defined on-line (see deff ). A file which contains a macro must begin as follows:

function [y1,...,yn]=foo(x1,...,xm)

The yi are output variables calculated as functions of input variables and variables existing in Scilab when the macro is executed. A macro can be compiled for faster execution. Collections of macros can be collected in libraries. Macros which begin with % sign (e.g. %foo ) and whose arguments are lists are used to perform specific operations: for example, z=%rmr(x,y) is equivalent to z=x*y when x and z are rationals (i.e. x=list('r',n,d,[]) with n and d polynomials).

See Also

deff , getf , comp , lib ,


newfun

Scilab Function
Last update : 12/01/2004

newfun - add a name in the table of functions

Calling Sequence

newfun("function-name",nameptr)

Description

Utility function (for experts only). Adds the name "function-name" in the table of functions known to the interpreter. "nameptr" is an integer 100*fun+fin where fun and fin is the internal coding of the primitive "function-name" . This function is useful to associate a primitive to a routine interfaced in "matusr.f" ( fun=14 ). Used with funptr and clearfun one can redefine a primitive by a function with same name.

See Also

clearfun ,


plotprofile

Scilab Function
Last update : 21/11/2005

plotprofile - extracts and displays execution profiles of a Scilab function

Calling Sequence

plotprofile(fun)

Parameters

  • fun : a Scilab compiled function, or a function name (string), or an array of function names

Description

To use plotprofile , the Scilab function must have been prepared for profiling (see getf).

When such a function is executed, the system counts how many times each line is executed and how much cpu time is spent executing each line. This data is stored within the function data structure. The function plotprofile in an interactive command which displays this results in a graphic window. When a line is clicked, the source of the function is displayed with the selected line highlighted.

NOTE: you have to click on the "Exit" item in the graphics windows to exit from "plotprofile".

The function code is regenerated with fun2string and dumped into a temporary file.

Examples

//define a function and prepare it for profiling
deff('x=foo(n)',['if n==0 then'
                 '  x=[]'
                 'else'
                 '  x=0'
                 '  for k=1:n'
                 '    s=svd(rand(n+10,n+10))'
                 '    x=x+s(1)'
                 '  end'
                 'end'],'p')
//call the function
foo(30)
//get execution profiles
plotprofile(foo) // click on Exit to exit

See Also

profile , showprofile , fun2string ,


profile

Scilab Function
Last update : 12/01/2004

profile - extract execution profiles of a Scilab function

Calling Sequence

c=profile(fun)

Parameters

  • fun : a Scilab function
  • c : a nx3 matrix containig the execution profiles

Description

To use profile the Scilab function must have been prepared for profiling (see getf).

For such function, When such a function is executed the systems counts how many time each line is executed and how may cpu time is spend for each line execution. These data are stored within the function data structure. The profile function allows to extract these data and return them in the two first columns of c . The c third column gives a measure of interpetor effort for one execution of corresponding line. Ith line of c corresponds to Ith line of the function (included first)

Note that, due to the precision of the processor clock (typically one micro second), some executed lignes may appear with 0 cpu time even if total cpu time really spend in their execution is large.

Examples

//define function and prepare it for profiling
deff('x=foo(n)',['if n==0 then'
                 '  x=[]'
                 'else'
                 '  x=0'
                 '  for k=1:n'
                 '    s=svd(rand(n+10,n+10))'
                 '    x=x+s(1)'
                 '  end'
                 'end'],'p')
//call the function
foo(10)
//get execution profiles
profile(foo)
//call the function
foo(20)
profile(foo) //execution profiles are cumulated

See Also

getf , deff , plotprofile , showprofile ,


setbpt

Scilab Function
Last update : 08/06/2005

setbpt - set breakpoints

Calling Sequence

setbpt(macroname [,linenumb])

Parameters

  • macroname : string
  • linenumb : scalar integer or vector of integers

Description

setbpt interactively inserts a breakpoint in the line number linenumb (default value is 1) of the function macroname

linenumb can be a line or column vector of line numbers, or a single scalar line number.

When reaching the breakpoint, Scilab evaluates the specified line, prints the number of the line and the name of the function. If the function is not compiled (see comp ) the line is printed on the screen. Then Scilab goes into a pause mode in which the user can check current values. The pause is exited with resume or abort . Redefining the function does not clear the breakpoints, the user must explicitly delete breakpoints using delbpt . The maximum number of functions with breakpoints enabled must be less than 100 and the maximum number of breakpoints is set to 1000.

Examples

setbpt('foo'),setbpt('foo',10),dispbpt()
delbpt()

setbpt('foo',[1,2,5,6]),dispbpt()

See Also

delbpt , dispbpt , pause , resume ,


showprofile

Scilab Function
Last update : 12/01/2004

showprofile - extracts and displays execution profiles of a Scilab function

Calling Sequence

showprofile(fun)

Parameters

  • fun : a Scilab function

Description

To use showprofile the Scilab function must have been prepared for profiling (see getf).

For such function, When such a function is executed the systems counts how many time each line is executed and how may cpu time is spend for each line execution. These data are stored within the function data structure. The showprofile function outputs profiling results (see profile ) with text of the function lines.

Function text is rebuild with fun2string .

Examples

//define function and prepare it for profiling
deff('x=foo(n)',['if n==0 then'
                 '  x=[]'
                 'else'
                 '  x=0'
                 '  for k=1:n'
                 '    s=svd(rand(n+10,n+10))'
                 '    x=x+s(1)'
                 '  end'
                 'end'],'p')
//call the function
foo(30)
//get execution profiles
showprofile(foo)

See Also

profile , plotprofile , fun2string ,


varargin

Scilab keyword
Last update : 12/01/2004

varargin - variable numbers of arguments in an input argument list

Description

A function whose input argument list contains varargin can be called with more input arguments than indicated in the input argument list. The calling arguments passed form varargin keyword onwards may then be retrieved within the function in a list named varargin .

Suppose that varargin keyword is the n th argument of the formal input argument list, then if the function is called with less than n-1 input arguments the varargin list is not defined, if the function is called with n-1 arguments then varargin list is an empty list.

y = function ex(varargin) may be called with any number of input arguments. Within function ex input arguments may be retrieved in varargin(i) , i=1:length(varargin)

Remark

Named argument syntax like foo(...,key=value) is incompatible with the use of varargin.

Examples

deff('exampl(a,varargin)',['[lhs,rhs]=argn(0)'
                          'if rhs>=1 then disp(varargin),end'])
exampl(1)
exampl()
exampl(1,2,3)
l=list('a',%s,%t);
exampl(1,l(2:3))

See Also

function , varargout , list ,


varargout

Scilab keyword
Last update : 12/01/2004

varargout - variable numbers of arguments in an output argument list

Description

A function whose output argument list contains varargout must be called with more output arguments than indicated in the output argument list. The calling arguments passed form varargout keyword onwards are extracted out of the varargout list defined in the function

varagout = function ex() may be called with any number of output arguments. Within function ex output arguments may be stored in in varargout(i) .

Examples

deff('varargout=exampl()','varargout=list(1,2,3,4)')

x=exampl()
[x,y]=exampl()
[x,y,z]=exampl()

See Also

function , varargin , list ,


Manipulations de chaînes de caractères
chartooem - translates a string into the OEM-defined character set.(Windows only)
code2str - returns character string associated with Scilab integer codes.
convstr - case conversion
emptystr - zero length string
grep - find matches of a string in a vector of strings
justify - Justify character array.
length - length of object
oemtochar - translates a string from the OEM-defined character set into either an ANSI string. (Windows Only)
part - extraction of strings
str2code - return scilab integer codes associated with a character string
strcat - catenate character strings
strindex - search position of a character string in an other string.
string - conversion to string
strings - Scilab Object, character strings
stripblanks - strips leading and trailing blanks (and tabs) of strings
strsplit - split a string into a vector of strings
strsubst - substitute a character string by another in a character string.
tokenpos - returns the tokens positions in a character string.
tokens - returns the tokens of a character string.


chartooem

Scilab Function
Last update : 08/06/2005

chartooem - translates a string into the OEM-defined character set.(Windows only)

Calling Sequence

str=chartooem(str1)

Parameters

  • str1 : a matrix of ANSI character string.
  • str : a matrix of OEM-defined character string.

Description

chartooem translates a string into the OEM-defined character set.

See Also

oemtochar ,


code2str

Scilab Function
Last update : 12/01/2004

code2str - returns character string associated with Scilab integer codes.

Calling Sequence

str=code2str(c)

Parameters

  • str : a character string
  • c : vector of character integer codes

Description

Returns character string associated with Scilab integer codes.str is such that c(i) is the Scilab integer code of part(str,i))

Examples

code2str([-28 12 18 21 10 11])

See Also

str2code ,


convstr

Scilab Function
Last update : 12/01/2004

convstr - case conversion

Calling Sequence

[y]=convstr(str-matrix, ["flag"])

Parameters

  • str-matrix, y : matrices of strings
  • "flag" : string ( "u" for upper or "l" for lower (default value))

Description

converts the matrix of strings str-matrix into lower case (for "l" ;default value) or upper case (for "u" ).

Examples

A=['this','is';'my','matrix'];
convstr(A,'u')


emptystr

Scilab Function
Last update : 12/01/2004

emptystr - zero length string

Calling Sequence

s=emptystr()
s=emptystr(a)
s=emptystr(m,n)

Parameters

  • a : any type of matrix
  • s : character string matrix
  • m,n : integers

Description

Returns a matrix of zero length character strings

With no input argument returns a zero length character string.

With a matrix for input argument returns a zero length character strings matrix of the same size.

With two integer arguments returns a mxn zero length character strings matrix

Examples

x=emptystr();for k=1:10, x=x+','+string(k);end

See Also

part , length , string ,


grep

Scilab Function
Last update : 12/01/2004

grep - find matches of a string in a vector of strings

Calling Sequence

row=grep(str1,str2)
[row,which]=grep(str1,str2)

Parameters

  • str1 : a vector of strings.
  • str2 : a character string or character string vector . The string(s) to search in str1
  • row : vector of indices: row where a match has been found or an empty matrix if no match found.
  • which : vector of indices: index of str2 string found or an empty matrix if no match found.

Description

Foreach entry of str1 , grep searches if at least a string in str2 matches a substring. str1 entries index where at least a match has been found are returned in the row argument. while optionnal which argument gives the index of first string of str2 found.

Examples

txt=['find matches of a string in a vector of strings'
     'search position of a character string in an other string'
     'Compare Strings'];

grep(txt,'strings')
grep(txt,['strings' 'Strings'])

[r,w]=grep(txt,['strings' 'Strings'])

See Also

strindex ,


justify

Scilab Function
Last update : 12/01/2004

justify - Justify character array.

Calling Sequence

Tj=justify(T,opt)

Parameters

  • T : a matrix of character string.
  • Tj : a matrix of character string. the justified result
  • opt : a character string option with possible values
    • 'r' or 'right' for right justification
    • 'l' or 'left' for left justification
    • 'c' or 'center' for centering justification

Description

justify justify the column of a matrix of string accdording to the given option.

Examples

t=['1234','x','adfdfgdfghfgj'
   '1','354556','dgf'
   'sdfgd','','sdfsf'];

justify(t,'l')
justify(t,'c')

See Also

length , part ,


length

Scilab Function
Last update : 12/01/2004

length - length of object

Calling Sequence

n=length(M)

Parameters

  • M : matrix (usual or polynomial or character string) or list
  • n : integer or integer matrix

Description

For usual or polynomial matrix n is the integer equal to number of rows times number of columns of M . (Also valid for M a boolean matrix)

For matrices made of character strings (and in particular for a character string) length returns in n the length of entries of the matrix of character strings M .

The length of a list is the number of elements in the list (also given by size ).

length('123') is 3 . length([1,2;3,4]) is 4 .

See Also

size ,


oemtochar

Scilab Function
Last update : 08/06/2005

oemtochar - translates a string from the OEM-defined character set into either an ANSI string. (Windows Only)

Calling Sequence

str=oemtochar(str1)

Parameters

  • str1 : a matrix of OEM-defined character string.
  • str : a matrix of ANSI character string.

Description

oemtochar translates a string from the OEM-defined character set into either an ANSI string.

See Also

chartooem ,


part

Scilab Function
Last update : 12/01/2004

part - extraction of strings

Calling Sequence

[c]=part(mp,v)

Parameters

  • mp,c : string matrices
  • v : integer vector.

Description

Let s[k] stands for the k character of string s ( or the white space character if k >length(s) ).

part returns c , a matrix of character strings, such that c(i,j) is the string "s[v(1)]...s[v(n)]" ( s=mp(i,j) ).

Examples

c=part(['a','abc','abcd'],[1,1,2])

See Also

string , length ,


str2code

Scilab Function
Last update : 12/01/2004

str2code - return scilab integer codes associated with a character string

Calling Sequence

c=str2code(str)

Parameters

  • str : a character string
  • c : vector of character integer codes

Description

Return c such that c(i) is the scilab integer code of part(str,i))

Examples

str2code('Scilab')

See Also

code2str ,


strcat

Scilab Function
Last update : 12/01/2004

strcat - catenate character strings

Calling Sequence

txt=strcat(vstr [,strp])

Parameters

  • vstr : vector of strings
  • strp : string, default value is the emptystr ""
  • txt : string

Description

txt=strcat(vstr) catenates character strings : txt=vstr(1)+...+vstr(n)

txt=strcat(vstr,strp) returns txt=strs(1)+strp+...+strp+strs(n) . The plus symbol does the same: "a"+"b" is the same as strcat(["a","b"])

Examples

strcat(string(1:10),',')

See Also

string , strings ,


strindex

Scilab Function
Last update : 27/08/2004

strindex - search position of a character string in an other string.

Calling Sequence

ind=strindex(str1,str2)
[ind,which]=strindex(str1,str2)

Parameters

  • str1 : a character string. The string where to search occurrences of str2
  • str2 : a character string or character string vector . The string(s) to search in str1
  • ind : vector of indexes
  • which : vector of indexes

Description

strindex searches indexes where str2(i) is found in str1

for each k it exist a i shuch that part(str1,ind(k)+(0:length(str2(i))-1)) is the same string than str2(i) . If which argument is required it contains these i .

Examples

k=strindex('SCI/demos/scicos','/')
k=strindex('SCI/demos/scicos','SCI/')
k=strindex('SCI/demos/scicos','!')
k=strindex('aaaaa','aa')
k=strindex('SCI/demos/scicos',['SCI','sci'])
[k,w]=strindex('1+3*abc/2.33',['+','-','*','/'])

See Also

string , strings ,


strings

Scilab Object
Last update : 12/01/2004

strings - Scilab Object, character strings

Description

Strings are defined as 'string' (between quotes) or "string" (between doublequotes); matrices of strings are defined as usual constant matrices.

Concatenation of two strings is made by a + : string1+string2 .

Examples

['this','is'; 'a 2x2','matrix']
"matrix"=="mat"+"rix"

See Also

part , length , strcat ,


string

Scilab Function
Last update : 12/01/2004

string - conversion to string

Calling Sequence

string(x)
[out,in,text]=string(x)

Parameters

  • x : real matrix or function

Description

converts a matrix into a matrix of strings.

If x is a function [out,in,text]=string(x) returns three vectors strings : out is the vector of output variables, in is the vector of input variables, and text is the (column) vector of the source code of the function.

If x is a lib variable, text is a character string column vector. The first element contains the path of library file and the other the name of functions it defines.

Character strings are defined as 'string' (between quotes) or "string" (between doublequotes); matrices of strings are defined as usual constant matrices.

Concatenation of strings is made by the + operation.

Examples

string(rand(2,2))
deff('y=mymacro(x)','y=x+1')
[out,in,text]=string(mymacro)
x=123.356; 'Result is '+string(x)

See Also

part , length , quote , evstr , execstr , strsubst , strcat , strindex , sci2exp ,


stripblanks

Scilab Function
Last update : 28/10/2004

stripblanks - strips leading and trailing blanks (and tabs) of strings

Calling Sequence

txt=stripblanks(txt[,tabs])

Parameters

  • txt : string or matrix of strings
  • tabs : if TRUE then tabs are also stripped (default value is FALSE)

Description

stripblanks strips leading and trailing blanks (and tabs) of strings

Examples

a='  123   ';
'!'+a+'!'
'!'+stripblanks(a)+'!'
a=['  123   ',' xyz']
strcat(stripblanks(a))


strsplit

Scilab Function
Last update : 01/02/2006

strsplit - split a string into a vector of strings

Calling Sequence

v = strsplit(str,ind)

Parameters

  • str : a string
  • ind : a vector of stricly increasing indices in the interval [1 length(str)-1] .
  • v : the resulting column vector of strings (dimension size(ind,'*')+1 ).

Description

v = strsplit(str,ind) splits the string str into a vector of strings at the points given by the indices in ind (after each characters pointed to by the index in ind).

Examples

    S='strsplit splits a string into a vector of strings';
    strsplit(S,[15 25 30])
    ind=strindex(S,' ')

See Also

strcat , tokens ,

Authors

S. Steer INRIA


strsubst

Scilab Function
Last update : 12/01/2004

strsubst - substitute a character string by another in a character string.

Calling Sequence

str=strsubst(str1,str2,str3)

Parameters

  • str1 : a matrix of character string. The strings where to search occurrences of str2
  • str2 : a character string. The string to search in str1 .
  • str3 : a character string. The replacement string.
  • str : a matrix of character string. The result of the substitution on str2 by str3 in str1

Description

strsubst replaces all occurrences of str2 in str1 by str3 .

Examples

strsubst('SCI/demos/scicos','SCI','.')
strsubst('SCI/demos/scicos','/',' ')

See Also

string , strings ,


tokenpos

Scilab Function
Last update : 12/01/2004

tokenpos - returns the tokens positions in a character string.

Calling Sequence

kdf=tokenpos(str [,delimiter])

Parameters

  • str : a character string. The string where to search the tokens.
  • delimiter : (optional) a character or a vector of characters. The tokens delimeters.
  • kdf : two columns matrix, first column gives the index of the beginning of the tokens, the second gives the index of the last character of the tokens.

Description

kdf=tokenpos(str [,delimiter]) searches the tokens included in the string str . The delimiter default value is [" ",<Tab>] where <Tab> stands for ascii(9) . It returns the indices of the first and last characters of each found tokens.

Examples

str='This is a character string';
kdf=tokenpos(str)
first=part(str,kdf(1,1):kdf(1,2))

See Also

strindex , tokens ,


tokens

Scilab Function
Last update : 12/01/2004

tokens - returns the tokens of a character string.

Calling Sequence

T=tokens(str [,delimiter])

Parameters

  • str : a character string. The string where to search the tokens.
  • delimiter : (optional) a character or a vector of characters. The tokens delimeters.
  • T : column vector of found tokens

Description

T=tokens(str [,delimiter]) searches the tokens included in the string str . The delimiter default value is [" ",<Tab>] where <Tab> stands for ascii(9) .

Examples

tokens('This is a character string')

tokens('SCI/demos/scicos','/')

tokens('y=a+b*2',['=','+','*'])

See Also

strindex , tokenpos ,


IHM et Dialogues
addmenu - interactive button or menu definition
browsevar - Scilab variable browser
buttondialog - Create a simple button dialog
config - Scilab general configuration.
delmenu - interactive button or menu deletion
demoplay - interactive demo player.
editvar - Scilab variable editor
getvalue - boîte de dialogue de saisie de paramètres
halt - stop execution
havewindow - return scilab window mode
keyboard - keyboard commands
progressionbar - Draw a progression bar
seteventhandler - set an event handler for the current graphic window
setmenu - interactive button or menu activation
unsetmenu - interactive button or menu or submenu de-activation
waitbar - Draw a waitbar
winclose - close windows created by sciGUI
winlist - Return the winId of current window created by sciGUI
x_choices - boîte de dialogue permettant de choisir des articles parmi plusieurs options
x_choose - boîte de dialogue permettant de faire des choix
x_dialog - boîte de dialogue
x_matrix - Xwindow editing of matrix
x_mdialog - boîte de dialogue pour la saisie de paramètres
x_message - boîte de dialogue modale
x_message_modeless - boîte de dialogue non modale


addmenu

Scilab Function
Last update : 12/01/2004

addmenu - interactive button or menu definition

Calling Sequence

addmenu(button [,submenus] [,action])
addmenu(gwin,button [,submenus] [,action])

Parameters

  • button : a character string. The button name. On Windows operating systems (not X_window), an & can be placed before the character in the name to be used for keyboard shortcut; this character will be underlined on the GUI.
  • submenus : a vector of character string. The sub_menus items names
  • action : a list with 2 elements action=list(flag,proc_name)
    • flag : an integer (default value is 0)
    • flag==0 the action is defined by a scilab instruction
    • flag==1 the action is defined by a C or Fortran procedure
    • flag==2 : the action is defined by a scilab function
    • proc_name : a character string which gives the name of scilab variable containing the instruction or the name of procedure to call.
  • gwin : integer. The number of graphic window where the button is required to be installed

Description

The function allows the user to add new buttons or menus in the main window or graphics windows command panels.

If action argument is not given the action associated with a button must be defined by a scilab instruction given by the character string variable which name is

+ button for a main window command

+ button_gwin for a graphic window command

If action argument is set to 0 proc_name should be the name of a Scilab string vector. Actions associated with the kth sub_menu must be defined by scilab instructions stored in the kth element of the character string variable.
If action argument is set to 1 proc_name designes a C or Fortran procedure, this procedure may be interfaced in Fortran subroutine default/fbutn.f or dynamically linked with scilab using the link function. The C calling sequence is: (char* button_name, int* gwin,int *k)
If action argument is set to 2 proc_name designes a Scilab function. This function calling sequence should be:

+ proc_name(k) for a main window command

+ proc_name(k,gwin) for a graphic window command or a main window command

Examples

addmenu('foo')
foo='disp(''hello'')'

addmenu('Hello',['Franck';'Peter'])
Hello=['disp(''hello Franck'')';'disp(''hello Peter'')']

addmenu(0,'Hello',['Franck';'Peter'])
Hello_0=['disp(''hello Franck'')';'disp(''hello Peter'')']

addmenu('Bye',list(0,'French_Bye'))
French_Bye='disp(''Au revoir'')'

//C defined Callback
// creating Callback code
code=[ '#include ""machine.h""'
 'void foo(char *name,int *win,int *entry)'
 '{'
 '  if (*win==-1) '
 '    sciprint(""menu %s(%i) in Scilab window selected\r\n"",name,*entry+1);'
 '  else'
 '    sciprint(""menu %s(%i) in window %i selected\r\n"",name,*entry+1,*win);'
 '}'];
//creating foo.c file
dir=getcwd(); chdir(TMPDIR)
mputl(code,TMPDIR+'/foo.c');
//reating Makefile
ilib_for_link('foo','foo.o',[],'c');
exec('loader.sce');
chdir(dir);
//add menu
addmenu('foo',['a','b','c'],list(1,'foo'))

See Also

setmenu , unsetmenu , delmenu ,


browsevar

sciGUI toolbox function
Last update : 29/06/2004

browsevar - Scilab variable browser

Calling Sequence

browsevar()

Description

browsevar is an embedded Scilab variable browser written in TCL/TK.

browsevar can show all variables and function (like who). browsevar can be costumized to show all or some type of variable. It's also posibble exclude variable names.

Examples

browsevar();

Author

Jaime Urzua


buttondialog

sciGUI toolbox function
Last update : 29/06/2004

buttondialog - Create a simple button dialog

Calling Sequence

answer=buttondialog(mes,buttons[,icon])

Parameters

  • mes : string, message to display.
  • buttons : string, buttons name.
  • icon : string, icon type, should be: error, hourglass, info, passwd, question and warning.

Description

buttondialog create a simple button dialog and retur the answer. buttons identify the buttons to show in the following manner : "button_1|button_2....|button_n"

Examples

answ=buttondialog("This is an example","ok");
answ=buttondialog("Do the work?","yes|no|maybe","question");

Author

Jaime Urzua


config

sciGUI toolbox function
Last update : 29/06/2004

config - Scilab general configuration.

Calling Sequence

config()

Description

config() allow configure scilab parameters like lines to display, stacksize, %ODEOPTIONS.

Author

Jaime Urzua


delmenu

Scilab Function
Last update : 21/07/2005

delmenu - interactive button or menu deletion

Calling Sequence

delmenu(button)
delmenu(gwin,button)

Parameters

  • button : a character string. The button name. On Windows operating systems (not X_window), an & should be placed before the character in the name used for keyboard shortcut; this character is underlined on the GUI.
  • gwin : integer. The number of graphic window where the button is required to be installed

Description

The function allows the user to delete buttons or menus create by addmenu in the main or graphics windows command panels. Predefined buttons on Scilab graphic windows can also be deleted.

If possible, it is better to delete first the latest created button for a given window to avoid gaps in command panels.

Examples

addmenu('foo')
delmenu('foo')

See Also

setmenu , unsetmenu , addmenu ,


demoplay

sciGUI toolbox function
Last update : 29/06/2004

demoplay - interactive demo player.

Calling Sequence

demoplay(filename)

Parameters

  • filename : string, name of the file to play.

Description

demoplay display demo files in a interactive manner. More information to do!!

Examples

demoplay();

Author

Jaime Urzua


editvar

sciGUI toolbox function
Last update : 29/06/2004

editvar - Scilab variable editor

Calling Sequence

editvar varname

Parameters

  • varname : variable name. The variable must exist in scilab.

Description

editvar is an embedded Scilab variable editor written in TCL/TK.

editvar can edit the following variable type: real or complex constant matrix (type 1), boolean matrix (type 4) an matrix of character strings (type 10).

Examples

a=rand(10,10);
editvar a;
b=['hello';'good bye'];
editvar b;

Author

Jaime Urzua


getvalue

Scilab Function
Last update : 17/06/2004

getvalue - boîte de dialogue de saisie de paramètres

Calling Sequence

[ok,x1,..,x14]=getvalue(desc,labels,typ,ini)

Parameters

  • desc : vecteur colonne de chaînes de caractères,
  • labels : vecteur colonne de n chaînes de caractères, labels(i) est l'entête du i-ème paramètre
  • typ : list(typ_1,dim_1,..,typ_n,dim_n)
    • typ_i : définit le type de la ième valeur. typ_i peut prendre l'une des valeurs :
      • "mat" : matrice
      • "col" : vecteur colonne
      • "row" : vecteur ligne
      • "vec" : vecteur
      • "str" : chaîne de caractères
      • "lis" : liste
    • dim_i : définit les dimensions de la i-ème valeur. Ce doit être un entier ou un vecteur de deux entiers. -1 signifie que les dimensions ne sont pas définies.
    • ini : vecteur colonne de n chaînes de caractères, ini(i) donne la valeur par défaut du i-ème paramètre
    • ok : booléen, %t (vrai) si le bouton "Ok" a été pressé, %f (faux) pour le bouton "Cancel"
    • xi : contient le i-ème paramètre si ok=%t. Si la liste des arguments de sortie contient un xi de plus que nécessaire, la valeur du dernier xi contient le vecteur des chaînes de caractères correspondant aux paramètres choisis.

Description

Cette fonction est une interface vers la fonction x_mdialog avec contrôle d'erreur, vérification de taille et de type des paramètres, évaluation des expressions Scilab, etc.

REMARQUES

Toute expression Scilab valide peut être utilisée pour entrer un paramètre; pour les matrices et les vecteurs getvalues ajoute [ ] autour des valeurs rentrées avant leur évaluation.

Examples

    labels=["module";"frequence";"phase    "];
    [ok,mag,freq,ph]=getvalue("signal sinusoidal",labels,...
    list("vec",1,"vec",1,"vec",1),["0.85";"10^2";"%pi/3"])

See Also

x_mdialog , x_matrix , x_dialog ,

Author

S. Steer ; ;


halt

Scilab Function
Last update : 12/01/2004

halt - stop execution

Calling Sequence

halt()

Description

stops execution until something is entered in the keyboard.

See Also

pause , return , exec ,


havewindow

Scilab Function
Last update : 12/01/2004

havewindow - return scilab window mode

Calling Sequence

havewindow()

Description

returns %t if scilab has it own window and %f if not, i.e. if scilab has been invoked by "scilab -nw". ( nw stands for "no-window".


keyboard

Scilab Function
Last update : 12/01/2004

keyboard - keyboard commands

Description

Let C- stands for the control key. The following keyboard commands are available:

C-lclears the Scilab window
C-ddeletes the current character
C-pcalls back the preceding command
C-ngo to next command line
C-amoves the cursor to the beginning of command line.
C-bbackspace, moves the cursor one character to the left
C-fforwards, moves the cursor one character to the right
C-kkills command line from cursor to the end.
C-yyank, retrieves killed line.
!beglooks for last command line which begins by beg .
C-cinterrupts Scilab and pause after carriage return. (Only functions can be interrupted). Clicking on the stop button enters a C-C .

See Also

pause , read , input ,


progressionbar

sciGUI toolbox function
Last update : 29/06/2004

progressionbar - Draw a progression bar

Calling Sequence

winId=progressionbar(mes)
progressionbar(winId[,mes])

Parameters

  • mes : string, message to display.
  • winId : integer greater than 0, window identificator.

Description

progressionbar(mes) create a new progression bar, return window identificator.

progressionbar(winId[,mes]) update the progression bar identificated as winId.

Examples

winId=progressionbar('Do something');
realtimeinit(0.3);
for j=0:0.1:1,
    realtime(3*j);
    progressionbar(winId);
end
winclose(winId);

Author

Jaime Urzua


seteventhandler

Scilab Function
Last update : 25/03/2005

seteventhandler - set an event handler for the current graphic window

Calling Sequence

seteventhandler(sfun_name)
seteventhandler('')

Parameters

  • sfun_name : a character string. The name of the Scilab function which is intended to handle the events

Description

The function allows the user to set a particular event handler for the current graphic window. seteventhandler('') removes the handler.

The event handler is defined by a Scilab function whose calling sequence must be function sfun_name(win,x,y,ibut) , where

win represents the number of the window where the event had occured.

x,y are the coordinates of the pointer (in pixels), when the event has occured

ibut is the event type:

  • ibut==0 : Left mouse button has been pressed
  • ibut==1 : Middle mouse button has been pressed
  • ibut==2 : Right mouse button has been pressed

  • ibut==3 : Left mouse button has been clicked
  • ibut==4 : Middle mouse button has been clicked
  • ibut==5 : Right mouse button has been clicked

  • ibut==10 : Left mouse button has been double-clicked
  • ibut==11 : Middle mouse button has been double-clicked
  • ibut==12 : Right mouse button has been double-clicked

  • ibut==-5 : Left mouse button has been released
  • ibut==-4 : Middle mouse button has been released
  • ibut==-3 : Right mouse button has been released

  • ibut==-1 : pointer has moved

  • ibut > =32 : key with ascii code ascii(ibut) has been pressed
  • ibut < =-32 : key with ascii code ascii(-ibut) has been released

  • ibut > =1000+32 : key with ascii code ascii(ibut-1000) has been pressed while CTRL key pressed
  • ibut==-1000 : graphic window has been closed

    • Examples

   function my_eventhandler(win,x,y,ibut)
      if ibut==-1000 then return,end
      [x,y]=xchange(x,y,'i2f')
       xinfo(msprintf('Event code %d at mouse position is (%f,%f)',ibut,x,y))
   endfunction
   plot2d()
   seteventhandler('my_eventhandler')
   //now:
   //   -  move the mouse over the graphic window
   //   -  press and release keys shifted or not with Ctrl pressed or not
   //   -  press button, wait a little release
   //   -  press and release button
   //   -  double-click button

   seteventhandler('') //suppress the event handler

    See Also

    addmenu , xgetmouse , xclick , xchange ,


setmenu

Scilab Function
Last update : 12/01/2004

setmenu - interactive button or menu activation

Calling Sequence

setmenu(button [,nsub])
setmenu(gwin,button [,nsub])

Parameters

  • button : a character string. The button name
  • gwin : integer. The number of graphic window where the button is installed
  • nsub : integer. The number of submenu to de-activate (if any). If button has no sub-menu, nsub is ignored

Description

The function allows the user to make active buttons or menus created by addmenu in the main or graphics windows command panels.

Examples

addmenu('foo')   //New button made in main scilab window
unsetmenu('foo')   //button foo cannot be activated (grey string)
setmenu('foo')     //button foo can be activated (black string)

See Also

delmenu , unsetmenu , addmenu ,


unsetmenu

Scilab Function
Last update : 12/01/2004

unsetmenu - interactive button or menu or submenu de-activation

Calling Sequence

unsetmenu(button,[nsub])
unsetmenu(gwin,button,[nsub])

Parameters

  • button : a character string. The button name
  • gwin : integer. The number of graphic window where the button is installed
  • nsub : integer. The number of submenu to de-activate (if any). If button has no sub-menu, nsub is ignored

Description

The function allows the user to desactivate buttons or menus created by addmenu in the main or graphics windows command panels.

Examples

//addmenu('foo')
//unsetmenu('foo')
//unsetmenu('File',2)

See Also

delmenu , setmenu , addmenu ,


waitbar

sciGUI toolbox function
Last update : 29/06/2004

waitbar - Draw a waitbar

Calling Sequence

winId=waitbar(x)
winId=waitbar(x,mes)
winId=waitbar(mes)
waitbar(x,winId)
waitbar(mes,winId)
waitbar(x,mes,winId)

Parameters

  • x : real, fraction to display.
  • mes : string, message to display.
  • winId : integer greater than 0, window identificator.

Description

waitbar(x) create a new waitbar displaying a fraction x, return window identificator.

waitbar(x,mes) create a new waitbar displaying a fraction x and message mes, return window identificator.

waitbar(mes) create a new waitbar displaying a fraction 0 and message mes, return window identificator.

waitbar(x,mes) create a new waitbar displaying a fraction 0 and message mes, return window identificator.

waitbar(x,winId) , waitbar(mes,winId) and waitbar(x,mes,winId) update waitbar with window identificator winId.

Examples

winId=waitbar('This is an example');
realtimeinit(0.3);
for j=0:0.1:1,
    realtime(3*j);
    waitbar(j,winId);
end
winclose(winId);

Author

Jaime Urzua


winclose

sciGUI toolbox function
Last update : 10/02/2006

winclose - close windows created by sciGUI

Calling Sequence

winclose(winIds)

Parameters

  • winIds : matrix of integer greater than 0, window identificator.

Description

winclose(winIds) close windows created by sciGUI.

Examples

//CREATE SOME WINDOWS
win1=waitbar('This is an example');
win2=waitbar('HELLO!');
winclose([win1,win2]);

Author

Jaime Urzua


winlist

sciGUI toolbox function
Last update : 29/06/2004

winlist - Return the winId of current window created by sciGUI

Calling Sequence

winIds=winlist()

Parameters

  • winIds : matrix of integer greater than 0, window identificator.

Description

winlist() Return the winId of current window created by sciGUI.

Author

Jaime Urzua


x_choices

Scilab Function
Last update : 16/06/2004

x_choices - boîte de dialogue permettant de choisir des articles parmi plusieurs options

Calling Sequence

rep=x_choices(title,items)

Parameters

  • title : vecteur de chaînes de caractères. Titre général
  • items : une liste d'articles items=list(item1,...,itemn) , où chaque item est aussi une liste du type suivant : item=list('label',default_choice,choices) . default_choice est un entier donnant le numéro du choix par défaut et choices est un vecteur ligne de chaînes de caractères donnant les choix possibles.
  • rep : un entier donnant le numéro du choix pour chaque article. Si le bouton "Cancel" est pressé rep vaut [] en sortie.

Description

Sélectionne des articles multiples et renvoie dans rep les numéros des articles sélectionnés.

Taper x_choices() pour voir un exemple.

Examples

l1=list('choix 1',1,['article c1','article c2','article c3']);
l2=list('choix 2',2,['article d1','article d2','article d3']);
l3=list('choix 3',3,['article e1','article e2']);
rep=x_choices('Menu d''articles',list(l1,l2,l3));


x_choose

Scilab Function
Last update : 16/06/2004

x_choose - boîte de dialogue permettant de faire des choix

Calling Sequence

[num]=x_choose(items,title [,button])

Parameters

  • items : vecteur colonne de chaînes de caractères. Les articles à choisir
  • title : vecteur colonne de chaînes de caractères. Titre de la boîte
  • button : chaîne de caractères, texte du bouton d'annulation ('Cancel' par défaut)
  • num : entier, le numéro de l'article choisi ou 0 si "Cancel" a été pressé.

Description

Renvoie dans num le numéro de l'article choisi.

Examples

n=x_choose(['item1';'item2';'item3'],['ceci est un commentaire';'pour la boite de dialogue'])
n=x_choose(['item1';'item2';'item3'],['ceci est un commentaire'],'Terminer')

See Also

x_choices , x_mdialog , getvalue , unix_g ,


x_dialog

Scilab Function
Last update : 16/06/2004

x_dialog - boîte de dialogue

Calling Sequence

result=x_dialog(labels,valueini)

Parameters

  • labels : vecteur de chaînes de caractères. Commentaire de la boîte
  • valueini : vecteur de n chaînes de caractères. Valeurs suggérées
  • result : vecteur de n chaînes de caractères si le bouton "Ok" est pressé ou [] si "Cancel" a été pressé.

Description

Crée une boîte de dialogue à plusieurs lignes.

Examples

gain=evstr(x_dialog('valeur du gain ?','0.235'))
x_dialog(['Methode';'entrer la periode d''echantillonnage'],'1')
m=evstr(x_dialog('entrer une matrice 3x3',['[0 0 0';'0 0 0';'0 0 0]']))

See Also

x_mdialog , x_matrix , evstr , execstr ,


x_matrix

Scilab Function
Last update : 12/01/2004

x_matrix - Xwindow editing of matrix

Calling Sequence

[result]=x_matrix(label,matrix-init)

Parameters

  • label : character string (name of matrix)
  • matrix-init : real matrix

Description

For reading or editing a matrix .

Examples

//m=evstr(x_matrix('enter a  3x3 matrix ',rand(3,3)))

See Also

x_mdialog , x_dialog ,


x_mdialog

Scilab Function
Last update : 16/12/2005

x_mdialog - boîte de dialogue pour la saisie de paramètres

Calling Sequence

result=x_mdialog(title,labels,default_inputs_vector)
result=x_mdialog(title,labelsv,labelsh,default_input_matrix)

Parameters

  • title : vecteur colonne de chaînes de caractères. Titre général
  • labels : n vecteurs colonnes de chaînes de caractères, labels(i) est l'intitulé du i-ème paramètre à saisir
  • default_input_vector : n vecteurs colonnes de chaînes de caractères, default_input_vector(i) la valeur initiale du i-ème paramètre
  • labelsv : vecteur de n chaînes de caractères, labelsv(i) est la légende de la i-ème ligne de la matrice de paramètres
  • labelsh : vecteur de m chaînes de caractères, labelsh(j) est la légende de la j-ième colonne de la matrice de paramètres
  • default_input_matrix : matrice n x m de chaînes de caractères, default_input_matrix(i,j) est la valeur initiale du terme (i,j) de la matrice à saisir
  • result : matrice n x m de chaînes de caractères si le bouton "Ok" a été pressé ou [] si c'est le bouton "Cancel".

Description

Boîte de dialogue pour la saisie de paramètres

Examples

 txt=['module';'frequence';'phase    '];
 sig=x_mdialog('choisir le signal sinusoidal',txt,['1';'10';'0'])
 mag=evstr(sig(1))
 frq=evstr(sig(2))
 ph=evstr(sig(3))

 rep=x_mdialog(['Simulation d''un systeme';'avec un regulateur PI'],...
                      ['gain P';'gain I'],[' ';' '])

See Also

editvar , x_dialog , x_choose , x_message , getvalue , evstr , execstr , editvar ,


x_message_modeless

Scilab Function
Last update : 16/06/2004

x_message_modeless - boîte de dialogue non modale

Calling Sequence

x_message_modeless(strings)

Parameters

  • strings : vecteur de chaînes de caractères à afficher

Description

Pour afficher un message (information, ...). la fonction rend la main immédiatement. La boîte de dialogue est supprimée quand le bouton "Ok" est pressé.

Examples

 x_message_modeless(['Ceci est un message non modal'
                     'Scilab peut continuer a travailler'
                     ' '
                     'Cliquer sur ""Ok"" pour fermer le message'])
 x_message_modeless('Voici un deuxieme message')

See Also

x_dialog , x_mdialog , x_message ,


x_message

Scilab Function
Last update : 16/06/2004

x_message - boîte de dialogue modale

Calling Sequence

[num]=x_message(strings [,buttons])

Parameters

  • strings : vecteur de chaînes de caractères à afficher
  • buttons : chaîne de caractère ou vecteur de deux chaînes de caractères donnant les noms des boutons ("Ok" par défaut).
  • num : numéro du bouton pressé (si 2 boutons ont été spécifiés)

Description

Pour afficher un message (diagnostic, ... ) et attendre une réponse (pression sur un bouton). La fonction rend la main dès qu'un des deux boutons est pressé.

Examples

 gain=0.235;x_message('La valeur du gain est :'+string(gain))
 x_message(['matrice singuliere';'utiliser les moindres carres'])

 r=x_message(['Votre probleme est mal conditionne';
             'continuer ?'],['Oui','Non'])

See Also

x_dialog , x_mdialog , x_message_modeless ,


Utilitaires
G_make - call make or nmake
about - affiche la boite de dialogue "A propos de scilab" (Windows)
add_demo - Add an entry in the demos list
add_help_chapter - Add an entry in the helps list
add_palette - Add an entry in the Scicos palettes list
apropos - recherche d'un mot-clé dans l'aide de Scilab
banner - affiche la baniere scilab
basename - strip directory and suffix from filenames
c_link - check dynamic link
calendar - Calendrier
cd - change le répertoire courant de Scilab
chdir - change le répertoire courant de Scilab
clc - Efface la fenêtre de commande
clipboard - Copie ou colle une chaine de caracteres dans le presse-papier (Windows).
configure_msvc - positionne les variables d'environnements necessaire pour pouvoir utiliser le compilateur Microsoft C.
console - montre ou cache la console (pour Windows)
create_palette - Build Scicos palettes
datenum - Convertie une date en un nombre
datevec - Reconstruction d'un vecteur contenant une Date
dec2hex - représentation hexadécimale d'un entier
dirname - get directory from filenames
edit_error - opens in SciPad the source of the last recorded error
findmsvccompiler - retourne la version du compilateur Microsoft C detecté
foo - foo short description
gethistory - retourne dans une matrice de type chaine de caracteres l'historique de scilab.
getlongpathname - retourne le chemin au format nom long (Seulement pour Windows)
getmemory - returns free and total system memory
getos - retourne le nom et la version de O.S
getscilabkeywords - returns a list with all scilab keywords.
getshell - retourne le nom de l'interpreteur de commandes.
getshortpathname - retourne le chemin au format court (Seulement pour Windows)
head_comments - display scilab function header comments
help - commande d'aide en ligne
help_skeleton - build the skeleton of the xml help file associated to a Scilab function
hex2dec - conversion from hexadecimal representation to integers
ilib_build - utility for shared library management
ilib_compile - ilib_build utility: executes the makefile produced by ilib_gen_Make
ilib_for_link - utility for shared library management with link
ilib_gen_Make - utility for ilib_build: produces a makefile for building shared libraries
ilib_gen_gateway - utility for ilib_build, generates a gateway file.
ilib_gen_loader - utility for ilib_build: generates a loader file
intersci - scilab tool to interface C of Fortran functions with scilab
LANGUAGE - Variable qui définit la langue
link - incremental linker
listfiles - list files
loadhistory - charge un fichier contenant l'historique
make_index - creates a new index file for on-line help
man - on line help XML file description format
mkdir - Crée un nouveau répertoire
pathconvert - pathnames convertion between posix and windows.
%helps - variable contenant les noms des répertoires des chapitres d'aide
perl - execute le script Perl.
printsetupbox - Display print dialog box (Windows)
realtime - set dates origin or waits until date
realtimeinit - set time unit
resethistory - Efface toutes les entrées dans l'historique courant.
rmdir - Supprime un repertoire
savehistory - sauvegarde l'historique de scilab dans un fichier.
sci2exp - convertit une expression ou une instruction d'affectation en une chaîne
sci2map - conversion de variables Scilab vers Maple
scilab - script principal d'exécution de Scilab et de divers outils
scilink - Unix script to relink Scilab
scipad - Embedded Scilab text editor
sethomedirectory - Set Scilab home directory
setlanguage - Modifie la langue courante.
sleep - suspend Scilab
timer - temps CPU consommé
tohome - Déplace le curseur en haut à gauche de la fenêtre de commande
toolbar - montre ou cache la toolbar (pour Windows) (Windows)
toprint - Send text or figure to the printer (Windows)
ulink - unlink a dynamically linked shared object
unix - exécution d'une commande Unix ou DOS
unix_g - exécution d'une commande Unix ou DOS, sortie redirigée vers une variable
unix_s - exécution d'une commande Unix ou DOS, pas de sortie
unix_w - exécution d'une commande Unix ou DOS, sortie redirigée vers la fenêtre de Scilab
unix_x - exécution d'une commande Unix ou DOS, sortie redirigée vers une fenêtre
winopen - Ouvre le fichier avec l'application appropriée (Windows seulement)
winqueryreg - Obtenir une clef de la base des registres de Microsoft Windows
with_atlas - Test si Scilab a ete construit avec la librairie Atlas
with_gtk - Checks if Scilab has been built with the "GIMP Toolkit" library
with_javasci - Test si Scilab a ete construit avec l'interface java
with_pvm - Test si Scilab a été compilé avec l'interface "Parallel Virtual Machine"
with_texmacs - Checks if Scilab has been called by texmacs
with_tk - Checks if Scilab has been built with TCL/TK
xmltohtml - converts xml Scilab help files to html


about

Fonction Scilab
Last update : 08/06/2005

about - affiche la boite de dialogue "A propos de scilab" (Windows)

Calling Sequence

about()

Description

affiche la boite de dialogue "A propos de scilab".

Examples

about()

Author

Allan CORNET


add_demo

Scilab Function
Last update : 12/01/2004

add_demo - Add an entry in the demos list

Calling Sequence

add_demo(title,path)

Parameters

  • title : a character string, the demo title
  • path : a character string, the path of the scilab script associated with the demo

Description

This function adds a new entry in the demos list. The demo should be executed by a Scilab script file. If the given title already exists in the demo list associated with the same file nothing is done. The function checks if the file exist.

Examples

  //create a simple demo script
  path=TMPDIR+'/foo.sce';
  mputl('disp Hello',path)
  add_demo('My first demo',path)
  //the demo can now be run using the "Demos" menu.

See Also

add_help_chapter ,

Author

Serge Steer , INRIA


add_help_chapter

Scilab Function
Last update : 12/01/2004

add_help_chapter - Add an entry in the helps list

Calling Sequence

add_help_chapter(title,path)

Parameters

  • title : a character string, the help chapter title
  • path : a character string, the path of the directory containing the help files.

Description

This function adds a new entry in the helps list. The help chapter files are to be located in a single directory. If the given title already exists in the helps list associated with the same path nothing is done. The function checks if the directory exist.

See Also

help , add_demo ,

Author

Serge Steer , INRIA


add_palette

Scilab Function
Last update : 26/05/2005

add_palette - Add an entry in the Scicos palettes list

Calling Sequence

add_palette(title,path)

Parameters

  • title : a character string, the palette title
  • path : a character string, the path of the scicos file associated with the palette

Description

This function adds a new entry in the Scicos palettes list. The palette should be executed by a Scilab script file. If the given title already exists in the palette list associated with the same file nothing is done. The function checks if the file exist.

See Also

scicos ,

Author

Serge Steer , INRIA


apropos

Scilab Function
Last update : 19/12/2005

apropos - recherche d'un mot-clé dans l'aide de Scilab

Calling Sequence

apropos(key)
apropos(regexp)

Parameters

  • key : Une chaîne de caractères, la séquence de caractères à rechercher
  • regexp : Une chaîne de caractères, l'expression régulière à rechercher. Cette syntaxe ne fonctionne que le browser "Scilab Browser"

Description

apropos(key) recherche les pages d'aides contenant la séquence de caractères key dans leur section "SHORT_DESCRIPTION".

Avec le "Browser Scilab" uniquement , apropos(regexp) recherche les pages d'aides contenant l'expression régulière donnée par regexp dans leur section "SHORT_DESCRIPTION".

Examples

apropos('ode')
apropos ode
apropos "list of"

// la suite ne fonction qu'avec le browser "Browser Scilab"
global %browsehelp;%browsehelp_save=%browsehelp;%browsehelp="Scilab Browser";

apropos "sin.*hyperbolique"
apropos "^ab"  //rechercher les pages d'aide dont le nom commence par les deux caractères "ab"
apropos "quadratic.*solver"

%browsehelp=%browsehelp_save;

See Also

help , man ,


banner

Fonction Scilab
Last update : 08/06/2005

banner - affiche la baniere scilab

Calling Sequence

banner()

Description

affiche la baniere scilab.

Examples

clc();banner()

Author

Allan CORNET


basename

Scilab Function
Last update : 12/01/2004

basename - strip directory and suffix from filenames

Calling Sequence

files= basename(files[,flag [,flagexpand]])

Parameters

  • files : a string matrix giving a set of file names.
  • flag,flagexpand : boolean optional parameters. (default value %t ).
  • files : a string matrix.

Description

basename return the basename of the file entries given in files.

If flag is true the files are first converted to the target type given by the MSDOS variable. Moreover, if flagexpand is true leading strings like HOME , SCI or ~ are expanded using environment variables.

Note that basename(files,%f) can give erroneous results if pathnames given in files do not follow the convention given by the MSDOS variable.

Examples

files=basename('SCI/macros/util/poo.sci')
files=basename('SCI/macros\util/poo.sci')
files=basename('SCI/macros\util/poo.sci.k')

See Also

listfiles , pathconvert ,


calendar

Fonction Scilab
Last update : 08/06/2005

calendar - Calendrier

Calling Sequence

c = calendar()
c = calendar(y,m)

Description

c = calendar retourne une liste contenant le calendrier pour le mois en cours. Les semaines debutant le Dimanche(Sunday) et se terminant le Samedi(Saturday).

c = calendar(y,m), ou y et sont des entiers, retourne le calendrier pour le mois et l'annee specifie.

Examples

calendar()

calendar(1973,8)

See Also

datevec , datenum ,

Authors

Allan CORNET


chdircd

Scilab Function
Last update : 19/12/2005

chdir - change le répertoire courant de Scilab

cd - change le répertoire courant de Scilab

Calling Sequence

chdir(path)
realpath=cd(path)
cd path

Parameters

  • path : une chaîne de caractères fournissant le chemin du répertoire.
  • realpath : une chaîne de caractères, le chemin effectif après conversion (voir ci-dessous)

Description

Change le répertoire courrant de Scilab par celui donné par la variable path . Notez que le chemin fourni est converti. Ainsi SCI/macros/util est un chemin valide pour Unix et Windows. Si path est vide , le chemin de destination est alors "home".

Examples

    chdir(TMPDIR);
    pwd
    cd
    cd SCI

See Also

getcwd , pwd ,


clc

Foncion Scilab
Last update : 22/04/2004

clc - Efface la fenêtre de commande

Calling Sequence

clc([nblines])

Parameters

  • nblines : une valeur double

Description

clc() efface toutes les entrées et sorties de la fenêtre de commande.

Après avoir utilisé clc() , vous ne pouvez pas utiliser la barre de défilement pour voir l'historique des fonctions, mais vous pouvez encore utiliser le clavier pour rappeler les instructions de l'historique des commandes.

clc(nblines) efface nblines au dessus de la ligne courante du curseur et déplace le curseur jusqu'à cette ligne.

Notez que clc([nblines]) ne peut être utilisé sous Unix/Linux quand Scilab est utilisé en mode sans fenêtre.

See Also

tohome ,

Authors

V.C.


clipboard

Fonction Scilab
Last update : 29/08/2005

clipboard - Copie ou colle une chaine de caracteres dans le presse-papier (Windows).

Calling Sequence

clipboard('copy',data)
str=clipboard('paste')
clipboard('do','paste')
clipboard('do','copy')
clipboard('do','empty')
clipboard(winnum,'EMF')
clipboard(winnum,'DIB')

Description

clipboard('copy',data) copie le contenu de data dans le presse-papier. Si data n'est pas une chaine de caracteres, sci2exp est utilisé pour convertir data en chaine de caracteres.

str = clipboard('paste') retourne le contenu du presse-papier dans la variable str, ou [] si le contenu du presse-papier ne peut etre converti en chaine de caracteres.

clipboard('do','paste') , clipboard('do','copy') , clipboard('do','empty') effectue l'action equivalente au menu Coller, Copier et Vider le presse-papier.

Note : clipboard(...) ne fonctionne que pour Windows et qu'en mode interface graphique.

clipboard(winnum,'EMF') copie, au format EMF, dans le presse papier le graphe correspondant au numero de la fenetre associée.

clipboard(winnum,'DIB') copie, au format DIB, dans le presse papier le graphe correspondant au numero de la fenetre associée.

Authors

A.C.


configure_msvc

Fonction Scilab
Last update : 08/06/2005

configure_msvc - positionne les variables d'environnements necessaire pour pouvoir utiliser le compilateur Microsoft C.

Calling Sequence

bOK=configure_msvc()

Parameters

  • bOK : retourne %T si la mise a jour des variables d'environnement c'est correctement effectuee

Description

positionne les variables d'environnements necessaire pour pouvoir utiliser le compilateur Microsoft C.

Examples

bOK=configure_msvc()

Author

Allan CORNET


console

Fonction Scilab
Last update : 08/06/2005

console - montre ou cache la console (pour Windows)

Calling Sequence

state1=console(state2)
state1=toolbar()

Parameters

  • state1 : retourne l'etat de la console 'on' ou 'off'
  • state2 : 'on' ou 'off' fixe l'etat de la console

Description

montre ou cache la console (pour Windows).

Examples

console('off')
state=console()
console()

Author

Allan CORNET


create_palette

Scilab Function
Last update : 04/02/2005

create_palette - Build Scicos palettes

Calling Sequence

routines = create_palette(Path)
routines = create_palette()

Parameters

  • Path : string, the path of the directory containing the interfacing functions
  • routines : The list of required simulation functions

Description

Without argument create_palette() build all the initial scicos palettes and store then in SCIDIR/macros/scicos/ .
create_palette(Path) build the palette associated with all *.sci files contained in the directory given by Path . The palette file is store in this directory.

N.B. : all *.sci file contained in the directory are assumed to be Scicos interfacing functions

See Also

add_palette ,


c_link

Scilab Function
Last update : 12/01/2004

c_link - check dynamic link

Calling Sequence

c_link(routine-name)
[test,ilib]=c_link(routine-name)
test=c_link(routine-name,num)

Parameters

  • routine-name : a character string
  • num :
  • test : boolean, indicates if there is a shared library which contains routine-name .
  • ilib : a scalar, the number of the shared library which contains routine-name

Description

c_link is a boolean function which checks if the routine routine-name is currently linked. This function returns a boolean value true or false. When used with two return values, the function c_link returns a boolean value in test and the number of the shared library which contains routine-name in ilib (when test is true).

See Also

link , fort ,


datenum

Fonction Scilab
Last update : 12/01/2005

datenum - Convertie une date en un nombre

Calling Sequence

N = datenum()
N = datenum(DT)
N = datenum(Y, M, D)
N = datenum(Y, M, D, H, MI, S)

Description

La fonction datenum convertie une date en un nombre lui correspondant. Ce nombre correspond au nombre de jours passe depuis une date reference. Par defaut, cette date est le 1-Jan-0000.

N = datenum() retourne le nombre correspondant a la date courante.

N = datenum(Y, M, D) retourne le nombre correspondant aux elements Y, M, D (annee, mois, jour).

N = datenum(Y, M, D, H, MI, S) retourne le nombre correspondant aux elements Y, M, D, H, MI, et S (annee, mois, jour, heure, minute, et seconde).

Examples

datenum()

datenum(1973,8,4)

See Also

datevec , calendar ,

Authors

A.C


datevec

Fonction Scilab
Last update : 08/06/2005

datevec - Reconstruction d'un vecteur contenant une Date

Calling Sequence

V=datevec(DT)
[Y,M,D,H,MI,S]=datevec(DT)

Description

V = datevec(DT) convertie un nombre (défini par datenum) en un vecteur contenant une date dont les éléments sont [year, month, day, hour, minute, second].

[Y, M, D, H, MI, S] = datevec(DT) retourne les composants de la date dans 6 variables.

Examples

datevec(720840)

datevec(datenum())

See Also

datenum , calendar ,

Authors

A.C


dec2hex

Scilab Function
Last update : April 1993

dec2hex - représentation hexadécimale d'un entier

Calling Sequence

h=dec2hex(d)

Parameters

  • d : matrice d'entiers positifs
  • h : matrice de chaînes de caractères

Description

dec2hex(x) renvoie la représentation hexadécimale d'une matrice d'entiers.

Examples

dec2hex([2748 10;11 3])


dirname

Scilab Function
Last update : 12/01/2004

dirname - get directory from filenames

Calling Sequence

dirs= dirname(files[,flag [,flagexpand]])

Parameters

  • files : a string matrix giving a set of file names.
  • flag,flagexpand : boolean optional parameters. (default value %t ).
  • files,dir : string matrices.

Description

dirname return the dirname of the file entries given in files.

If flag is true the files are first converted to the target type given by the MSDOS variable. Moreover, if flagexpand is true leading strings like HOME , SCI or ~ are expanded using environment variables.

Note that dirname(files,%f) can give erroneous results if pathnames given in files do not follow the convention given by the MSDOS variable.

Examples

files=dirname('SCI/macros/util/poo.sci')
files=dirname('SCI/macros\util/poo.sci')
files=dirname('SCI/macros\util/poo.sci.k')

See Also

basename , listfiles , pathconvert ,


edit_error

Scilab Function
Last update : 16/11/2004

edit_error - opens in SciPad the source of the last recorded error

Calling Sequence

answ = edit_error(clearerror)

Parameters

  • clearerror : boolean - if true the error condition is cleared, if false it is kept (as in lasterror )
  • answ : a string stating which source file is open (or why no file was open)

Description

This function opens in SciPad the source of the function which caused the last recorded error, and highlights the offending line.

This function works only for functions which are defined in libraries, i.e. not for internal functions, nor with functions defined online, nor loaded with individual getf or getd . This is since Scilab presently retains only the path to libraries and not to individual function sources.

Correspondance between the function name foo and function filename foo.sci is tacitly assumed.

Examples

    acosh abc
    edit_error

See Also

scipad , lasterror , errclear ,

Authors

Enrico Segre


findmsvccompiler

Fonction Scilab
Last update : 08/06/2005

findmsvccompiler - retourne la version du compilateur Microsoft C detecté

Calling Sequence

msvc=findmsvccompiler()

Parameters

  • msvc : retourne 'msvc50','msvc60','msvc70','msvc71','unknown'

Description

retourne la version du compilateur Microsoft C detecté.

Examples

msvc=findmsvccompiler()

Author

Allan CORNET


foo

Scilab function
Last update : 12/01/2004

foo - foo short description

Calling Sequence

[y] = foo(x)

Parameters

  • x : what may be x
  • y : what may be y

Description

A first paragraph which explains what computes the foo function. If you want to emphasis a parameter name then you use the following tag x , if you want to emphasis a part of text inclose it inside theses tags and use theses ones to have a bold font and finally for a type writer style.

A second paragraph... Here is an example of a link to another page : man .

  • first simple paragraph
  • second toto is the french foo...

    • Examples

deff("y=foo(x)","y=x"); // define the foo function as the identity function
foo("toto")

    See Also

    man , apropos ,

    Authors

    B. P.


gethistory

Fonction Scilab
Last update : 12/01/2005

gethistory - retourne dans une matrice de type chaine de caracteres l'historique de scilab.

Calling Sequence

matstr=gethistory()

Parameters

  • matstr

    une matrice de type chaine de caracteres

Description

retourne dans une matrice de type chaine de caracteres l'historique de scilab.

See Also

savehistory , loadhistory , resethistory ,

Authors

A.C


getlongpathname

Fonction Scilab
Last update : 08/06/2005

getlongpathname - retourne le chemin au format nom long (Seulement pour Windows)

Calling Sequence

longpath=getlongpathname(shortpath)
[longpath,bOK]=getlongpathname(shortpath)

Parameters

  • shortpath : Une chaine de caracteres contenant le chemin au format court
  • longpath : Une chaine de caracteres contenant le chemin au format long.
  • bOK : retourne %T si le chemin a ete converti ou %F dans le cas contraire.

Description

La primitive getlongpathname convertie le chemin au format court en un nom de chemin au format long.

Examples

[longpath,bOK]=getlongpathname(SCI)

See Also

getshortpathname ,

Author

Allan CORNET


getmemory

Scilab Function
Last update : 06/10/2005

getmemory - returns free and total system memory

Calling Sequence

[free, total]=getmemory()

Description

getmemory() returns free system memory (kilo-octets).

[free, total]=getmemory() returns free and total system memory (kilo-octets).

Authors

A.C


getos

Fonction Scilab
Last update : 08/06/2005

getos - retourne le nom et la version de O.S

Calling Sequence

OS=getos()
[OS,Version]=getos()

Description

getos retourne le nom et la version de O.S

Examples

OS=getos()
[OS,version]=getos()

Author

A.C


getscilabkeywords

Scilab Function
Last update : 04/10/2005

getscilabkeywords - returns a list with all scilab keywords.

Calling Sequence

list_keywords=getscilabkeywords()

Parameters

  • list_keywords : a list

Description

list_keywords(1) : primitives

list_keywords(2) : commands

list_keywords(3) : predef variables

list_keywords(4) :scilab functions

list_keywords(5) :scicos functions

Author

A.C


getshell

Fonction Scilab
Last update : 24/01/2006

getshell - retourne le nom de l'interpreteur de commandes.

Calling Sequence

getshell()

Description

getshell : retourne le nom de l'interpreteur de commandes.

Examples

    getshell()

Author

Allan CORNET


getshortpathname

Fonction Scilab
Last update : 08/06/2005

getshortpathname - retourne le chemin au format court (Seulement pour Windows)

Calling Sequence

shortpath=getshortgpathname(longpath)
[shortpath,bOK]=getshortpathname(longpath)

Parameters

  • longpath : Une chaine de caractere contenant le chemin au format long.
  • shortpath : Une chaine de caractere contenant le chemin au format court
  • bOK : contient %T si le chemin a ete converti ou %F si ce n'est pas le cas.

Description

La primitive getshortpathname convertie un chemin au format long en un chemin au format court.

Examples

[shortpath,bOK]=getshortpathname(SCI)

See Also

getlongpathname ,

Author

Allan CORNET


head_comments

Scilab Function
Last update : 17/06/2004

head_comments - display scilab function header comments

Calling Sequence

head_comments(name)
head_comments(name,%paths)

Parameters

  • name : character string, the function name
  • %paths : character string vector, paths where to look for the asscoated sci-file

Description

comments(name) displays the function header comments (like the Matlab help). The comments are read from the associated sci-file. If name if a function in a library the sci-file path is those given by the library path (see lib ). If name if a function which is not in a library, a file with name name.sci is searched in the directories given by the variable %paths .

Warning, most of the scilab predefined functions have no header comments.

Examples

    head_comments sinc

See Also

help ,

Author

Serge Steer, INRIA


help_skeleton

Scilab Function
Last update : 28/05/2004

help_skeleton - build the skeleton of the xml help file associated to a Scilab function

Calling Sequence

txt = help_skeleton(funname [,path])

Parameters

  • funname : character string : the name of the function
  • path : character string : the path where the file will be create if required. If this argument is not given the skeleton is returned as a string.
  • txt : the XML code or the complete xml file path

Description

txt = help_skeleton(funname) generates a vector of strings containing the skeleton of the XML code describing the help of the function funname .

fullpath = help_skeleton(funname,dirpath) generates the XML code describing the help of the function funname in a file named funname.xml in the directory specified by the path dirpath . In this case the function returns the file path.

Examples

   function [y,z]=foo(a,b),y=a+b,z=1,endfunction
    p=help_skeleton('foo',TMPDIR)
    scipad(p)

See Also

help ,

Author

Serge Steer, INRIA


help

Scilab Function
Last update : 20/11/2006

help - commande d'aide en ligne

Calling Sequence

help(key)

Parameters

  • key : Une chaîne de caractères. Donne le nom de la page d'aide à visualiser.

Description

help sans argument, visualise la page hypertexte contenat la liste des chapitres d'aide.

help(key) visualise la page d'aide associé avec le nom donné par key . S'il n'y a pas de page d'aide, help(key) appele automatiquement apropos(key) .

Scilab comprend son propre browser html écrit en TCL/TK. Il est possible de choisir un autre browser. La variable globale %browsehelp contient une chaîne de caractères définissant quel browser doit être utilisé. Sa valeur initiale est fixée par le fichier startup SCIHOME/.scilab ou SCIHOME/scilab.ini est peut être changée.

Si cette variable est affectée à la matrice vide ( global %browsehelp; %browsehelp=[] ) alors une fenêtre de dialogue apparait au lancement du help et permet de choisir le browser désiré. Attention, les differents browsers on des synatxes d'appel différentes. Aussi si vous souhaitez ajouter un nouveau browser à la liste vous devrez modifier la fonction Scilab browsehelp dont le code source est dans SCI/macros/util/browsehelp.sci .

Voir man pour apprendre à écrire de nouvelles pages d'aide.

See Also

apropos , man ,


hex2dec

Scilab Function
Last update : 12/01/2004

hex2dec - conversion from hexadecimal representation to integers

Calling Sequence

d=hex2dec(h)
d=oct2dec(o)
d=base2dec(s,b)

Parameters

  • d : matrix of integers
  • h : matrix of character strings corresponding to hexadecimal representation
  • o : matrix of character strings corresponding to octal representation
  • s : matrix of character strings corresponding to base b representation
  • b : integer, the base

Description

hex2dec(x) returns the matrix of numbers corresponding to the hexadecimal representation.

oct2dec(x) returns the matrix of numbers corresponding to the octal representation.

base2dec(x,b) returns the matrix of numbers corresponding to the base b representation.

Examples

hex2dec(['ABC','0','A'])


ilib_build

Scilab Function
Last update : 12/01/2004

ilib_build - utility for shared library management

Calling Sequence

ilib_build(lib_name,table,files,libs [,makename,ldflags,cflags,fflags])

Parameters

  • lib_name : a character string, the generic name of the library without path and extension.
  • table : 2 column string matrix giving the table of pairs 'scilab-name', 'interface name'
  • files : string matrix giving objects files needed for shared library creation
  • libs : string matrix giving extra libraries needed for shred library creation
  • makename : character string. The path of the Makefile file without extension.
  • ldflags,cflags,fflags : character strings to provide options for the loader, the C compiler and the Fortran compiler.

Description

This tool is used to create shared libraries and to generate a loader file which can be used to dynamically load the shared library into Scilab with addinter

Many examples are provided in examples/interface-tour-so directory.

Examples

//Here with give a complete example on adding new primitive to Scilab
//create the procedure files
f1=['extern double fun2();'
    'void fun1(x,y)'
    'double *x, *y;'
    '{*y=fun2(*x)/(*x);}'];

mputl(f1,'fun1.c')

f2=['#include <math.h>'
    'double fun2(x)'
    'double x;'
    '{ return( sin(x+1.));}'];
mputl(f2,'fun2.c');

//creating the interface file
i=['#include ""stack-c.h""'
   'extern int fun1 _PARAMS(( double *x, double *y));'
   'int intfun1(fname)'
   'char * fname;'
   '{'
   '  int m1,n1,l1;'
   '  CheckRhs(1,1);'
   '  CheckLhs(1,1);'
   '  GetRhsVar(1, ""d"", &m1, &n1, &l1);'
   '  fun1(stk(l1),stk(l1));'
   '  LhsVar(1) = 1;'
   '  return 0;'
   '}'];
mputl(i,'intfun1.c')

//creating the shared library (a gateway, a Makefile and a loader are
//generated.

files=['fun1.o','fun2.o','intfun1.o'];
ilib_build('foo',['scifun1','intfun1'],files,[]);

// load the shared library

exec loader.sce

//using the new primitive
scifun1(33)

See Also

addinter , link , ilib_compile , ilib_gen_Make , ilib_gen_gateway , ilib_gen_loader , ilib_for_link ,


ilib_compile

Scilab Function
Last update : 26/05/2005

ilib_compile - ilib_build utility: executes the makefile produced by ilib_gen_Make

Calling Sequence

libn=ilib_compile(lib_name,makename [,files])

Parameters

  • lib_name : a character string, the generic name of the library without path and extension.
  • makename : character string. The path of the Makefile file without extension.
  • files : optionnal vector of character strings. If files is given the make is performed on each target contained in files then a whole make is performed
  • libn : character string. The path of the really generated shared library file.

Description

Utility function used by ilib_build

This executes the makefile produced by ilib_gen_Make , compiles the C and fortran files and generates the shared library.

Shared libraries can then be used with the link and addinter scilab function for incremental linking.

See Also

addinter , link , ilib_build , ilib_gen_Make , ilib_gen_gateway , ilib_gen_loader , ilib_for_link ,


ilib_for_link

Scilab Function
Last update : 29/06/2005

ilib_for_link - utility for shared library management with link

Calling Sequence

libn=ilib_for_link(names,files,libs,flag [,makename [,loadername [,libname [,ldflags [,cflags [,fflags [,cc]]]]]]])

Parameters

  • names : a string matrix giving the entry names which are to be linked.
  • files : string matrix giving objects files needed for shared library creation
  • libs : string matrix giving extra libraries needed for shred library creation
  • flag : a string flag ("c" or "f") for C or Fortran entry points.
  • makename : character string. The pathname of the Makefile file without extension (default value Makelib ).
  • loadername : character string. The pathname of the loader file (default value is loader.sce ).
  • libname : optional character string. The name of the generated shared library (default value is '', and in this case the name is derived from names(1) ).
  • ldflags : optional character string. It can be used to add specific linker options in the generated Makefile. Default value is ''
  • cflags : optional character string. It can be used to add specific C compiler options in the generated Makefile. Default value is ''
  • fflags : optional character string. It can be used to add specific Fortran compiler options in the generated Makefile. Default value is ''
  • cc : optional character string. It can be used to specify a C compiler. Default value is ''
  • libn : character string. The path of the really generated shared library file.

Description

This tool is used to create shared libraries and to generate a loader file which can be used to dynamically load the shared library into Scilab with the link function. New entry points given by names are then accessible through the call function or with non linear tools ode , optim ,...

The file to compile are supposed to be located given by makename . If makename sets a path different to the current directory, loader script must be located in the same directory using the loadername variable.

Many examples are provided in examples/link-examples-so directory.

Examples

f1=['int ext1c(n, a, b, c)'
    'int *n;     double *a, *b, *c;'
    '{int k;'
    '  for (k = 0; k < *n; ++k) '
    '      c[k] = a[k] + b[k];'
    '  return(0);}'];

mputl(f1,'fun1.c')

//creating the shared library (a gateway, a Makefile and a loader are
//generated.

ilib_for_link('ext1c','fun1.o',[],"c")

// load the shared library

exec loader.sce

//using the new primitive
a=[1,2,3];b=[4,5,6];n=3;
c=call('ext1c',n,1,'i',a,2,'d',b,3,'d','out',[1,3],4,'d');
if norm(c-(a+b)) > %eps then pause,end

See Also

addinter , link , ilib_compile , ilib_gen_Make , ilib_gen_gateway , ilib_gen_loader , ilib_for_link ,


ilib_gen_gateway

Scilab Function
Last update : 12/01/2004

ilib_gen_gateway - utility for ilib_build, generates a gateway file.

Calling Sequence

ilib_gen_gateway(name,table)

Parameters

  • name : a character string, the generic name of the library without path and extension.
  • table : 2 column string matrix giving the table of pairs 'scilab-name' 'interface name'

Description

Utility function used by ilib_build This function generates a gateway file used by addinter .

See Also

addinter , link , ilib_build , ilib_compile , ilib_gen_Make , ilib_gen_loader , ilib_for_link ,


ilib_gen_loader

Scilab Function
Last update : 12/01/2004

ilib_gen_loader - utility for ilib_build: generates a loader file

Calling Sequence

ilib_gen_loader(name,table)

Parameters

  • name : a character string, the generic name of the library without path and extension.
  • table : 2 column string matrix giving the table of pairs 'scilab-name' 'interface name'

Description

Utility function used by ilib_build This function generates a loader file.

See Also

addinter , link , ilib_build , ilib_compile , ilib_gen_Make , ilib_gen_loader , ilib_for_link ,


ilib_gen_Make

Scilab Function
Last update : 26/05/2005

ilib_gen_Make - utility for ilib_build : produces a makefile for building shared libraries

Calling Sequence

Makename=ilib_gen_Make(name,files,libs,makename [,with_gateway,ldflags,cflags,fflags])

Parameters

  • lib_name : a character string, the generic name of the library without path and extension.
  • files : a vector of character string. The names of the C or Fortran files without the extension and the path part.
  • libs : a vector of character string. additionnal libraries paths or [].
  • makename : character string. The path of the Makefile file.
  • with_gateway : a boolean. If true a file with name <lib_name>_gateway is added. Default value is %t
  • ldflags : a string. It can be used to add specific linker options in the generated Makefile. Default value is ''
  • cflags : a string. It can be used to add specific C compiler options in the generated Makefile. Default value is ''
  • fflags : a string. It can be used to add specific Fortran compiler options in the generated Makefile. Default value is ''
  • Makename : character string. The path of the really generated Makefile file.

Description

Utility function used by ilib_build

This function generates a makefile adapted to the Operating System for building shared libraries to be loaded in Scilab. Proper options and paths are set.

Shared libraries can then be used with the link and addinter scilab function for incremental linking.

The shared library is build from a set of C or Fortran routines stored in a directory and if required from a set of external libraries.

Files are not required to exist, when makefile is generated, but of course are required for executing the makefile.

See Also

addinter , link , ilib_build , ilib_compile , ilib_gen_gateway , ilib_gen_loader , ilib_for_link ,


intersci

Scilab Tool
Last update : 12/01/2004

intersci - scilab tool to interface C of Fortran functions with scilab

Description

All scilab primitive functions are defined in a set of interface routines. For each function the interfacing code checks first number of rhs and lhs arguments. Then it get pointers on input arguments in the Scilab data base and checks their types. After that it calls procedure associated with Scilab functions, checks returned errors flags and set the results in the data base.

intersci \ is a program which permits to interface automatically FORTRAN subroutines or C functions to Scilab

With intersci , a user can group all his FORTRAN or C code into a same set, called an interface, and use them in Scilab as Scilab functions. The interfacing is made by creating a FORTRAN subroutine which has to be linked to Scilab together with the user code. This complex FORTRAN subroutine is automatically generated by intersci \ from a description file of the interface.

Refer to intersci documentation for more details.

See Also

fort , external , addinter ,


LANGUAGE

Scilab Variable
Last update : 16/06/2004

LANGUAGE - Variable qui définit la langue

Description

La variable globale LANGUAGE est une chaîne de caractères. Elle définit la langue pour l'aide en ligne et divers menus. Actuellement, les valeurs de LANGUAGE peuvent être "fr" pour le français, c'est le défaut, ou "eng" pour l'anglais.

Cette variable est définie dans le fichier d'initialisation scilab.star . On peut la changer là.

Quand on lance Scilab, on peut donner la valeur de la langue comme argument : scilab -l <language> pour Unix et runscilab.exe -l <language> pour Windows.


link

Scilab Function
Last update : 07/03/2006

link - incremental linker

Calling Sequence

x=link(files [, sub-names,flag]);
link(x , sub-names [, flag]);
ulink(x)
lst=link('show')

Parameters

  • files : a character string or a vector of character strings, the files names used to define the new entry point (compiled routines, user libraries, system libraries,..)
  • sub-names : a character string or a vector of character strings . Name of the entry points in files to be linked.
  • x : an integer which gives the id of a shared library linked into Scilab with a previous call to link .
  • flag : character string 'f' or 'c' for Fortran (default) or C code.

Description

link is a incremental link facility based on the dld library: this command allows to add new compiled Fortran or C routines to Scilab executable code. Linked routines can be called interactively by the function fort . Linked routines can also be used as "external" for e.g. non linear problem solvers ( ode , optim , intg , dassl ...).

a call to link returns an integer which gives the id of the shared library which is loaded into Scilab. This number can then be used as the first argument of the link function in order to link additional function from the linked shared library. The shared library is removed with the ulink command.

A routine can be unlinked with ulink . If the linked function has been modified between two links, it is required to ulink the previous instance before the new link.

link('show') returns the current linked routines.

To be able to link routines in a system independent way, it is convenient to use the ilib_for_link utility function instead of link .

(Experienced) users may also link a new Scilab interface routine to add a set of new functions. See intersci documentation for interface generation and ilib_build and addinter functions.

Examples

    //Example of the use of ilib_for_link with  a simple C code
    f1=['#include <math.h>'
    'void fooc(c,a,b,m,n)'
    'double a[],*b,c[];'
    'int *m,*n;'
    '{'
    '   int i;'
    '   for ( i =0 ; i < (*m)*(*n) ; i++) '
    '     c[i] = sin(a[i]) + *b; '
    '}'];

    mputl(f1,'fooc.c')

    //creating the shared library: a Makefile and a loader are
    //generated, the code is compiled and a shared library built.
    ilib_for_link('fooc','fooc.o',[],"c")

    // display the loader.sce file which calls link
    mprintf('%s\n',mgetl('loader.sce'))
    // load the shared library
    exec loader.sce

    link('show')
    // call the new linked entry point
    a=linspace(0,%pi,10);b=5;
    y1=call('fooc',a,2,'d',b,3,'d',size(a,1),4,'i',size(a,2),5,'i','out',size(a),1,'d')
    // check
    y1-(sin(a)+b)

See Also

call , external , c_link , addinter , ilib_for_link , ilib_build ,


listfiles

Scilab Function
Last update : 12/01/2004

listfiles - list files

Calling Sequence

files= listfiles(paths [,flag,flagexpand])

Parameters

  • paths : a string matrix giving a set of pathnames (eventually ended by a pattern built with * )
  • flag,flagexpand : boolean optional parameters. (default value %t ).
  • files : a string matrix.

Description

listfiles can be used to list the files which match the patterns given by one of the paths entries. Patterns are given to the unix ls or to the windows dir commands in order to get information on files. Thus in order to write portable Scilab script valid wildcard patterns for both os are to be given. Note that Pathname conversion is performed and for example SCI/macros/util/*.sci is a valid pattern for both unix and windows.

if flag is true the pathnames given by paths are converted according to the MSDOS value (See pathconvert ). Moreover, if flagexpand is true leading strings like HOME , SCI or ~ are expanded using environment variables.

Examples

files=listfiles(['SCI/macros/util/*.sci';'SCI/macros/util/*.bin']);

See Also

basename , pathconvert ,


loadhistory

Fonction Scilab
Last update : 12/01/2005

loadhistory - charge un fichier contenant l'historique

Calling Sequence

loadhistory()
loadhistory(f)

Parameters

  • f : chemin du fichier à charger

Description

charge un fichier contenant l'historique

Par défaut, le nom du fichier contenant l'historique est home+'/history.scilab'

Examples

loadhistory(SCI+'/session.scilab')

See Also

savehistory , resethistory , gethistory ,

Authors

A.C


make_index

Scilab Function
Last update : 12/01/2004

make_index - creates a new index file for on-line help

Calling Sequence

make_index()

Description

The on-line help reads first the index.html file which contains the list of the chapters. This file comes with Scilab and is in the directory SCIDIR/man/<language> (see man ). It is possible to change this index file while interactively adding new chapters. For that, modify the %helps variable and then use the make_index function.

See Also

%helps , man ,


man

Scilab Format
Last update : 05/07/2005

man - on line help XML file description format

Description

The on line help source files are written in XML.

Source files (with extension .xml) can be found in the <SCIDIR>/man/<language>/* directories. The file name is usually associated to a keyword (corresponding to a function name most of the cases) it describes.

A few words about XML

An XML file resembles to an HTML file but with both a more rigid and free syntax. Free because you may build your own tags: the set of tags together with its rules must be described somewhere, generally in another file ( <SCIDIR>/man/manrev.dtd for scilab), and rigid because, once the tags and rules are defined (which are called the Definition Type Document: DTD) , you must respect its (in particular to every open tags <MY_TAG> must correspond a closed </MY_TAG> ).

The DTD manrev.dtd is written in SGML and precises the exact syntax required by a scilab XML help page. So if you know this language you may red this file. The following annotated example (see the next section) shows you some possibilities offered by this DTD and may be enough to write simple help pages.

Once an XML page is written and conforms to the DTD, it may be transformed in HTML to be red by your favorite browser or by the tcltk scilab browser (see section browser choice in this page). The XML -> HTML translation is controled by a set of rules written in the (XML) file <SCIDIR>/man/language/html.xsl . Those rules are currently more or less restricted to fit the tcltk scilab browser features (which may display correctly only basic HTML): if you use a real HTML browser and want a better appearance you have to modify this file.

How to write a simple xml scilab help page: the lazzy way

If one want to write the xml file associated to a new scilab function he or she may use the Scilab function help_skeleton to produce the skeleton of the xml file. In most cases the user will not be required to know xml syntax.

How to write a simple xml scilab help page: an example

Here is a simple annotated XML scilab help page which describes an hypothetic foo scilab function. In the following, the XML file is displayed in a type writer font and cut-out in several parts, each part being preceded by some associated explanations. The entire XML file foo.xml is in the <SCIDIR>/man/eng/utility directory and the result may be displayed by clicking on foo . (you may found others examples in the <SCIDIR>/examples/man-examples-xml directory). Finally note that some tag pairs <TAG> , </TAG> have been renamed here <ATAG> , </ATAG> . This is because some scilab scripts which do some work on or from the xml files don't verify if a tag is inside a VERBATIM entry.

The 3 first lines of the file are mandatory, the second precises the path to the DTD file and the third, formed by the <MAN> tag, begin the hierarchical description (the file must finish with the </MAN> tag). The 4 followings entries : LANGUAGE , TITLE , TYPE and DATE , are also mandatory (in this order) the text corresponding to <TYPE> being generally 'Scilab function' (most of the cases) but may be simply 'Scilab keyword' or 'Scilab data type', ..., depending of what explains the help page.

       <?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
       <!DOCTYPE MAN SYSTEM "<SCIDIR>/man/manrev.dtd">
       <MAN>
          <LANGUAGE>eng</LANGUAGE>
          <TITLE>foo</TITLE>
          <TYPE>Scilab function</TYPE>
<DATE>05/07/2005</DATE>

The first of these 2 following entries ( SHORT_DESCRIPTION ) is mandatory and important since the words of the short description text, are used by the apropos command to search help pages from a keyword: the short description is used to build the whatis.html file corresponding to your toolbox and the apropos keyword command looks in all the whatis files and then proposes the links to every page containing the word keyword in its short description (in fact the actual associated tags are <SHORT_DESCRIPTION> and </SHORT_DESCRIPTION> and not <ASHORT_DESCRIPTION> and </ASHORT_DESCRIPTION> ). The next entry ( CALLING_SEQUENCE ) must be used if you describe a function (but is not strictly mandatory). If your function have several calling sequences use several CALLING_SEQUENCE_ITEM entries.

          <ASHORT_DESCRIPTION name="foo">foo short description</ASHORT_DESCRIPTION>
          <CALLING_SEQUENCE>
              <CALLING_SEQUENCE_ITEM>[y] = foo(x)</CALLING_SEQUENCE_ITEM>
          </CALLING_SEQUENCE>

The following entry ( PARAM ) is not strictly mandatory but is the good one to describe each parameters (input and output) in case of a function.

          <PARAM>
             <PARAM_INDENT>
                <PARAM_ITEM>
                   <PARAM_NAME>x</PARAM_NAME>
                   <PARAM_DESCRIPTION>
                      <SP>: what may be x</SP>
                   </PARAM_DESCRIPTION>
                </PARAM_ITEM>
                <PARAM_ITEM>
                   <PARAM_NAME>y</PARAM_NAME>
                   <PARAM_DESCRIPTION>
                      <SP>: what may be y</SP>
                   </PARAM_DESCRIPTION>
                </PARAM_ITEM>
             </PARAM_INDENT>
          </PARAM>

The DESCRIPTION entry is perhaps the most significant one (but not strictly mandatory) and may be more sophisticated than in this example (for instance you may have DESCRIPTION_ITEM sub-entries). Here you see how to write several paragraphes (each one enclosed between the <P> and </P> tags), how to emphasis a variable or a function name (by enclosing it between the <VERB> and </VERB> tags), how to emphasis a part of text ( <EM> or <BD> and <TT> to put it in a type writer font)), and finally, how to put a link onto another help page (in fact the actual associated tags are <LINK> and </LINK> and not <ALINK> and </ALINK> ).

         <DESCRIPTION>
             <P>
                A first paragraph which explains what computes the foo function.
                If you want to emphasis a parameter name then you use the following
                tag <VERB>x</VERB>, if you want to emphasis a part of text
                <EM>inclose it inside theses tags</EM> and use theses ones
                <BD>to have a bold font</BD> and finally <TT>for a type writer style</TT>.
             </P>
             <P>
                A second paragraph... Here is an example of a link to another page :
                <ALINK>man</ALINK>.
             </P>
         </DESCRIPTION>

Here is how to write your own entry, for instance to describe some outside remarks and/or notes about your wonderful function.

         <SECTION label='Notes'>
             <P>
                Here is a list of notes :
             </P>
             <ITEM label='first'><SP>blablabla...</SP></ITEM>
             <ITEM label='second'><SP>toto is the french foo...</SP></ITEM>
         </SECTION>

An important entry is the EXAMPLE one which is reserved to show scilab uses of your function (begin with simple ones !). Note that you must close this entry with ]]></EXAMPLE> and not like here with }}></EXAMPLE> (once again this is a bad trick to avoid some interpretation problems).

         <EXAMPLE><![CDATA[
             deff("y=foo(x)","y=x"); // define the foo function as the identity function
             foo("toto")
      }}></EXAMPLE>

This last part explains how to put the links onto others related help pages (as said before the good tags are in fact <LINK> and </LINK> and not <ALINK> and </ALINK> ) and finally how to reveal your name if you want (use one AUTHOR_ITEM entry by author). Perhaps it is a good idea to put an email adress if you look for bug reports !

         <SEE_ALSO>
           <SEE_ALSO_ITEM> <ALINK>man</ALINK> </SEE_ALSO_ITEM>
           <SEE_ALSO_ITEM> <ALINK>apropos</ALINK> </SEE_ALSO_ITEM>
         </SEE_ALSO>

         <AUTHOR>
           <AUTHOR_ITEM>B. P.</AUTHOR_ITEM>
         </AUTHOR>
       </MAN>

How to create an help chapter

Create a directory and write down a set of xml files build as described above. Then start Scilab and execute xmltohtml(dir) , where dir is a character string giving the path of the directory (see xmltohtml for more details) .

How to make Scilab know a new help chapter

This can be done by the function add_help_chapter .

Examples

    function y=foo(a,b,c),y=a+2*b+c,endfunction
    path=help_skeleton('foo',TMPDIR)
    scipad(path)

See Also

apropos , help , help_skeleton ,


mkdir

Fonction Scilab
Last update : 10/02/2006

mkdir - Crée un nouveau répertoire

Calling Sequence

mkdir('dirname')
mkdir('parentdir','newdir')
status=mkdir( ... )
[status,msg]=mkdir( ... )

Description

mkdir('dirname') crée le repertoire dirname dans le répertoire courant.

mkdir('parentdir','dirname') crée le répertoire dirname dans le répertoire existant parentdir , ou parentdir est un chemin relatif ou absolu.

[status,message] = mkdir(...,'dirname') crée le répertoire dirname dans le répertoire existant parentdir , retourne le status, et un message. Ici, status vaut 1 si tout c'est bien passé, 2 si le repertoire existe déjà, 0 dans un autre cas.

Examples

rmdir(SCI + '/Directory'); //détruit le répertoire s'il existe
mkdir(SCI,'Directory')
status=mkdir(SCI,'Directory')
[status,msg] = mkdir(SCI,'Directory')
rmdir(SCI+'/Directory')

See Also

cd , dir , rmdir ,

Authors

A.C


pathconvert

Scilab Function
Last update : 12/01/2004

pathconvert - pathnames convertion between posix and windows.

Calling Sequence

paths=pathconvert(paths [,flagtrail [,flagexpand [,type]]])

Parameters

  • paths : a string matrix giving a set of pathnames
  • flagtrail,flagexpand : boolean optional parameters (default value depends on the MSDOS variable).
  • type : a string 'u' or 'w' .

Description

pathconvert can be used to convert a set of pathnames (given by a string matrix paths ) from windows native filename to posix-style pathnames and back. The target style is given by the optional string type which can be 'u' for Unix or 'w' for Windows. The default style is set according to the value of MSDOS . If MSDOS is true (resp. false ) then default type is 'w' (resp. 'u' ).

Windows pathnames starting with name: are converted to pathnames starting with /cygdrive/name/ using the cygwin convention.

flagtrail is an optional boolean parameter. When its value is true a trailing separator ( '\' or '/' ) is added at the end of the path.

flagexpand is an optional boolean parameter. When its value is true leading strings like HOME , SCI or ~ are expanded using environment variables.

Examples

pathconvert('SCI/macros\util/foo.sci',%f,%f,'u')
pathconvert('SCI/macros\util/foo.sci',%f,%f,'w')
pathconvert('SCI/macros/util/foo.sci',%f,%t,'w')
pathconvert('HOME/macros/util/foo.sci',%t,%t,'w')
pathconvert('c:/tmp',%f,%t,'u')
pathconvert('/cygdrive/c/tmp',%f,%f,'w')

See Also

basename , listfiles ,


%helps

Scilab Function
Last update : 20/11/2006

%helps - variable contenant les noms des répertoires des chapitres d'aide

Description

%helps est une matrice de chaînes de caractères à deux colonnes. Chaque ligne est formée comme ceci

répertoire_du_chapitre    titre_du_chapitre

Par exemple, nous avons le chapitre "graphics". %helps(2,:) .

La valeur par défaut de %helps est initialisée dans le fichier SCI+"scilab.star" .

Pour ajouter de nouveaux chapitres d'aide il suffit d'ajouter des lignes à la variable %helps , par exemple dans le fichier utilisateur de démarrage SCIHOME/.scilab .

Par exemple, %helps=[%helps; "répertoire_du_chapitre", "titre_du_chapitre"];

"titre_du_chapitre" devient le titre d'un nouveau chapitre.

Chaque répertoire d'aide contient des fichiers *.html , généralement généré à partir d'un fichier XML, et un fichier whatis.html contenant une ligne pour chaque mot-clé documenté dans le chapitre correspondant. Chaque ligne doit avoir le format :

<BR><A HREF="item.html">item</A> - description rapide

item est l'article de la liste d'aide, c'est-à-dire que la commande help item affiche le contenu du fichier item.html .

La commande apropos mot-clé renvoie les lignes de tous les fichiers whatis dans lesquels mot-clé apparaît.

Sur les plates-formes Linux, Scilab dispose d'un Makefile pour transformer les fichiers .xml en .html (voir SCI/examples/man-examples).

See Also

help , apropos ,


perl

Fonction Scilab
Last update : 12/01/2005

perl - execute le script Perl.

Calling Sequence

perl('perlfile')
perl('perlfile',arg1,arg2,...)
result = perl(...)

Description

perl('perlfile') appelle le script Perl perlfile.

perl('perlfile',arg1,arg2,...) appelle le script Perl perlfile et passe les arguments arg1, arg2, ..., à perlfile.

result = perl(...) retourne le resultat du script Perl.

See Also

unix ,

Authors

A.C


printsetupbox

Fonction Scilab
Last update : 04/08/2005

printsetupbox - Display print dialog box (Windows)

Calling Sequence

printsetupbox()
bOK=printsetupbox()

Description

bOK=printsetupbox() displays the built-in printing dialogbox for Windows and configure the printer. returns %T if you push 'OK' button

See Also

toprint ,

Authors

A.C


realtimeinitrealtime

Scilab Function
Last update : 12/01/2004

realtimeinit - set time unit

realtime - set dates origin or waits until date

Calling Sequence

realtimeinit(time_unit)
realtime(t)

Parameters

  • time_unit : a real number. The number of seconds associated to the realtime argument
  • t : a real number. A date

Description

These two functions can be used to handle real time into Scilab.

realtimeinit(time_unit) defines the time unit associated to the realtime argument t

first call to realtime(t0) sets current date to ( t0 ). subsequent calls to realtime(t) wait till date t is reached.

Examples

   realtimeinit(1/2);//sets time unit to half a second
   realtime(0);//sets current date to 0
   for k=1:10,realtime(k);mprintf('current time is '+string(k/2)+'sec .\r\n');end

  //next instruction outputs a dot each 2 seconds
   realtimeinit(2); realtime(0);for k=1:10,realtime(k);mprintf('.\r\n');end

   realtimeinit(1);realtime(0);
   dt=getdate('s'); realtime(10);   getdate('s')-dt

See Also

getdate ,


resethistory

Fonction Scilab
Last update : 12/01/2005

resethistory - Efface toutes les entrées dans l'historique courant.

Calling Sequence

resethistory()

Description

Efface toutes les entrées dans l'historique courant.

See Also

savehistory , loadhistory ,

Authors

A.C


rmdir

Fonction Scilab
Last update : 08/06/2005

rmdir - Supprime un repertoire

Calling Sequence

rmdir('dirname')
rmdir('dirname','s')
[status,message] = rmdir('dirname','s')

Description

rmdir('dirname') supprime le repertoire dirname depuis le repertoire courant. Si le repertoire n'est pas vide, vous devez utiliser l'argument s. Si dirname n'est pas dans le repertoire courant , vous devez specifier le chemin relatif ou complet pour acceder a dirname.

rmdir('dirname','s') suppprime le repertoire dirname depuis le repertoire courant et ses sous repertoires ainsi que leurs contenus.

[status, message] = rmdir('dirname','s') supprime le repertoire dirname et son contenu depuis le repertoire courant et retourne la variable status et un message. Ici, status vaut 1 si l'execution s'est bien passé et 0 en cas d'erreur.

Examples

mkdir(SCI,'Directory')
rmdir(SCI+'/Directory')

See Also

cd , dir , mkdir ,

Authors

A.C


savehistory

Fonction Scilab
Last update : 12/01/2005

savehistory - sauvegarde l'historique de scilab dans un fichier.

Calling Sequence

savehistory()
savehistory(f)

Parameters

  • f : chemin du fichier dans lequel sera sauvegardé l'historique de scilab

Description

sauvegarde l'historique de scilab dans un fichier.

Par défaut, l'historique est sauvegardé dans home+'/history.scilab'

Examples

savehistory(SCI+'/session.scilab')

See Also

loadhistory , resethistory , gethistory ,

Authors

A.C


sci2exp

Scilab Function
Last update : April 1993

sci2exp - convertit une expression ou une instruction d'affectation en une chaîne

Calling Sequence

t=sci2exp(a [,nam] [,lmax])

Parameters

  • a : une expression Scilab de type
  • nam : chaîne de caractères
  • t : vecteur de chaînes de caractères, contenant l'instruction ou l'expression
  • lmax : entier, longueur maximum d'une ligne (90 par défaut. lmax=0 signifie qu'il n'y pas de contrôle de taille, et sci2exp ne renvoie dans ce cas qu'une seule ligne).

Description

sci2exp évalue une expression et renvoie le résultat dans une chaîne de caractères. Si nam est précisé, la chaîne contient une instruction d'affectation de ce résultat à la variable dont le nom est donné dans nam .

Examples

  a=[1 2;3 4]
  sci2exp(a,'aa')
  sci2exp(a,'aa',0)
  sci2exp(ssrand(2,2,2))
  sci2exp(poly([1 0 3 4],'s'),'fi')


sci2map

Scilab Function
Last update : April 1993

sci2map - conversion de variables Scilab vers Maple

Calling Sequence

txt=sci2map(a,Map-name)

Parameters

  • a : objet Scilab (matrice, polynôme, liste, chaîne)
  • Map-name : chaîne de caractères (nom de la variable Maple)
  • txt : vecteur de chaînes de caractères contenant le code Maple

Description

Génère le code Maple nécessaire pour envoyer la variable Scilab a vers Maple : le nom de la variable dans Maple est Map-name . Une procédure Maple maple2scilab se trouve dans le dossier SCIDIR/maple .

Examples

txt=[sci2map([1 2;3 4],'a');
     sci2map(%s^2+3*%s+4,'p')]


scilab

Scilab Function
Last update : 20/11/2006

scilab - script principal d'exécution de Scilab et de divers outils

Calling Sequence

scilab <Options>

Description

-args arguments: si cette option est présente des arguments sont passés à Scilab. Ils peuvent être récupérés par la fonction sciargs . Les arguments multiples doivent être passés dans chaîne de caractères les contenant, séparés par des espaces scilab -args 'foo1 foo2';
-display Display: Cette option n'est valide que pour les version basées sur Xwindow, elle peut alors être utilisée pour specifier un server X. La valeur par défaut est unix:0.0

-display peut être remplacé par -d

-debug: Lance Scilab sous gdb (Unix/linux seulement).
-e Instruction: si cette option est présente l'instruction Instruction est exécutée dans Scilab immédiatement après les fichiers startup.
-f File: si cette option est présente le script File est exécuté dans Scilab mmédiatement après les fichiers startup.
-l lang: Cette option permet de sélectionner la langue de l'utilisateur. Les valeurs possible pour sont -l fr pour sélectionner le francais et -l eng pour sélectionner l'anglais. La langue par défaut est l'anglais, ce défaut est fixé dans le fichier scilab.star .
scilab -link <objects>: est utilisé pour générer un scilex local (exécutable de Scilab) lié avec les fichiers additionnels donnés dans <objects> . Cette commande produit aussi un script scilab , qui lance l'exécution du nouveau scilex .

Par exemple :

      scilab -link  C/interf.o C/evol.o C/bib.a

crée un nouveau scilex dans le quel le fichier interf.o par défaut sera remplacé par C/interf.o .

-mem N: Spécifie la valeur initiale de la stacksize, cette option est a utiliser avec l'option -ns. Lorsque Scilab est appelé sans l'option -ns la valeur initiale de la stacksize est définie par le script scilab.star.
-nb: si cette option est présente la bannière d'acceuil de Scilab n'est pas affichée.
-ns : si cette option est présente le script de démarrage "principal" SCI/scilab.star ainsi que les fichiers de démarrage "utilisateur" SCIHOME/.scilab et SCIHOME/scilab.ini ne sont pas pas exécutés.
-nouserstartup : Si cette option est fournie, les fichiers de démarrage "utilisateur" SCIHOME/.scilab , SCIHOME/scilab.ini ne sont pas éxécutés.
-nw: si cette option est présente Scilab n'est pas exécuté dans une fenêtre spécifique mais sur la ligne de commande.
-nwni: si cette option est présente Scilab n'est pas exécuté dans une fenêtre spécifique et n'accepte pas d'interaction avec l'utilisateur. Cette option doit être utilisée avec l'option -e ou -f .
--texmacs: Cette option est réservée pour TeXMacs.


scilink

Scilab Function
Last update : 12/01/2004

scilink - Unix script to relink Scilab

Calling Sequence

scilink <object-files>

Description

This script is used to produce a local scilex (executable code of Scilab) linked with the additional files given by the user in <object-files> .

If in the list of object files some names are known scilex names (from SCIDIR/routines/default ) then the scilex default files are omitted and replaced with the given ones .

This script also produces an xscilab script, which when called will ran the new generated scilex file.

For example the command

scilink C/interf.o C/evol.o C/bib.a

will create a new scilex file in which the default interf.o file will be replaced by C/interf.o .

See Also

link , addinter ,


scipad

Scilab Function
Last update : 05/09/2005

scipad - Embedded Scilab text editor

Calling Sequence

scipad()
scipad(f)
scipad([f1,f2,...])
scipad f1 f2 ...

Parameters

  • f, f1, f2... : file pathnames

Description

Scipad is an embedded Scilab text editor written in TCL/TK. It can be started with the "Editor" button on top of the main Scilab window, or from Scilab command line with the instruction scipad() or scipad f .

The same invocation adds further files to an already opened scipad session. Scipad allows Windows like edition modes. Keyboard shortcuts are defined for most possible editing actions and reported by the menu entries.

Additionally, the following shortcuts are defined:

<F2> | Save file
<F5> | Save file and run it into Scilab
<F6>, <Control-F6> | Show next buffer
<F7>, <Control-F7> | Show previous buffer
<double-click mouse-button1> | Select word
<triple-click mouse-button1> | Select line
<Shift-Control-mouse-button1> | Open the source of the library function under the pointer
<mouse-button2> | Paste selection
<mouse-button3> | Popup edit menu, or debug menu if clicked during a debug session
<Shift-mouse-button3> | Popup Execute menu
<Control-mouse-button3> | Popup Options menu
<Control-plus> | Increase the font size
<Control-minus> | Decrease the font size
<double-button1> on a tile title | Maximize this tile
<double-button1> on a sash | Space sashes evenly (for this paned window)
<button2> on a tile title | Switch hidden files

The "Load Into Scilab" (Ctrl-lowercase-l) menu entry can be used to exec the file content into Scilab, while "Execute selection" (Ctrl-lowercase-y) passes the selected lines to the scilab shell using ScilabEval (i.e. execstr ).

Debugger

Scipad 2.0 or later includes a debugger (for .sci files only). The user can:

  • Set/remove breakpoints anywhere in the opened files. The breakpointed lines get pink background.

  • Configure execution. The user has to provide the function name to execute, its variable names, and variable values. To ease this step, a scan of the currently displayed buffer is implemented to look for functions defined in it, scan their names and variable names. All this is displayed to the user in a dialog for easy selection. First, he has to select a function in a spinbox, then eventually one of its variables. Once a variable is selected, the user can set/change its value (another dialog pops). Variable values and names are displayed in listboxes. The user can also add a new variable or remove already defined variables. This is in case the user changes the input variables of his function in the file, and he does not want to scan the buffer again (which causes all the variable values to reset to a null value, actually "").

  • Launch execution with breakpoints. Scipad execs the currently displayed buffer as well as all the opened buffers that contain functions, sends to Scilab the buffer as well as all the opened buffers that contain functions, sends to Scilab the setbpt instructions relative to all the breakpoints that have been set, and executes the selected function with the input variable values provided during the configure execution step. Then the execution is automagically stopped by Scilab at the first breakpoint.

    • At this point there are several possibilities for the user:

  • Continue up to next breakpoint. Scilab resumes execution, and stops at the next breakpoint or goes to the end of the file if there are no more breakpoints. The active breakpoint is emphasized in Scipad so that it can easily be identified.

  • Insert a new breakpoint or remove existing breakpoint during the debug. The breakpointed lines get pink background, and lines where breakpoints are removed restore their normal background. The new breakpoint configuration is taken into account for the next steps of execution or debug.

  • Execute step by step. This is currently not available (it is always disabled in the Debug menu). See proc stepbystep_bp in SCI/tcl/scipadsources/db_debugsession.tcl for further details about the problems encountered for this item.

  • Continue ignoring any breakpoint. Finish execution in Scilab as if there was no breakpoint at all: Breakpoints are removed from Scilab but kept in Scipad.

  • Abort debug. Abort execution in Scilab and cancel the current debug session in Scipad.

  • Remove all breakpoints. This allows to quickly remove all the breakpoints from both Scilab and Scipad.

    • At any time during the debug, a watch window can be displayed on user request. It allows to monitor any variable value, or change a variable value during a breakpoint stop and relaunch execution with the modified value. The watch window also displays the calling stack.

    After the end of the execution, the breakpoints are removed from Scilab (but kept in Scipad).

    In its current development state the debugger works well with functions, i.e. pure .sci files. Support of .sce files or mixed .sce/.sci files has been foreseen but not yet implemented. That means that a .sce file will not crash Scipad, which is the very least, but more, once a feasible solution for debugging this type of files is figured out, it should be easy to add the functionality in the Scipad source code. Anyway, if actually a debug is required in a .sce, you should first convert it into a .sci function just by adding (output_vars)=function foo(input_vars) / endfunction and that's it. The absence of breakpoints management for .sce is therefore not such a major drawback.

    Remarks

  • Localisation: Scipad menues and messages can be translated to several languages. By default, they appear in the language of Scilab, which is either English or French (see setlanguage ), but other languages are being added. The localization in effect can be selected with the menu Options/Locale, and is remembered across sessions. Currently, the supported languages are: "de" (German) ,"eng" (English), "fr" (French), "it" (Italian), "no" (Norwegian), "se" (Swedish).Further languages can be added by creating the proper translation file and putting it in SCI/tcl/scipadsources/msg_files/. If you plan to do such a job, please check the file SCI/tcl/scipadsources/msg_files/AddingTranslations.txt for detailed instructions, and consider to contribute it to the community.

  • Drag and drop: DnD has been implemented in Scipad for moving around text, for dropping selected text from and to external applications, and for opening files or for list of files.

    Dragging one or more files from an explorer and dropping to Scipad will open the file(s) in Scipad. Doing the same with a directory will open recursively all the directory contents (beware!)

    For text selected within the Scipad window, the possible actions are move (just use mouse button-1) and copy (Control button-1). Text selections can be moved or copied also between different Scipad subpanes, when tiling is active.

    Drag and drop capabilities in Scipad rely on the TkDnD package (http://sourceforge.net/projects/tkdnd). Presence of this package should be automatically detected by Scipad, enabling the corresponding features at that time. Windows and linux-i386 binary versions of Scilab are currently shipped with Tkdnd. If not, here are some installation instructions:

    Windows platforms: Download the full package (currently tkdnd-1.0a2.tar.gz), and uncompress it somewhere. Copy the content of lib\tkdnd and paste it into SCI\tcl\tk8.4\tkdnd. That's all!

    linux-i386 platforms: Download the rpm package (currently tkdnd-1.0-b2.i386.rpm). Install it with rpm -U (may have to force --nodeps if it doesn't recognize an existing tcl installation). If you have a source version of Scilab and an installation of tcl-tk, check where they are installed (e.g. /usr/share/) and move the newly created directory /usr/lib/tkdnd1.0/ to there. If you have a binary version of Scilab, move tkdnd1.0/ to SCI/tcl/, where the supplied tcl-tk binaries are.

  • Known Issues:

    The commands passed are output on the Scilab window, but are not recorded in the history.

  • Bugs: There are still a few... Details can be found in file SCI/tcl/scipadsources/BUGS

    • Examples

       scipad SCI/scilab.star

    See Also

    edit , manedit , edit_error ,

    Authors

    Scipad is derived from tknotepad written by Joseph Acosta;
    Mathieu Philippe, INRIA, 2001;
    Enrico Segre, Weizmann Institute, 2003-2005;
    Francois Vogel, 2004-2005.


sethomedirectory

Scilab Function
Last update : 08/06/2005

sethomedirectory - Set Scilab home directory

Calling Sequence

[home,scilabhome]=sethomedirectory()
[home,scilabhome]=sethomedirectory(homepath)

Parameters

  • home : a string
  • scilabhome : a string (value of SCIHOME environment variable)
  • homepath : home path (a string)

Description

Set Scilab home path : "SCIHOME" variable.

On Windows, C:/Documents and Settings/<User>/Scilab/<Scilab-Version>

On Unix, /home/<User>/Scilab/<Scilab-Version>

Author

Allan CORNET


setlanguage

Foncion Scilab
Last update : 25/10/2006

setlanguage - Modifie la langue courante.

Calling Sequence

setlanguage(language)

Parameters

  • language : avec language='fr' or 'eng'

Description

setlanguage(language) change la langue courante dans scilab (aide et les menus).

See Also

LANGUAGE ,

Authors

A.C.


sleep

Fonction Scilab
Last update : 08/06/2005

sleep - suspend Scilab

Calling Sequence

sleep(milliseconds)

Description

sleep : Sleep suspend Scilab durant la duree specifie en millisecondes.

Examples

    tic;sleep(6000);toc

See Also

xpause ,

Author

Allan CORNET


timer

Scilab Function
Last update : 16/06/2004

timer - temps CPU consommé

Calling Sequence

timer()

Description

Renvoie le temps CPU consommé par Scilab depuis le dernier appel à timer() .

Examples

timer();A=rand(100,100);timer()

See Also

unix_g ,


tohome

Fonction Scilab
Last update : 22/04/2004

tohome - Déplace le curseur en haut à gauche de la fenêtre de commande

Calling Sequence

tohome()

Description

tohome() déplace le curseur en haut à gauche de la fenêtre de commande et efface l'écran.

Vous pouvez utiliser la barre de défilement pour voir l'historique des fonctions.

Notez que tohome() ne peut être utilisé sous Windows quand Scilab est utilisé en mode sans fenêtre.

See Also

clc ,

Authors

V.C.


toolbar

Fonction Scilab
Last update : 08/06/2005

toolbar - montre ou cache la toolbar (pour Windows) (Windows)

Calling Sequence

state1=toolbar(winnum,state2)
state1=toolbar(winnum)

Parameters

  • state1 : retourne l'etat de la toolbar 'on' ou 'off'
  • winum : numero de la fenetre (-1 : console )
  • state2 : 'on' ou 'off' fixe l'etat de la toolbar

Description

montre ou cache la toolbar (pour Windows).

Examples

toolbar(-1,'off')
state=toolbar(-1,'on')

plot3d();
h=gcf();
toolbar(h.figure_id,'off')

Author

Allan CORNET


toprint

Scilab Function
Last update : 09/08/2005

toprint - Send text or figure to the printer (Windows)

Calling Sequence

toprint('filename')
toprint(['line1','line2',...],'page header')
toprint(num)
toprint(num,output)

Description

toprint('filename') send text file to the printer.

bOK=toprint('filename') send text file to the printer. bOK is %T if file exist.

toprint(['line1','line2',...],'page header')

toprint(num) send the figure with figure_id=num to the printer.

toprint(num,output) send the figure with figure_id=num to the printer.With ouput='pos' or 'gdi' ('gdi' by default)

Examples

toprint(['Test','toprint primitive'],'Scilab page header');
scf(4);
plot();
toprint(4);
toprint(4,'pos');

See Also

printsetupbox ,

Authors

A.C


ulink

Scilab Function
Last update : 12/01/2004

ulink - unlink a dynamically linked shared object

Calling Sequence

ulink(x)

Description

see link

See Also

link ,


unix_g

Scilab Function
Last update : April 1993

unix_g - exécution d'une commande Unix ou DOS, sortie redirigée vers une variable

Calling Sequence

rep=unix_g(cmd)
[rep,stat]=unix_g(cmd)

Parameters

  • command-name : chaîne de caractères
  • rep : vecteur colonne de chaînes de caractères
  • stat : un entier, le statut d'erreur, si stat==0 aucune erreur.

Description

Envoie la chaîne command-name à l'interpréteur de commande (sh sous Unix, ou command.com sous DOS). La sortie standard et les erreurs sont reportées dans la variable rep . Les erreurs se produisant dans l'interpréteur de commande sont interceptées; notez que la *dernière erreur uniquement* est signalée quand command-name est une suite de commandes séparées par des ";".

Examples

function d=DIR(path)
  path=pathconvert(path,%t,%t)
  if MSDOS then
    d=unix_g('dir '+path)
  else
    d=unix_g('ls '+path)
  end
endfunction

DIR('SCI/demos')

See Also

unix_s , unix_w , unix_x , unix ,


unix_s

Scilab Function
Last update : April 1993

unix_s - exécution d'une commande Unix ou DOS, pas de sortie

Calling Sequence

unix_s(command-name)

Parameters

  • command-name : chaîne de caractères
  • .SH DESCRIPTION

Description

Envoie la chaîne command-name à l'interpréteur de commande (sh sous Unix, ou command.com sous DOS). La sortie standard et les erreurs ne sont pas reportées (redirection vers /dev/null sous Unix); notez que la *dernière erreur uniquement* est signalée quand command-name est une suite de commandes séparées par des ";".

Examples

if MSDOS then
  unix_s("del foo");
else
  unix_s("rm -f foo");
end

See Also

edit , manedit , unix_g , unix_w , unix_x , unix ,


unix_w

Scilab Function
Last update : 16/12/2005

unix_w - exécution d'une commande Unix ou DOS, sortie redirigée vers la fenêtre de Scilab

Calling Sequence

unix_w(command-name)

Parameters

  • command-name : chaîne de caractères
  • .SH DESCRIPTION

Description

Envoie la chaîne command-name à l'interpréteur de commande (sh sous Unix, ou command.com sous DOS). La sortie standard et les erreurs sont reportées dans la variable rep . Les erreurs se produisant dans l'interpréteur de commande sont interceptées; notez que la *dernière erreur uniquement* est signalée quand command-name est une suite de commandes séparées par des ";".

Examples

if MSDOS then
   unix_w("dir "+'""'+WSCI+"\demos"+'""');
else
  unix_w("ls $SCI/demos");
end

See Also

edit , manedit , unix_g , unix_s , unix_x , unix ,


unix_x

Scilab Function
Last update : 16/12/2005

unix_x - exécution d'une commande Unix ou DOS, sortie redirigée vers une fenêtre

Calling Sequence

unix_x(command-name)

Parameters

  • command-name : chaîne de caractères

Description

Envoie la chaîne command-name à l'interpréteur de commande (sh sous Unix, ou command.com sous DOS). La sortie standard et les erreurs sont reportées dans une fenêtre . Les erreurs se produisant dans l'interpréteur de commande sont interceptées; notez que la *dernière erreur uniquement* est signalée quand command-name est une suite de commandes séparées par des ";"

Examples

if MSDOS then
  unix_x("dir "+'""'+WSCI+"\demos"+'""');
else
 unix_x("ls $SCI/demos");
end

See Also

edit , manedit , unix_g , unix_s , unix_w , unix ,


unix

Scilab Function
Last update : April 1993

unix - exécution d'une commande Unix ou DOS

Calling Sequence

stat=unix(command-name)

Parameters

  • command-name : chaîne de caractères contenant les commandes à exécuter
  • stat : un entier

Description

Envoie la chaîne command-name à l'interpréteur de commande (sh sous Unix, ou command.com sous DOS). La sortie standard et les erreurs sont reportées dans l'interpréteur de commande.

stat vaut -1 en sortie si la fonction ne peut pas être appelée (pas assez de mémoire par exemple) ou alors le code de sortie de l'interpréteur de commande.

Examples

unix("ls $SCI/demos");
deff('wd=getdir()','if MSDOS then unix(''cd>''+TMPDIR+''\path'');..
                 else unix(''pwd>''+TMPDIR+''/path'');end..
      wd=read(TMPDIR+''/path'',1,1,''(a)'')')
wd=getdir()

See Also

edit , manedit , unix_g , unix_s , unix_w , unix_x ,


winopen

Fonction Scilab
Last update : 08/06/2005

winopen - Ouvre le fichier avec l'application appropriée (Windows seulement)

Calling Sequence

winopen('filename')

Description

winopen('filename') ouvre le fichier avec l'application appropriée de Microsoft Windows. winopen effectue la même action que si vous double-cliquez sur l'icone dans l'explorateur de Windows.

See Also

unix ,

Authors

A.C.


winqueryreg

Fonction Scilab
Last update : 08/06/2005

winqueryreg - Obtenir une clef de la base des registres de Microsoft Windows

Calling Sequence

value = winqueryreg('name', 'rootkey', 'subkey')
value = winqueryreg('rootkey', 'subkey', 'valname')
value = winqueryreg('rootkey', 'subkey')

Description

value = winqueryreg('name', 'rootkey', 'subkey') retourne les clefs contenues dans rootkey\subkey dans une matrice de chaines de caracteres. Le premier argument doit etre la chaine de caracteres, 'name'.

Si la valeur contenue dans la base des registres est une chaine de caracteres, winqueryreg retourne une chaine de caracteres. Si la valeur est un entier sur 32 bits, winqueryreg retourne la valeur comme un entier (int32).

value = winqueryreg('rootkey', 'subkey', 'valname') retourne la valeur pour la clef valname dans rootkey\subkey.

value = winqueryreg('rootkey', 'subkey') retourne la valeur "par défaut" de la clef rootkey\subkey.

Note : Les arguments 'name' et 'rootkey' sont "case-sensitive". Les arguments 'subkey' et 'valname' ne le sont pas.

Examples

if MSDOS then
  winqueryreg 'HKEY_LOCAL_MACHINE' 'HARDWARE\DESCRIPTION\System\CentralProcessor\0\' 'ProcessorNameString'
  lines(-1);
  mousechar = winqueryreg('name', 'HKEY_CURRENT_USER','control panel\mouse');
  len=size(mousechar);
  for k=1:len(1)
    setting = winqueryreg('HKEY_CURRENT_USER','control panel\mouse', mousechar(k));
     if (mousechar(k)=='') then mousechar(k)='default';,end
     str = sprintf('%s = %s', mousechar(k), string(setting));
     disp(str);
  end
end

Authors

A.C


with_atlas

Fonction Scilab
Last update : 08/06/2005

with_atlas - Test si Scilab a ete construit avec la librairie Atlas

Calling Sequence

r=with_atlas()

Parameters

  • r : un booleen

Description

retourne %t si Scilab a ete construit avec la librairie Atlas ou %f si ce n'est pas le cas.


with_gtk

Scilab Function
Last update : 06/01/2006

with_gtk - Checks if Scilab has been built with the "GIMP Toolkit" library

Calling Sequence

r=with_gtk()

Parameters

  • r : a boolean

Description

Returns %t if Scilab as been built with gtk library interface or %f if not.


with_javasci

Fonction Scilab
Last update : 08/06/2005

with_javasci - Test si Scilab a ete construit avec l'interface java

Calling Sequence

r=with_javasci()

Parameters

  • r : un booleen

Description

Retourne %t si Scilab a ete construit avec l'interface java ou %f si ce n'est pas le cas.


with_pvm

Scilab Function
Last update : 08/12/2005

with_pvm - Test si Scilab a été compilé avec l'interface "Parallel Virtual Machine"

Calling Sequence

r=with_pvm()

Parameters

  • r : a boolean

Description

Retourne %t si Scilab a été compilé avec l'interface "Parallel Virtual Machine" ou %f sinon.


with_texmacs

Scilab Function
Last update : 12/01/2004

with_texmacs - Checks if Scilab has been called by texmacs

Calling Sequence

r=with_texmacs()

Parameters

  • r : a boolean

Description

Returns %t if Scilab as been been called by TeXmacs


with_tk

Scilab Function
Last update : 12/01/2004

with_tk - Checks if Scilab has been built with TCL/TK

Calling Sequence

r=with_tk()

Parameters

  • r : a boolean

Description

Returns %t if Scilab as been built with TCL/TK interface or %f if not.


xmltohtml

Scilab Function
Last update : 12/01/2004

xmltohtml - converts xml Scilab help files to html

Calling Sequence

xmltohtml(dirs [,titles [,xsl [,step]]])

Parameters

  • dirs : vector of strings: a set of directory paths for which html manuals are to be generated or []
  • titles : vector of strings: titles associated to directory paths or []
  • xsl : string, name of xsl file used for translation
  • step : string, should be "whatis", "index", "html","contents", or "all"

Description

converts xml Scilab help files contained in a set of directories into html files.

In a first step ("whatis") a whatis.htm file is generated in each directory using information given in the "SHORT_DESCRIPTION" tag of each xml file and the given title.

In a second step ("index") the tags LINK are analysed, and xmltohtml tries to resolve the references using the already known help files defined in the %helps variable.

The third step ("html") it translates the xml file to html using external program xsltproc and the given xsl file which should be located in SCIDIR/man/LANGUAGE/ The generated html files are located together with the corresponding xml ones.

the last step ("contents") produces a contents.xml file

if dirs is [] then already defined help directories (see %helps(:,1) ) are assumed and titles are searched in %helps(:,2) . So xmltohtml([]) updates currents html files

See Also

help , help_skeleton ,


G_make

Scilab Function
Last update : 12/01/2004

G_make - call make or nmake

Calling Sequence

Rfiles=G_make(files,dllname)

Parameters

  • files : a character string or a vector of character string.
  • dllname : a character string.
  • Rfiles : vector of character string. Rfiles can be used as a first argument when calling addinter function.

Description

On Unix like systems (i.e unix or windows/gcwin32) G_make calls the make utility for building target files and returns the value of files in the variable Rfiles . On windows platforms, (i.e when Scilab was compiled with Microsoft VisualC++). G_make calls the nmake utility for building target dllname and it returns the value of dllname in the variable Rfiles . Of course G_make will work if apropriate Makefiles are provided in the current Scilab directory.

G_make can be used to provide OS independant call to addinter. and such examples can be found in the directory SCIDIR/examples/addinter-examples

files=G_make([TMPDIR+'/ex1cI.o',TMPDIR+'/ex1c.o'],'ex1c.dll');// compilation
addinter(files,'foobar','foubare'); // link

See Also

addinter ,


Algèbre linéaire
aff2ab - linear (affine) function to A,b conversion
balanc - matrix or pencil balancing
bdiag - bloc-diagonalisation, vecteurs propres généralisés
chfact - Factorisation de Cholesky creuse
chol - Factorisation de Cholesky
chsolve - solveur de Cholesky creux
classmarkov - recurrent and transient classes of Markov matrix
coff - résolvante (méthode des cofacteurs)
colcomp - compression de colonnes, noyau
companion - matrice compagnon
cond - conditionnement
det - déterminant
eigenmarkov - normalized left and right Markov eigenvectors
ereduc - computes matrix column echelon form by qz transformations
exp - exponentielle
expm - exponentielle de matrice
fstair - computes pencil column echelon form by qz transformations
fullrf - factorisation de rang plein
fullrfk - factorisation de rang plein de A^k
genmarkov - generates random markov matrix with recurrent and transient classes
givens - Transformation de Givens
glever - inverse d'un faisceau de matrices
gschur - generalized Schur form (obsolete).
gspec - valeurs propres d'un faisceau de matrices (obsolete)
hess - Forme de Hessenberg
householder - Matrice de Householder
im_inv - inverse image
inv - inverse d'une matrice
kernel - noyau
kroneck - Kronecker form of matrix pencil
linsolve - solveur d'équation linéaire
lsq - linear least square problems.
lu - factorisation LU
ludel - libération de la mémoire allouée à des facteurs LU creux
lufact - factorisation LU d'une matrice creuse
luget - extraction de facteurs LU creux
lusolve - solveur de système linéaire creux
lyap - Equation de Lyapunov
nlev - Algorithme de Leverrier
orth - calcul d'une base orthogonale
pbig - projection sur des sous-espaces propres
pencan - canonical form of matrix pencil
penlaur - Laurent coefficients of matrix pencil
pinv - pseudo-inverse
polar - forme polaire
proj - projection
projspec - spectral operators
psmall - spectral projection
qr - factorisation QR
quaskro - quasi-Kronecker form
randpencil - random pencil
range - Image de A^k
rank - rang
rankqr - rank revealing QR factorization
rcond - estimation de l'inverse du conditionnement
rowcomp - compression de lignes, image
rowshuff - shuffle algorithm
rref - computes matrix row echelon form by lu transformations
schur - [ordered] Schur decomposition of matrix and pencils
spaninter - subspace intersection
spanplus - sum of subspaces
spantwo - sum and intersection of subspaces
spchol - Factorisation de Cholesky creuse
spec - valeurs propres d'une matrice
sqroot - factorisation hermitienne W*W'
sva - approximation de valeurs singulières
svd - décomposition en valeurs singulières
sylv - Sylvester equation.
trace - trace d'une matrice


aff2ab

Scilab Function
Last update : 12/01/2004

aff2ab - linear (affine) function to A,b conversion

Calling Sequence

[A,b]=aff2ab(afunction,dimX,D [,flag])

Parameters

  • afunction : a scilab function Y =fct(X,D) where X, D, Y are list of matrices
  • dimX : a p x 2 integer matrix ( p is the number of matrices in X )
  • D : a list of real matrices (or any other valid Scilab object).
  • flag : optional parameter ( flag='f' or flag='sp' )
  • A : a real matrix
  • b : a real vector having same row dimension as A

Description

aff2ab returns the matrix representation of an affine function (in the canonical basis).

afunction is a function with imposed syntax: Y=afunction(X,D) where X=list(X1,X2,...,Xp) is a list of p real matrices, and Y=list(Y1,...,Yq) is a list of q real real matrices which depend linearly of the Xi 's. The (optional) input D contains parameters needed to compute Y as a function of X. (It is generally a list of matrices).

dimX is a p x 2 matrix: dimX(i)=[nri,nci] is the actual number of rows and columns of matrix Xi . These dimensions determine na , the column dimension of the resulting matrix A : na=nr1*nc1 +...+ nrp*ncp .

If the optional parameter flag='sp' the resulting A matrix is returned as a sparse matrix.

This function is useful to solve a system of linear equations where the unknown variables are matrices.

Examples

// Lyapunov equation solver (one unknown variable, one constraint)
deff('Y=lyapunov(X,D)','[A,Q]=D(:);Xm=X(:); Y=list(A''*Xm+Xm*A-Q)')
A=rand(3,3);Q=rand(3,3);Q=Q+Q';D=list(A,Q);dimX=[3,3];
[Aly,bly]=aff2ab(lyapunov,dimX,D);
[Xl,kerA]=linsolve(Aly,bly); Xv=vec2list(Xl,dimX); lyapunov(Xv,D)
Xm=Xv(:); A'*Xm+Xm*A-Q

// Lyapunov equation solver with redundant constraint X=X'
// (one variable, two constraints) D is global variable
deff('Y=ly2(X,D)','[A,Q]=D(:);Xm=X(:); Y=list(A''*Xm+Xm*A-Q,Xm''-Xm)')
A=rand(3,3);Q=rand(3,3);Q=Q+Q';D=list(A,Q);dimX=[3,3];
[Aly,bly]=aff2ab(ly2,dimX,D);
[Xl,kerA]=linsolve(Aly,bly); Xv=vec2list(Xl,dimX); ly2(Xv,D)

// Francis equations
// Find matrices X1 and X2 such that:
// A1*X1 - X1*A2 + B*X2 -A3 = 0
// D1*X1 -D2 = 0
deff('Y=bruce(X,D)','[A1,A2,A3,B,D1,D2]=D(:),...
[X1,X2]=X(:);Y=list(A1*X1-X1*A2+B*X2-A3,D1*X1-D2)')
A1=[-4,10;-1,2];A3=[1;2];B=[0;1];A2=1;D1=[0,1];D2=1;
D=list(A1,A2,A3,B,D1,D2);
[n1,m1]=size(A1);[n2,m2]=size(A2);[n3,m3]=size(B);
dimX=[[m1,n2];[m3,m2]];
[Af,bf]=aff2ab(bruce,dimX,D);
[Xf,KerAf]=linsolve(Af,bf);Xsol=vec2list(Xf,dimX)
bruce(Xsol,D)

// Find all X which commute with A
deff('y=f(X,D)','y=list(D(:)*X(:)-X(:)*D(:))')
A=rand(3,3);dimX=[3,3];[Af,bf]=aff2ab(f,dimX,list(A));
[Xf,KerAf]=linsolve(Af,bf);[p,q]=size(KerAf);
Xsol=vec2list(Xf+KerAf*rand(q,1),dimX);
C=Xsol(:); A*C-C*A

See Also

linsolve ,


balanc

Scilab Function
Last update : 12/01/2004

balanc - matrix or pencil balancing

Calling Sequence

[Ab,X]=balanc(A)
[Eb,Ab,X,Y]=balanc(E,A)

Parameters

  • A: a real square matrix
  • X: a real square invertible matrix
  • E: a real square matrix (same dimension as A )
  • Y: a real square invertible matrix.

Description

Balance a square matrix to improve its condition number.

[Ab,X] = balanc(A) finds a similarity transformation X such that

Ab = inv(X)*A*X has approximately equal row and column norms.

For matrix pencils,balancing is done for improving the generalized eigenvalue problem.

[Eb,Ab,X,Y] = balanc(E,A) returns left and right transformations X and Y such that Eb=inv(X)*E*Y, Ab=inv(X)*A*Y

Remark

Balancing is made in the functions bdiag and spec .

Examples

A=[1/2^10,1/2^10;2^10,2^10];
[Ab,X]=balanc(A);
norm(A(1,:))/norm(A(2,:))
norm(Ab(1,:))/norm(Ab(2,:))

See Also

bdiag , spec , schur ,


bdiag

Scilab Function
Last update : 16/06/2004

bdiag - bloc-diagonalisation, vecteurs propres généralisés

Calling Sequence

[Ab [,X [,bs]]]=bdiag(A [,rmax])

Parameters

  • A : matrice carrée réelle ou complexe
  • rmax : nombre réel
  • Ab : matrice carrée réelle ou complexe
  • X : matrice régulière, réelle ou complexe
  • bs : vecteur d'entiers

Description

[Ab [,X [,bs]]]=bdiag(A [,rmax])

[Ab [,X [,bs]]]=bdiag(A [,rmax]) calcule la forme bloc-diagonale de A . bs précise la structure des blocs (tailles respectives des blocs). X est la matrice de changement de base, c'est à dire que Ab = inv(X)*A*X est bloc-diagonale.

rmax contrôle le conditionnement de X ; la valeur par défaut est la norme l1 de A .

Pour obtenir une forme diagonale (si celle-ci existe) choisissez une valeur élevée de rmax ( rmax=1/%eps par exemple). Pour une matrice réelle quelconque, les blocs sont de taille (1x1) ou (2x2) et X est la matrice des vecteurs propres.

Examples

// Cas réel: blocs 1x1 et 2x2
a=rand(5,5);[ab,x,bs]=bdiag(a);ab
// Cas complexe : blocs complexes 1x1
[ab,x,bs]=bdiag(a+%i*0);ab

See Also

schur , sylv , spec ,


chfact

Scilab Function
Last update : 16/06/2004

chfact - Factorisation de Cholesky creuse

Calling Sequence

spcho=chfact(A)

Parameters

  • A : matrice creuse réelle ou complexe
  • spcho : liste contenant les facteurs de Cholesky

Description

Si A est creuse et hermitienne (symétrique dans le cas réel) définie positive, spcho=chfact(A) calcule les facteurs de sa factorisation de Cholesky. Cette fonction est basée sur le programme Ng-Peyton (ORNL). Voir le programme Fortran pour une description complète des variables de la liste spcho . Cette fonction est à utiliser conjointement avec chsolve .

See Also

chsolve , sparse , lufact , luget , spchol ,


chol

Scilab Function
Last update : 17/06/2004

chol - Factorisation de Cholesky

Calling Sequence

[R]=chol(X)

Parameters

  • X : matrice réelle ou complexe

Description

Si X est hermitienne (symétrique dans le cas réel) définie positive, alors R = chol(X) renvoie une matrice triangulaire supérieure R telle que R'*R = X .

chol(X) utilise uniquement la partie triangulaire supérieure de X dont la partie triangulaire inférieure est supposée être la transposée (transposée conjuguée dans le cas complexe).

Examples

    W=rand(5,5)+%i*rand(5,5);
    X=W*W';
    R=chol(X);
    norm(R'*R-X)

See Also

spchol , qr , svd , bdiag , fullrf ,

Used Function

La décomposition de Cholesky est basée sur les routines Lapack DPOTRF pour les matrices réelles et ZPOTRF pour le cas complexe.


chsolve

Scilab Function
Last update : 28/06/2006

chsolve - solveur de Cholesky creux

Calling Sequence

sol=chsolve(spcho,rhs)

Parameters

  • spcho : liste contenant les facteurs de Cholesky renvoyés par chfact
  • rhs, sol : vecteurs

Description

sol=chsolve(spcho,rhs) calcule la solution de rhs=A*sol , où A est une matrice symétrique définie positive. Cette fonction est basée sur le programme Ng-Peyton (ORNL). Voir le programme Fortran pour une description complète des variables de la liste spcho .

Examples

    A=sprand(20,20,0.1);
    A=A*A'+eye();
    spcho=chfact(A);
    sol=(1:20)';rhs=A*sol;
    spcho=chfact(A);
    chsolve(spcho,rhs)

See Also

chfact , sparse , lufact , luget , spchol ,


classmarkov

Scilab Function
Last update : 12/01/2004

classmarkov - recurrent and transient classes of Markov matrix

Calling Sequence

[perm,rec,tr,indsRec,indsT]=classmarkov(M)

Parameters

  • M : real N x N Markov matrix. Sum of entries in each row should add to one.
  • perm : integer permutation vector.
  • rec, tr : integer vector, number (number of states in each recurrent classes, number of transient states).
  • indsRec,indsT : integer vectors. (Indexes of recurrent and transient states).

Description

Returns a permutation vector perm such that

M(perm,perm) = [M11 0 0 0 0   0]
               [0 M22 0 0     0]
               [0 0 M33       0]
               [      ...      ]
               [0 0       Mrr 0]
               [* *        *  Q]

Each Mii is a Markov matrix of dimension rec(i) i=1,..,r . Q is sub-Markov matrix of dimension tr . States 1 to sum(rec) are recurrent and states from r+1 to n are transient. One has perm=[indsRec,indsT] where indsRec is a vector of size sum(rec) and indsT is a vector of size tr.

Examples

//P has two recurrent classes (with 2 and 1 states) 2 transient states
P=genmarkov([2,1],2,'perm')
[perm,rec,tr,indsRec,indsT]=classmarkov(P);
P(perm,perm)

See Also

genmarkov , eigenmarkov ,


coff

Scilab Function
Last update : 16/06/2004

coff - résolvante (méthode des cofacteurs)

Calling Sequence

[N,d]=coff(M [,var])

Parameters

  • M : matrice carrée réelle
  • var : chaîne de caractères (indéterminée des polynômes)
  • N : matrice de polynômes (de même taille que M )
  • d : polynôme (polynôme caractéristique de M : poly(M,var) )

Description

coff calcule R= (s*eye()-M)^-1 pour M une matrice réelle. R est donnée par N/d .

N = matrice des numérateurs (polynômes).

d = dénominateur commun.

var chaîne de caractères (indéterminée des polynômes, ' s ' par défaut)

Examples

M=[1,2;0,3];
[N,d]=coff(M)
N/d
inv(%s*eye()-M)

See Also

coffg , ss2tf , nlev , poly ,


colcomp

Scilab Function
Last update : 16/06/2004

colcomp - compression de colonnes, noyau

Calling Sequence

[W,rk]=colcomp(A [,flag] [,tol])

Parameters

  • A : matrice réelle ou complexe
  • flag : chaîne de caractères
  • tol : nombre réel
  • W : matrice carré régulière (matrice de changement de base)
  • rk : entier (rang de" A )

Description

Compression des colonnes de A : Ac = A*W est à colonnes compressées, c'est à dire

Ac=[0,Af] et Af est de rang maximal rank( Af ) = rank( A ) = rk .

flag et tol sont des paramètres optionnels : flag = 'qr' ou 'svd' ( 'svd' par défaut).

tol = paramètre de tolérance (de l'ordre de %eps par défaut).

Les ma-rk premières colonnes de W forment une base du noyau de A quand size(A)=[na,ma] .

Examples

A=rand(5,2)*rand(2,5);
[X,r]=colcomp(A);
norm(A*X(:,1:$-r),1)

See Also

rowcomp , fullrf , fullrfk , kernel ,

Author

F.D.;


companion

Scilab Function
Last update : 16/06/2004

companion - matrice compagnon

Calling Sequence

A=companion(p)

Parameters

  • p : polynôme ou vecteur de polynômes
  • A : matrice carrée

Description

Renvoie une matrice A dont le polynôme caractéristique est p si p est unitaire (le coefficient de plus haut degré est égal à un). Si p n'est pas unitaire le polynôme caractéristique de A est égal à p/c où c est le coefficient de plus haut degré de p .

Si p est un vecteur de polynômes unitaires, A est bloc-diagonale, et le polynôme caractéristique du i-ème bloc est égal à p(i) .

Examples

s=poly(0,'s');
p=poly([1,2,3,4,1],'s','c')
det(s*eye()-companion(p))
roots(p)
spec(companion(p))

See Also

spec , poly , randpencil ,

Author

F.D.


cond

Scilab Function
Last update : 16/06/2004

cond - conditionnement

Calling Sequence

cond(X)

Parameters

  • X : matrice réelle ou complexe

Description

Conditionnement en norme 2. cond(X) est le quotient entre la plus grande et la plus petite valeur singulière de X .

Examples

A=testmatrix('hilb',6);
cond(A)

See Also

rcond , svd ,


det

Scilab Function
Last update : 17/06/2004

det - déterminant

Calling Sequence

det(X)
[e,m]=det(X)

Parameters

  • X : matrice réelle, complexe, polynomiale, rationnelle
  • m : nombre réel ou complexe, mantisse du déterminant en base 10
  • e : entier, exposant du déterminant en base 10

Description

det(X) ( m*10^e est le déterminant de la matrice carrée X .

Pour les matrices polynomiales det(X) est équivalent à determ(X) .

Pour les matrices rationnelles det(X) est équivalent à detr(X) .

Examples

    x=poly(0,'x');
    det([x,1+x;2-x,x^2])
    w=ssrand(2,2,4);roots(det(systmat(w))),trzeros(w)   // zéros du système linéaire
    A=rand(3,3);
    det(A), prod(spec(A))

See Also

detr , determ ,

Used Function

Le calcul du determinant est basé sur les routines Lapack : DGETRF pour les matrices réelles et ZGETRF pour le cas complexe.


eigenmarkov

Scilab Function
Last update : 12/01/2004

eigenmarkov - normalized left and right Markov eigenvectors

Calling Sequence

[M,Q]=eigenmarkov(P)

Parameters

  • P : real N x N Markov matrix. Sum of entries in each row should add to one.
  • M : real matrix with N columns.
  • Q : real matrix with N rows.

Description

Returns normalized left and right eigenvectors associated with the eigenvalue 1 of the Markov transition matrix P. If the multiplicity of this eigenvalue is m and P is N x N, M is a m x N matrix and Q a N x m matrix. M(k,:) is the probability distribution vector associated with the kth ergodic set (recurrent class). M(k,x) is zero if x is not in the k-th recurrent class. Q(x,k) is the probability to end in the k-th recurrent class starting from x. If P^k converges for large k (no eigenvalues on the unit circle except 1), then the limit is Q*M (eigenprojection).

Examples

//P has two recurrent classes (with 2 and 1 states) 2 transient states
P=genmarkov([2,1],2)
[M,Q]=eigenmarkov(P);
P*Q-Q
Q*M-P^20

See Also

genmarkov , classmarkov ,


ereduc

Scilab Function
Last update : 12/01/2004

ereduc - computes matrix column echelon form by qz transformations

Calling Sequence

[E,Q,Z [,stair [,rk]]]=ereduc(X,tol)

Parameters

  • X : m x n matrix with real entries.
  • tol : real positive scalar.
  • E : column echelon form matrix
  • Q : m x m unitary matrix
  • Z : n x n unitary matrix
  • stair : vector of indexes,
    • * ISTAIR(i) = + j if the boundary element E(i,j) is a corner point.
    • * ISTAIR(i) = - j if the boundary element E(i,j) is not a corner point.

    (i=1,...,M)

  • rk : integer, estimated rank of the matrix

Description

Given an m x n matrix X (not necessarily regular) the function ereduc computes a unitary transformed matrix E=Q*X*Z which is in column echelon form (trapezoidal form). Furthermore the rank of matrix X is determined.

Examples

X=[1 2 3;4 5 6]
[E,Q,Z ,stair ,rk]=ereduc(X,1.d-15)

See Also

fstair ,

Author

Th.G.J. Beelen (Philips Glass Eindhoven). SLICOT


expm

Scilab Function
Last update : 16/06/2004

expm - exponentielle de matrice

Calling Sequence

expm(X)

Parameters

  • X : matrice carrée réelle ou complexe

Description

Pour X une matrice carrée expm(X) est la matrice

expm(X) = I + X + X^2 /2 + ...

Le calcul fait appel à une bloc-diagonalisation préliminaire de X suivie d'une approximation de Padé sur chaque bloc.

Examples

X=[1 2;3 4]
expm(X)
logm(expm(X))

See Also

logm , bdiag , coff , log , exp ,


exp

Scilab Function
Last update : 16/06/2004

exp - exponentielle

Calling Sequence

exp(X)

Parameters

  • X : matrice carrée réelle ou complexe.

Description

exp(X) renvoie (élément par élément) l'exponentielle des éléments de X .

Examples

x=[1,2,3+%i];
log(exp(x))  // élément par élément
2^x
exp(x*log(2))

See Also

coff , log , expm ,


fstair

Scilab Function
Last update : 12/01/2004

fstair - computes pencil column echelon form by qz transformations

Calling Sequence

[AE,EE,QE,ZE,blcks,muk,nuk,muk0,nuk0,mnei]=fstair(A,E,Q,Z,stair,rk,tol)

Parameters

  • A : m x n matrix with real entries.
  • tol : real positive scalar.
  • E : column echelon form matrix
  • Q : m x m unitary matrix
  • Z : n x n unitary matrix
  • stair : vector of indexes (see ereduc)
  • rk : integer, estimated rank of the matrix
  • AE : m x n matrix with real entries.
  • EE : column echelon form matrix
  • QE : m x m unitary matrix
  • ZE : n x n unitary matrix
  • nblcks :is the number of submatrices having full row rank >= 0 detected in matrix A .
  • muk: integer array of dimension (n). Contains the column dimensions mu(k) (k=1,...,nblcks) of the submatrices having full column rank in the pencil sE(eps)-A(eps)
  • nuk: integer array of dimension (m+1). Contains the row dimensions nu(k) (k=1,...,nblcks) of the submatrices having full row rank in the pencil sE(eps)-A(eps)
  • muk0: integer array of dimension (n). Contains the column dimensions mu(k) (k=1,...,nblcks) of the submatrices having full column rank in the pencil sE(eps,inf)-A(eps,inf)
  • nuk: integer array of dimension (m+1). Contains the row dimensions nu(k) (k=1,...,nblcks) of the submatrices having full row rank in the pencil sE(eps,inf)-A(eps,inf)
  • mnei: integer array of dimension (4). mnei(1) = row dimension of sE(eps)-A(eps)

Description

Given a pencil sE-A where matrix E is in column echelon form the function fstair computes according to the wishes of the user a unitary transformed pencil QE(sEE-AE)ZE which is more or less similar to the generalized Schur form of the pencil sE-A . The function yields also part of the Kronecker structure of the given pencil.

Q,Z are the unitary matrices used to compute the pencil where E is in column echelon form (see ereduc)

See Also

quaskro , ereduc ,

Author

Th.G.J. Beelen (Philips Glass Eindhoven). SLICOT


fullrfk

Scilab Function
Last update : 16/06/2004

fullrfk - factorisation de rang plein de A^k

Calling Sequence

[Q,M]=fullrfk(A,k)

Parameters

  • A : matrice réelle ou complexe
  • k : entier
  • Q,M : matrices réelles ou complexes

Description

Cette fonction calcule la factorisation de rang plein de A^k : fullrfk renvoie Q et M telles que A^k = Q*M avec Im( Q )=Im( A^k ) et ker( M )=ker( A^k ), Q de rang maximal, et les lignes de M sont linéairement indépendantes,

Pour k=1 , fullrfk est équivalent à fullrf .

Examples

A=rand(5,2)*rand(2,5);[Bk,Ck]=fullrfk(A,3);
norm(Bk*Ck-A^3,1)

See Also

fullrf , range ,

Author

F.D (1990);


fullrf

Scilab Function
Last update : 16/06/2004

fullrf - factorisation de rang plein

Calling Sequence

[Q,M,rk]=fullrf(A,[tol])

Parameters

  • A : matrice réelle ou complexe
  • tol : nombre réel (tolérance pour le calcul du rang)
  • Q,M : matrices réelles ou complexes
  • rk : entier (rang de A )

Description

Cette fonction calcule la factorisation de rang plein de A : fullrf renvoie Q et M telles que A = Q*M avec Im( Q )=Im( A ) et ker( M )=ker( A ), Q de rang maximal, et les lignes de M sont linéairement indépendantes, rk = rank( A ) = nombre de colonnes de Q = nombre de lignes de M .

tol = paramètre de tolérance (de l'ordre de %eps par défaut). Le rang rk de A est considéré égal au nombre de ses valeurs singulières plus grandes que norm(A)*tol .

Si A est symétrique, fullrf renvoie M=Q' .

Examples

A=rand(5,2)*rand(2,5);
[Q,M]=fullrf(A);
norm(Q*M-A,1)
[X,d]=rowcomp(A);Y=X';
svd([A,Y(:,1:d),Q])        // Im(Q) = Im(A) = Im(Y(:,1:2))

See Also

svd , qr , fullrfk , rowcomp , colcomp ,

Author

F.D.


genmarkov

Scilab Function
Last update : 12/01/2004

genmarkov - generates random markov matrix with recurrent and transient classes

Calling Sequence

M=genmarkov(rec,tr)
M=genmarkov(rec,tr,flag)

Parameters

  • rec : integer row vector (its dimension is the number of recurrent classes).
  • tr : integer (number of transient states)
  • M : real Markov matrix. Sum of entries in each row should add to one.
  • flag : string 'perm' . If given, a random permutation of the states is done.

Description

Returns in M a random Markov transition probability matrix with size(rec,1) recurrent classes with rec(1),...rec($) entries respectively and tr transient states.

Examples

//P has two recurrent classes (with 2 and 1 states) 2 transient states
P=genmarkov([2,1],2,'perm')
[perm,rec,tr,indsRec,indsT]=classmarkov(P);
P(perm,perm)

See Also

classmarkov , eigenmarkov ,


givens

Scilab Function
Last update : 16/06/2004

givens - Transformation de Givens

Calling Sequence

U=givens(xy)
U=givens(x,y)
[U,c]=givens(xy)
[U,c]=givens(x,y)

Parameters

  • x,y : deux nombres réels ou complexes
  • xy : vecteur colonne réel ou complexe à deux composantes
  • U : matrice unitaire 2 x 2
  • c : vecteur colonne réel ou complexe à deux composantes

Description

U = givens(x, y) ou U = givens(xy) avec xy = [x;y] renvoie U une matrice unitaire 2 x 2 telle que :

U*xy=[r;0]=c .

Notez que givens(x,y) et givens([x;y]) sont équivalents.

Examples

A=[3,4;5,6];
U=givens(A(:,1));
U*A

See Also

qr ,


glever

Scilab Function
Last update : 17/06/2004

glever - inverse d'un faisceau de matrices

Calling Sequence

[Bfs,Bis,chis]=glever(E,A [,s])

Parameters

  • E, A : matrices carrées réelles de même dimensions
  • s : chaîne de caractères (indéterminée des polynômes, ' s ' par défaut )
  • Bfs,Bis : deux matrices polynomiales
  • chis : polynôme

Description

Calcul de

(s*E-A)^-1

par l'algorithme généralisé de Leverrier pour un faisceau de matrices.

      (s*E-A)^-1 = (Bfs/chis) - Bis.

chis = polynôme caractéristique (à une constante multiplicative près).

Bfs = matrice polynomiale de numérateurs

Bis = matrice polynomiale ( - développement de (s*E-A)^-1 à l'infini).

Noter le signe - devant Bis .

Attention

Cette fonction utilise cleanp pour simplifier Bfs,Bis et chis .

Examples

    s=%s;F=[-1,s,0,0;0,-1,0,0;0,0,s-2,0;0,0,0,s-1];
    [Bfs,Bis,chis]=glever(F)
    inv(F)-((Bfs/chis) - Bis)

See Also

rowshuff , det , invr , coffg , pencan , penlaur ,

Author

F. D. (1988)


gschur

Scilab Function
Last update : 12/01/2004

gschur - generalized Schur form (obsolete).

Calling Sequence

[As,Es]=gschur(A,E)
[As,Es,Q,Z]=gschur(A,E)
[As,Es,Z,dim] = gschur(A,E,flag)
[As,Es,Z,dim]= gschur(A,E,extern)

Description

This function is obsolete and is now included in the schur function. In most cases the gschur function will still work as before, but it will be removed in the future release.

The first three syntaxes can be replaced by

[As,Es]=schur(A,E)
[As,Es,Q,Z]=schur(A,E);Q=Q' //NOTE THE TRANPOSITION HERE
[As,Es,Z,dim] = schur(A,E,flag)

The last syntax requires little more adaptations:

ifextern is a scilab function the new calling sequence should be [As,Es,Z,dim]= schur(A,E,Nextern) with Nextern defined as follow:

function t=Nextern(R)
if R(2)==0 then
  t=extern([1,R(1),R(3)])==1
else
  c=(R(1)+%i*R(2))/R(3)
  t=extern([2,real(c+c'),real(c*c')])==1
end
endfunction
ifextern is the name of an external function coded in Fortran or C the new calling sequence should be [As,Es,Z,dim]= schur(A,E,'nextern') with nextern defined as follow:

      logical function nextern(ar,ai,beta)
      double precision ar,ai,beta
      integer r,extern
      if (ai.eq.0.0d0) then
        r=extern(1,ar,beta,0.0d0,0.0d0)
      else
        r=extern(2,0.0d0,0.0d0,2.0d0*ar,ar*ar+ai*ai)
      endif
      nextern=r.eq.1
      end

See Also

external , schur ,


gspec

Scilab Function
Last update : 16/06/2004

gspec - valeurs propres d'un faisceau de matrices (obsolete)

Calling Sequence

[al,be]=gspec(A,E)
[al,be,Z]=gspec(A,E)

Parameters

  • A, E : matrices carrées réelles de mêmes dimensions
  • al, be : vecteurs réels
  • Z : matrice carrée régulière

Description

Cette fonction est maintenant un cas particulier de la fonction spec . La syntaxe d'appel doit être remplacée par

[al,be]=spec(A,E)
[al,be,Z]=spec(A,E)

See Also

spec ,


hess

Scilab Function
Last update : 17/06/2004

hess - Forme de Hessenberg

Calling Sequence

H = hess(A)
[U,H] = hess(A)

Parameters

  • A : matrice carrée réelle ou complexe
  • H : matrice carrée réelle ou complexe
  • U : matrice carrée unitaire

Description

[U,H] = hess(A) Calcule une matrice unitaire U et une matrice de Hessenberg H telles que A = U*H*U' et U'*U = Identité. La syntaxe H=hess(A) ne renvoie que la matrice de Hessenberg.

Les coefficients d'une matrice sous forme de Hessenberg sont nuls sous la première sous-diagonale. Si la matrice est symétrique ou hermitienne, la forme est tridiagonale.

Examples

    A=rand(3,3);[U,H]=hess(A);
    and( abs(U*H*U'-A)<1.d-10 )

See Also

qr , contr , schur ,

Used Function

Le calcul de la forme de Hessenberg determinant est basé sur les routines Lapack : DGEHRD, DORGHR pour les matrices réelles et ZGEHRD, ZORGHR pour le cas complexe.


householder

Scilab Function
Last update : 16/06/2004

householder - Matrice de Householder

Calling Sequence

u=householder(v [,w])

Parameters

  • v : vecteur colonne réel ou complexe
  • w : vecteur colonne réel ou complexe de même taille que v (la valeur par défaut est eye(v) )
  • u : vecteur colonne réel ou complexe

Description

Etant donnés deux vecteurs colonnes v et w de même taille, householder(v,w) renvoie un vecteur normé u , tel que (eye()-2*u*u')*v est colinéaire à w . (eye()-2*u*u') est la matrice de la transformation de Householder correspondante.

La valeur par défaut de w est eye(v) . Dans ce cas le vecteur (eye()-2*u*u')*v est égal à eye(v)*norm(v) .

See Also

qr , givens ,


im_inv

Scilab Function
Last update : 12/01/2004

im_inv - inverse image

Calling Sequence

[X,dim]=im_inv(A,B [,tol])
[X,dim,Y]=im_inv(A,B, [,tol])

Parameters

  • A,B : two real or complex matrices with equal number of columns
  • X : orthogonal or unitary square matrix of order equal to the number of columns of A
  • dim : integer (dimension of subspace)
  • Y : orthogonal matrix of order equal to the number of rows of A and B .

Description

[X,dim]=im_inv(A,B) computes (A^-1)(B) i.e vectors whose image through A are in range( B )

The dim first columns of X span (A^-1)(B)

tol is a threshold used to test if subspace inclusion; default value is tol = 100*%eps . If Y is returned, then [Y*A*X,Y*B] is partitioned as follows: [A11,A12;0,A22] , [B1;0]

where B1 has full row rank (equals rank(B) ) and A22 has full column rank and has dim columns.

Examples

A=[rand(2,5);[zeros(3,4),rand(3,1)]];B=[[1,1;1,1];zeros(3,2)];
W=rand(5,5);A=W*A;B=W*B;
[X,dim]=im_inv(A,B)
svd([A*X(:,1:dim),B])   //vectors A*X(:,1:dim) belong to range(B)
[X,dim,Y]=im_inv(A,B);[Y*A*X,Y*B]

See Also

rowcomp , spaninter , spanplus , linsolve ,

Author

F. Delebecque INRIA


inv

Scilab Function
Last update : 17/06/2004

inv - inverse d'une matrice

Calling Sequence

inv(X)

Parameters

  • X : matrice carrée réelle, complexe, polynomiale ou rationnelle, liste de type "syslin"

Description

inv(X) est l'inverse de la matrice carrée X . Un message de mise en garde est affiché si X est mal équilibrée (termes très petits et termes très grands) ou singulière à la précision machine.

Pour les matrices polynomiales ou rationnelles, inv(X) est équivalent à invr(X) .

Pour les systèmes dynamiques linéaires sous forme de leur représentation d'état (liste de type syslin ), inv(X) est équivalent à invsyslin(X) .

Examples

    A=rand(3,3);inv(A)*A
    //
    x=poly(0,'x');
    A=[x,1,x;x^2,2,1+x;1,2,3];inv(A)*A
    //
    A=[1/x,2;2+x,2/(1+x)]
    inv(A)*A
    //
    A=ssrand(2,2,3);
    W=inv(A)*A
    clean(ss2tf(W))

See Also

slash , backslash , pinv , qr , lufact , lusolve , invr , coff , coffg ,

Used Function

La fonction inv pour les matrices de nombres est basée sur les routines Lapack : DGETRF, DGETRI pour les matrices réelles et ZGETRF, ZGETRI pour le cas complexe. Pour les matrices de polynomes et de fractions rationnelles inv est basée sur la fonction Scilab invr .


kernel

Scilab Function
Last update : 16/06/2004

kernel - noyau

Calling Sequence

W=kernel(A [,tol,[,flag])

Parameters

  • A : matrice réelle ou complexe (pleine ou creuse)
  • flag : chaîne de caractères
  • tol : nombre réel
  • W : matrice régulière

Description

W=kernel(A) calcule le noyau de A . Les colonnes de W forment une base du noyau de A . Si A est régulière, alors W=[].

flag et tol sont des paramètres optionnels : flag = 'qr' or 'svd' ( 'svd' par défaut).

tol = paramètre de tolérance (de l'ordre de %eps par défaut).

Examples

A=rand(3,1)*rand(1,3);
A*kernel(A)
A=sparse(A);
clean(A*kernel(A))

See Also

colcomp , fullrf , fullrfk , linsolve ,

Author

F.D.;


kroneck

Scilab Function
Last update : 12/01/2004

kroneck - Kronecker form of matrix pencil

Calling Sequence

[Q,Z,Qd,Zd,numbeps,numbeta]=kroneck(F)
[Q,Z,Qd,Zd,numbeps,numbeta]=kroneck(E,A)

Parameters

  • F : real matrix pencil F=s*E-A
  • E,A : two real matrices of same dimensions
  • Q,Z : two square orthogonal matrices
  • Qd,Zd : two vectors of integers
  • numbeps,numeta : two vectors of integers

Description

Kronecker form of matrix pencil: kroneck computes two orthogonal matrices Q, Z which put the pencil F=s*E -A into upper-triangular form:

           | sE(eps)-A(eps) |        X       |      X     |      X        |
           |----------------|----------------|------------|---------------|
           |        O       | sE(inf)-A(inf) |      X     |      X        |
Q(sE-A)Z = |---------------------------------|----------------------------|
           |                |                |            |               |
           |        0       |       0        | sE(f)-A(f) |      X        |
           |--------------------------------------------------------------|
           |                |                |            |               |
           |        0       |       0        |      0     | sE(eta)-A(eta)|

The dimensions of the four blocks are given by:

eps=Qd(1) x Zd(1) , inf=Qd(2) x Zd(2) , f = Qd(3) x Zd(3) , eta=Qd(4)xZd(4)

The inf block contains the infinite modes of the pencil.

The f block contains the finite modes of the pencil

The structure of epsilon and eta blocks are given by:

numbeps(1) = # of eps blocks of size 0 x 1

numbeps(2) = # of eps blocks of size 1 x 2

numbeps(3) = # of eps blocks of size 2 x 3 etc...

numbeta(1) = # of eta blocks of size 1 x 0

numbeta(2) = # of eta blocks of size 2 x 1

numbeta(3) = # of eta blocks of size 3 x 2 etc...

The code is taken from T. Beelen (Slicot-WGS group).

Examples

F=randpencil([1,1,2],[2,3],[-1,3,1],[0,3]);
Q=rand(17,17);Z=rand(18,18);F=Q*F*Z;
//random pencil with eps1=1,eps2=1,eps3=1; 2 J-blocks @ infty
//with dimensions 2 and 3
//3 finite eigenvalues at -1,3,1 and eta1=0,eta2=3
[Q,Z,Qd,Zd,numbeps,numbeta]=kroneck(F);
[Qd(1),Zd(1)]    //eps. part is sum(epsi) x (sum(epsi) + number of epsi)
[Qd(2),Zd(2)]    //infinity part
[Qd(3),Zd(3)]    //finite part
[Qd(4),Zd(4)]    //eta part is (sum(etai) + number(eta1)) x sum(etai)
numbeps
numbeta

See Also

gschur , gspec , systmat , pencan , randpencil , trzeros ,


linsolve

Scilab Function
Last update : 16/06/2004

linsolve - solveur d'équation linéaire

Calling Sequence

[x0,kerA]=linsolve(A,b [,x0])

Parameters

  • A : une matrice réelle na x ma (éventuellement creuse)
  • b : un vecteur na x 1
  • x0 : un vecteur réel
  • kerA : une matrice réelle ma x k

Description

linsolve donne toutes les solutions de A*x+b=0 .

x0 est une solution particulière (s'il en existe une) et kerA est le noyau de A . Tout vecteur de la forme x=x0+kerA*w avec w quelconque vérifie A*x+b=0 .

Si un x0 compatible est donné en entrée, x0 est renvoyé. Dans le cas contraire un x0 compatible, s'il en existe un, est renvoyé.

Examples

A=rand(5,3)*rand(3,8);
b=A*ones(8,1);[x,kerA]=linsolve(A,b);A*x+b   // b compatible
b=ones(5,1);[x,kerA]=linsolve(A,b);A*x+b   // b incompatible
A=rand(5,5);[x,kerA]=linsolve(A,b), -inv(A)*b  // x est unique

See Also

inv , pinv , colcomp , im_inv ,


lsq

Scilab Function
Last update : 11/01/2006

lsq - linear least square problems.

Calling Sequence

X=lsq(A,B [,tol])

Parameters

  • A : Real or complex (m x n) matrix
  • B : real or complex (m x p) matrix
  • tol : positive scalar, used to determine the effective rank of A (defined as the order of the largest leading triangular submatrix R11 in the QR factorization with pivoting of A, whose estimated condition number <= 1/tol. The tol default value is set to sqrt(%eps) .
  • X : real or complex (n x p) matrix

Description

X=lsq(A,B) computes the minimum norm least square solution of the equation A*X=B , while X=A \ B compute a least square solution with at at most rank(A) nonzero components per column.

References

lsq function is based on the LApack functions DGELSY for real matrices and ZGELSY for complex matrices.

Examples

//Build the data
x=(1:10)';

y1=3*x+4.5+3*rand(x,'normal');
y2=1.8*x+0.5+2*rand(x,'normal');
plot2d(x,[y1,y2],[-2,-3])
//Find the linear regression
A=[x,ones(x)];B=[y1,y2];
X=lsq(A,B);

y1e=X(1,1)*x+X(2,1);
y2e=X(1,2)*x+X(2,2);
plot2d(x,[y1e,y2e],[2,3])

//Difference between lsq(A,b) and A\b
A=rand(4,2)*rand(2,3);//a rank 2 matrix
b=rand(4,1);
X1=lsq(A,b)
X2=A\b
[A*X1-b, A*X2-b] //the residuals are the same

See Also

backslash , inv , pinv , rank ,


ludel

Scilab Function
Last update : 16/06/2004

ludel - libération de la mémoire allouée à des facteurs LU creux

Calling Sequence

ludel(hand)

Parameters

  • hand : pointeur vers des facteurs L,U creux déjà calculés (sortie de lufact)

Description

Cette fonction est à utiliser conjointement avec lufact . Elle libère la mémoire allouée pour le stockage des facteurs L,U creux renvoyés par lufact .

La suite de commandes [p,r]=lufact(A);x=lusolve(p,b);ludel(p); résout le système linéaire creux A*x = b et libère les facteurs creux dont p est le pointeur.

See Also

sparse , lufact , luget ,


lufact

Scilab Function
Last update : 16/06/2004

lufact - factorisation LU d'une matrice creuse

Calling Sequence

[hand,rk]=lufact(A,prec)

Parameters

  • A : matrice réelle carrée creuse
  • hand : pointeur vers des facteurs L,U creux
  • rk : entier (rang de A)
  • prec : vecteur à 2 composantes prec=[eps,reps] (tolérances absolue et relative).

Description

[hand,rk]=lufact(A) calcule la factorisation LU d'une matrice creuse A . hand (variable non affichable) est utilisé par lusolve (pour la résolution d'un système linéaire Ax=B) et luget (pour récupérer L et U à partir du pointeur hand ). hand doit être détruit après utilisation (par luget ou lusolve) : ludel(hand) ;

La matrice A n'est pas obligatoirement de rang plein mais doit être carrée (puisque A est supposée creuse on peut lui ajouter des lignes ou des colonnes nulles pour la rendre carrée).

eps : La valeur absolue qu'un élément de A doit avoir pour être utilisé comme pivot, sauf éventuellement en dernier recours. Ce nombre doit être significativement plus petit que le plus petit élément diagonal attendu dans la matrice. La valeur par défaut est %eps .
reps : Ce nombre donne le seuil relatif pour les pivots. Il doit être compris entre zéro et un. S'il vaut un, la méthode se comporte comme un pivot total, qui est très lent et qui a tendance à remplir la matrice. S'il est proche de zéro, la méthode de pivotage est de type Markowitz stricte sans utilisation de seuil. Ce seuil est utilisé pour éliminer les pivots qui causeraient une croissance excessive des termes de la matrice. La croissance des éléments est source d'erreurs d'arrondi, et peut avoir lieu même si la matrice est bien conditionnée. Prendre reps grand réduit cette croissance excessive, et donc les erreurs d'arrondi, mais le prendre trop grand risque d'augmenter le temps d'exécution, ainsi que le remplissage de la matrice. La précision peut donc ainsi être dégradée à cause du nombre élevé d'opérations à effectuer à cause du remplissage. Une valeur correcte semble être 0.001 qui est la valeur par défaut (cette valeur par défaut est aussi utilisée si reps>1 ou reps<0). Cette valeur doit être augmentée et la factorisation doit être recommencée si la croissance s'avère trop importante. Changer le seuil sur les pivots n'améliore pas les performances pour les matrices où la croissance est faible, comme c'est souvent le cas pour les matrices mal conditionnées. La valeur par défaut de reps a été choisie pour un usage de lufact avec des matrices à diagonale à peu près dominante (matrices provenant de problèmes de type éléments finis). Pour ces matrices un pivotage diagonal donne les meilleurs résultats. Pour les matrices à diagonale non dominante, on obtient de meilleurs résultats en prenant un seuil plus élevé, comme 0.01 ou 0.1.

Examples

a=rand(5,5);b=rand(5,1);A=sparse(a);
[h,rk]=lufact(A);
x=lusolve(h,b);a*x-b
ludel(h)

See Also

sparse , lusolve , luget ,


luget

Scilab Function
Last update : 16/06/2004

luget - extraction de facteurs LU creux

Calling Sequence

[P,L,U,Q]=luget(hand)

Parameters

  • hand : pointeur vers des facteurs L,U creux déjà calculés (sortie de lufact)
  • P : matrice de permutation (creuse)
  • L : matrice creuse, triangulaire inférieure si hand provient de la factorisation d'une matrice régulière.
  • U : matrice carrée creuse, régulière, triangulaire supérieure à diagonale unité.
  • Q : matrice de permutation (creuse)

Description

[P,L,U,Q]=luget(hand) avec hand obtenue avec la commande [hand,rk]=lufact(A) avec A une matrice creuse, renvoie quatre matrices P,L,U,Q telles que P*L*U*Q=A .

La matrice A n'est pas obligatoirement de rang plein mais doit être carrée (puisque A est supposée creuse on peut lui ajouter des lignes ou des colonnes nulles pour la rendre carrée).

Si A est singulière, la matrice L est à colonnes compressées (avec rk colonnes indépendantes non nulles) : la matrice creuse régulière Q'*inv(U) compresse les colonnes de A .

Examples

a=rand(5,2)*rand(2,5);A=sparse(a);
[hand,rk]=lufact(A);[P,L,U,Q]=luget(hand);
full(L), P*L*U*Q-A
clean(P*L*U*Q-A)
ludel(hand)

See Also

sparse , lusolve , luget , clean ,


lusolve

Scilab Function
Last update : 17/06/2004

lusolve - solveur de système linéaire creux

Calling Sequence

lusolve(hand,b)
lusolve(A,b)

Parameters

  • b : matrice réelle pleine
  • A : matrice réelle carrée creuse inversible
  • hand : pointeur vers des facteurs L,U creux déjà calculés (sortie de lufact)

Description

x=lusolve(hand,b) résout le système linéaire A*x = b , où hand est obtenu par un appel préliminaire à lufact : [hand,rk]=lufact(A) .

x=lusolve(A,b) résout le système linéaire creux A*x = b

Examples

    non_zeros=[1,2,3,4];rows_cols=[1,1;2,2;3,3;4,4];
    sp=sparse(rows_cols,non_zeros);
    [h,rk]=lufact(sp);x=lusolve(h,[1;1;1;1]);ludel(h)
    rk,sp*x

    non_zeros=[1,2,3,4];rows_cols=[1,1;2,2;3,3;4,4];
    sp=sparse(rows_cols,non_zeros);
    x=lusolve(sp,-ones(4,1));
    sp*x

See Also

sparse , lufact , slash , backslash ,


lu

Scilab Function
Last update : 17/06/2004

lu - factorisation LU

Calling Sequence

[L,U]= lu(A)
[L,U,E]= lu(A)

Parameters

  • A : matrice carrée réelle ou complexe (m x n).
  • L,U : matrices carrées réelles ou complexes (n x n).
  • E : une matrice de permutation.

Description

[L,U]= lu(A) calcule deux matrices L et U telles que A = L*U avec U triangulaire supérieure et L triangulaire inférieure à une permutation des lignes près.

Si A est de rang k , les lignes k+1 à n de U sont nulles.

[L,U,E]= lu(A) calcule trois matrices L , U et E telles que E*A = L*U avec U triangulaire supérieure, L triangulaire inférieure et E une matrice de permutation.

Si A est une matrice réelle, il est possible en utilisant lufact et luget d'obtenir les matrices de permutations et quand A n'est pas inversible la compression des colonnes de la matrice L .

Examples

    a=rand(4,4);
    [l,u]=lu(a)
    norm(l*u-a)

    [h,rk]=lufact(sparse(a))  // lufact fonctionne avec des matrices creuses
    [P,L,U,Q]=luget(h);
    ludel(h)
    P=full(P);L=full(L);U=full(U);Q=full(Q);
    norm(P*L*U*Q-a) // P,Q sont des matrices de permutation

See Also

lufact , luget , lusolve , qr , svd ,

Used Function

La décomposition LU est basée sur les routines Lapack DGETRF pour les matrices réelles et ZGETRF pour le cas complexe.


lyap

Scilab Function
Last update : 17/06/2004

lyap - Equation de Lyapunov

Calling Sequence

[X]=lyap(A,C,flag)

Parameters

  • A, C : matrices réelles, C doit être symétrique
  • flag : chaîne de caractères, 'c' ou 'd'

Description

X = lyap(A,C,flag) résout l'équation matricielle de Lyapunov en temps continu ou discret

      A'*X + X*A = C       ( flag = 'c' )
      A'*X*A - X = C       ( flag = 'd' )

Une solution unique existe si A n'a pas de valeur propre sur l'axe imaginaire ( flag='c' ) ou si 1 n'est pas valeur propre de A ( flag='d' ).

Examples

    A=rand(4,4);C=rand(A);C=C+C';
    X=lyap(A,C,'c');
    A'*X + X*A -C
    X=lyap(A,C,'d');
    A'*X*A - X -C

See Also

sylv , ctr_gram , obs_gram ,


nlev

Scilab Function
Last update : 17/06/2004

nlev - Algorithme de Leverrier

Calling Sequence

[num,den]=nlev(A,z [,rmax])

Parameters

  • A : matrice réelle carrée
  • z : chaîne de caractères
  • rmax : paramètre optionnel (voir bdiag )

Description

[num,den]=nlev(A,z [,rmax]) calcule (z*eye()-A)^(-1) par bloc diagonalisation de A suivie de l'algorithme de Leverrier sur chaque bloc.

Cet algorithme est plus efficace que l'algorithme de Leverrier seul, mais il n'est toujours pas parfait !

Examples

    A=rand(3,3);x=poly(0,'x');
    [NUM,den]=nlev(A,'x')
    clean(den-poly(A,'x'))
    clean(NUM/den-inv(x*eye()-A))

See Also

coff , coffg , glever , ss2tf ,

Authors

F. Delebecque, INRIA;
S. Steer, INRIA;


orth

Scilab Function
Last update : 16/06/2004

orth - calcul d'une base orthogonale

Calling Sequence

Q=orth(A)

Parameters

  • A : matrice réelle ou complexe
  • Q : matrice réelle ou complexe

Description

Q=orth(A) renvoie Q , une base orthogonale de l'image de A . Im( Q ) = Im( A ) et Q'*Q = I .

Le nombre de colonnes de Q est égal au rang de A , comme déterminé par l'algorithme QR.

Examples

A=rand(5,3)*rand(3,4);
[X,dim]=rowcomp(A);X=X';
svd([orth(A),X(:,1:dim)])

See Also

qr , rowcomp , colcomp , range ,


pbig

Scilab Function
Last update : 17/06/2004

pbig - projection sur des sous-espaces propres

Calling Sequence

[Q,M]=pbig(A,thres,flag)

Parameters

  • A : matrice réelle carrée
  • thres : nombre réel
  • flag : chaîne de caractères ( 'c' ou 'd' )
  • Q,M : matrices réelles

Description

Projection sur des sous-espaces propres de A associés aux valeurs propres avec partie réelle >= thres ( flag='c' ) ou avec module >= thres ( flag='d' ).

La projection est définie par Q*M , où Q est de rang maximal, les lignes de M sont linéairement indépendantes et M*Q=eye .

Si flag='c' , les valeurs propres de M*A*Q = valeurs propres de A avec partie réelle >= thres .

Si flag='d' , les valeurs propres de M*A*Q = valeurs propres de A avec module >= thres .

Si flag='c' et si [Q1,M1] = factorisation de rang maximal ( fullrf ) de eye()-Q*M alors les valeurs propres de M1*A*Q1 = valeurs propres de A avec partie réelle < thres .

Si flag='d' et si [Q1,M1] = factorisation de rang maximal ( fullrf ) de eye()-Q*M alors les valeurs propres de M1*A*Q1 = valeurs propres de A avec module < thres .

Examples

    A=diag([1,2,3]);X=rand(A);A=inv(X)*A*X;
    [Q,M]=pbig(A,1.5,'d');
    spec(M*A*Q)
    [Q1,M1]=fullrf(eye()-Q*M);
    spec(M1*A*Q1)

See Also

psmall , projspec , fullrf , schur ,

Author

F. Delebecque, INRIA (1988); ;

Used Function

pbig est basée sur la forme de Schur ordonnée (fonction Scilab schur ).


pencan

Scilab Function
Last update : 12/01/2004

pencan - canonical form of matrix pencil

Calling Sequence

[Q,M,i1]=pencan(Fs)
[Q,M,i1]=pencan(E,A)

Parameters

  • Fs : a regular pencil s*E-A
  • E,A : two real square matrices
  • Q,M : two non-singular real matrices
  • i1 : integer

Description

Given the regular pencil Fs=s*E-A , pencan returns matrices Q and M such than M*(s*E-A)*Q is in "canonical" form.

M*E*Q is a block matrix

[I,0;
 0,N]

with N nilpotent and i1 = size of the I matrix above.

M*A*Q is a block matrix:

[Ar,0;
 0,I]

Examples

F=randpencil([],[1,2],[1,2,3],[]);
F=rand(6,6)*F*rand(6,6);
[Q,M,i1]=pencan(F);
W=clean(M*F*Q)
roots(det(W(1:i1,1:i1)))
det(W($-2:$,$-2:$))

See Also

glever , penlaur , rowshuff ,

Author

F. D.; ;


penlaur

Scilab Function
Last update : 12/01/2004

penlaur - Laurent coefficients of matrix pencil

Calling Sequence

[Si,Pi,Di,order]=penlaur(Fs)
[Si,Pi,Di,order]=penlaur(E,A)

Parameters

  • Fs : a regular pencil s*E-A
  • E, A : two real square matrices
  • Si,Pi,Di : three real square matrices
  • order : integer

Description

penlaur computes the first Laurent coefficients of (s*E-A)^-1 at infinity.

(s*E-A)^-1 = ... + Si/s - Pi - s*Di + ... at s = infinity.

order = order of the singularity (order=index-1).

The matrix pencil Fs=s*E-A should be invertible.

For a index-zero pencil, Pi, Di,... are zero and Si=inv(E) .

For a index-one pencil (order=0), Di =0.

For higher-index pencils, the terms -s^2 Di(2), -s^3 Di(3),... are given by:

Di(2)=Di*A*Di , Di(3)=Di*A*Di*A*Di (up to Di(order) ).

Remark

Experimental version: troubles when bad conditioning of so*E-A

Examples

F=randpencil([],[1,2],[1,2,3],[]);
F=rand(6,6)*F*rand(6,6);[E,A]=pen2ea(F);
[Si,Pi,Di]=penlaur(F);
[Bfs,Bis,chis]=glever(F);
norm(coeff(Bis,1)-Di,1)

See Also

glever , pencan , rowshuff ,

Author

F. Delebecque INRIA(1988,1990) ;


pinv

Scilab Function
Last update : 17/06/2004

pinv - pseudo-inverse

Calling Sequence

pinv(A,[tol])

Parameters

  • A : matrice réelle ou complexe
  • tol : nombre réel

Description

X = pinv(A) renvoie une matrice X de mêmes dimensions que A' telle que :

A*X*A = A, X*A*X = X avec A*X et X*A Hermitiennes.

Le calcul est basé sur une décomposition en valeurs singulières et les valeurs singulières plus petites qu'une tolérance donnée sont considérées comme nulles : pour cela utiliser la syntaxe X=pinv(A,tol) .

Examples

    A=rand(5,2)*rand(2,4);
    norm(A*pinv(A)*A-A,1)

See Also

rank , svd , qr ,

Used Function

La fonction pinv est basée sur la decomposition en valeurs singulières (fonction Scilab svd ).


polar

Scilab Function
Last update : 16/06/2004

polar - forme polaire

Calling Sequence

[Ro,Theta]=polar(A)

Parameters

  • A : matrice carrée réelle ou complexe
  • Ro, Theta : matrices réelles

Description

[Ro,Theta]=polar(A) renvoie la forme polaire de A c'est à dire : A=Ro*expm(%i*Theta) Ro symétrique >=0 et Theta hermitienne >=0.

Examples

A=rand(5,5);
[Ro,Theta]=polar(A);
norm(A-Ro*expm(%i*Theta),1)

See Also

expm , svd ,

Author

F. Delebecque INRIA


projspec

Scilab Function
Last update : 12/01/2004

projspec - spectral operators

Calling Sequence

[S,P,D,i]=projspec(A)

Parameters

  • A : square matrix
  • S, P, D : square matrices
  • i : integer (index of the zero eigenvalue of A ).

Description

Spectral characteristics of A at 0.

S = reduced resolvent at 0 ( S = -Drazin_inverse( A )).

P = spectral projection at 0.

D = nilpotent operator at 0.

index = index of the 0 eigenvalue.

One has (s*eye()-A)^(-1) = D^(i-1)/s^i +... + D/s^2 + P/s - S - s*S^2 -... around the singularity s=0.

Examples

deff('j=jdrn(n)','j=zeros(n,n);for k=1:n-1;j(k,k+1)=1;end')
A=sysdiag(jdrn(3),jdrn(2),rand(2,2));X=rand(7,7);
A=X*A*inv(X);
[S,P,D,index]=projspec(A);
index   //size of J-block
trace(P)  //sum of dimensions of J-blocks
A*S-(eye()-P)
norm(D^index,1)

See Also

coff ,

Author

F. D.; ;


proj

Scilab Function
Last update : 16/06/2004

proj - projection

Calling Sequence

P = proj(X1,X2)

Parameters

  • X1,X2 : deux matrices réelles avec un nombre identique de colonnes.
  • P : matrice réelle de projection ( P^2=P )

Description

P est la projection sur X2 parallèlement à X1 .

Examples

X1=rand(5,2);X2=rand(5,3);
P=proj(X1,X2);
norm(P^2-P,1)
trace(P)    // il s'agit de dim(X2)
[Q,M]=fullrf(P);
svd([Q,X2])   // Im(Q) = Im(X2)

See Also

projspec , orth , fullrf ,

Author

F. D.; ;


psmall

Scilab Function
Last update : 12/01/2004

psmall - spectral projection

Calling Sequence

[Q,M]=psmall(A,thres,flag)

Parameters

  • A : real square matrix
  • thres : real number
  • flag : character string ( 'c' or 'd' )
  • Q,M : real matrices

Description

Projection on eigen-subspace associated with eigenvalues with real part < thres ( flag='c' ) or with modulus < thres ( flag='d' ).

The projection is defined by Q*M , Q is full column rank, M is full row rank and M*Q=eye .

If flag='c' , the eigenvalues of M*A*Q = eigenvalues of A with real part < thres .

If flag='d' , the eigenvalues of M*A*Q = eigenvalues of A with magnitude < thres .

If flag='c' and if [Q1,M1] = full rank factorization ( fullrf ) of eye()-Q*M then eigenvalues of M1*A*Q1 = eigenvalues of A with real part >= thres .

If flag='d' and if [Q1,M1] = full rank factorization ( fullrf ) of eye()-Q*M then eigenvalues of M1*A*Q1 = eigenvalues of A with magnitude >= thres .

Examples

A=diag([1,2,3]);X=rand(A);A=inv(X)*A*X;
[Q,M]=psmall(A,2.5,'d');
spec(M*A*Q)
[Q1,M1]=fullrf(eye()-Q*M);
spec(M1*A*Q1)

See Also

pbig , proj , projspec ,

Author

F. Delebecque INRIA. (1988);

Used Function

This function is based on the ordered schur form (scilab function schur ).


qr

Scilab Function
Last update : 17/06/2004

qr - factorisation QR

Calling Sequence

[Q,R]=qr(X [,"e"])
[Q,R,E]=qr(X [,"e"])
[Q,R,rk,E]=qr(X [,tol])

Parameters

  • X : matrice réelle ou complexe
  • tol : nombre réel positif
  • Q : matrice carrée unitaire
  • R : matrice de même dimensions que X
  • E : matrice de permutation
  • rk : entier (rang de X )

Description

[Q,R] = qr(X) renvoie une matrice triangulaire supérieure R de même dimensions que X et une matrice carrée othogonale (unitaire dans le cas complexe) Q telles que X = Q*R . [Q,R] = qr(X,"e") renvoie une decomposition de taille réduite: si X est une matrice m x n avec m > n alors seulement les n premières colonnes de Q sont calculées ainsi que les n premières lignes de R .

Il découle de Q*R = X que la k ième colonne de X peut s'exprimer comme une combinaison linéaire des k premieres colonnes de Q (avec les coefficients R(1,k), ..., R(k,k) . Les k premieres colonnes de Q forment une base orthogonale du sous espace généré par les Les k premieres colonnes de X . Si la colonne k de X est une combinaison linéaire des p premiéres colonnes de X alors les éléments R(p+1,k), ..., R(k,k) sont nuls. Dans cette situation R est une matrice trapézoidale supérieure. Si X est de rang rk alors les lignes R(rk+1,:), R(rk+2,:), ... sont nulles.

[Q,R,E] = qr(X) renvoie une matrice de permutations (de colonnes) E , une matrice triangulaire supérieure R dont les éléments diagonaux sont classés par ordre décroissant et une matrice unitaire Q telles que X*E = Q*R . si rk est le rang de X les rk premiers éléménts diagonaux de R sont tous non nuls. [Q,R,E] = qr(X,"e") renvoie une decomposition de taille réduite: si X est une matrice m x n avec m > n alors seulement les n premières colonnes de Q sont calculées ainsi que les n premières lignes de R .

[Q,R,rk,E] = qr(X [,tol]) renvoie de plus rk =rang estimé de X . Plus précisément, rk est le nombre d'éléments diagonaux de R supérieurs à tol . La valeur par défaut de tol est R(1,1)*%eps*max(size(R))

renvoie rk = rang estimé de X . Ici, rk est le nombre d'éléments diagonaux de R supérieurs à R(1,1)*%eps*max(size(R) .

Examples

    // QR factorization, generic case
    // X is tall (full rank)
    X=rand(5,2);[Q,R]=qr(X); [Q'*X R]
    //X is fat (full rank)
    X=rand(2,3);[Q,R]=qr(X); [Q'*X R]
    //Column 4 of X is a linear combination of columns 1 and 2:
    X=rand(8,5);X(:,4)=X(:,1)+X(:,2); [Q,R]=qr(X); R, R(:,4)
    //X has rank 2, rows 3 to $ of R are zero:
    X=rand(8,2)*rand(2,5);[Q,R]=qr(X); R
    //Evaluating the rank rk: column pivoting ==> rk first
    //diagonal entries of R are non zero :
    A=rand(5,2)*rand(2,5);
    [Q,R,rk,E] = qr(A,1.d-10);
    norm(Q'*A-R)
    svd([A,Q(:,1:rk)])    //span(A) =span(Q(:,1:rk))

See Also

rank , svd , rowcomp , colcomp ,

Used Function

La décomposition QR est basée sur les routines Lapack DGEQRF, DGEQPF, DORGQR pour les matrices réelles et ZGEQRF, ZGEQPF, ZORGQR pour le cas complexe.


quaskro

Scilab Function
Last update : 12/01/2004

quaskro - quasi-Kronecker form

Calling Sequence

[Q,Z,Qd,Zd,numbeps,numbeta]=quaskro(F)
[Q,Z,Qd,Zd,numbeps,numbeta]=quaskro(E,A)
[Q,Z,Qd,Zd,numbeps,numbeta]=quaskro(F,tol)
[Q,Z,Qd,Zd,numbeps,numbeta]=quaskro(E,A,tol)

Parameters

  • F : real matrix pencil F=s*E-A ( s=poly(0,'s') )
  • E,A : two real matrices of same dimensions
  • tol : a real number (tolerance, default value=1.d-10)
  • Q,Z : two square orthogonal matrices
  • Qd,Zd : two vectors of integers
  • numbeps : vector of integers

Description

Quasi-Kronecker form of matrix pencil: quaskro computes two orthogonal matrices Q, Z which put the pencil F=s*E -A into upper-triangular form:

           | sE(eps)-A(eps) |        X       |      X     |
           |----------------|----------------|------------|
           |        O       | sE(inf)-A(inf) |      X     |
Q(sE-A)Z = |=================================|============|
           |                                 |            |
           |                O                | sE(r)-A(r) |

The dimensions of the blocks are given by:

eps=Qd(1) x Zd(1) , inf=Qd(2) x Zd(2) , r = Qd(3) x Zd(3)

The inf block contains the infinite modes of the pencil.

The f block contains the finite modes of the pencil

The structure of epsilon blocks are given by:

numbeps(1) = # of eps blocks of size 0 x 1

numbeps(2) = # of eps blocks of size 1 x 2

numbeps(3) = # of eps blocks of size 2 x 3 etc...

The complete (four blocks) Kronecker form is given by the function kroneck which calls quaskro on the (pertransposed) pencil sE(r)-A(r) .

The code is taken from T. Beelen

See Also

kroneck , gschur , gspec ,


randpencil

Scilab Function
Last update : 12/01/2004

randpencil - random pencil

Calling Sequence

F=randpencil(eps,infi,fin,eta)

Parameters

  • eps : vector of integers
  • infi : vector of integers
  • fin : real vector, or monic polynomial, or vector of monic polynomial
  • eta : vector of integers
  • F : real matrix pencil F=s*E-A ( s=poly(0,'s') )

Description

Utility function. F=randpencil(eps,infi,fin,eta) returns a random pencil F with given Kronecker structure. The structure is given by: eps=[eps1,...,epsk] : structure of epsilon blocks (size eps1x(eps1+1),....) fin=[l1,...,ln] set of finite eigenvalues (assumed real) (possibly []) infi=[k1,...,kp] size of J-blocks at infinity ki>=1 (infi=[] if no J blocks). eta=[eta1,...,etap] : structure ofeta blocks (size eta1+1)xeta1,...)

epsi 's should be >=0, etai 's should be >=0, infi 's should be >=1.

If fin is a (monic) polynomial, the finite block admits the roots of fin as eigenvalues.

If fin is a vector of polynomial, they are the finite elementary divisors of F i.e. the roots of p(i) are finite eigenvalues of F .

Examples

F=randpencil([0,1],[2],[-1,0,1],[3]);
[Q,Z,Qd,Zd,numbeps,numbeta]=kroneck(F);
Qd, Zd
s=poly(0,'s');
F=randpencil([],[1,2],s^3-2,[]); //regular pencil
det(F)

See Also

kroneck , pencan , penlaur ,


range

Scilab Function
Last update : 06/04/2006

range - Image de A^k

Calling Sequence

[X,dim]=range(A,k)

Parameters

  • A : matrice réelle carrée
  • k : entier non négatif, La valeur par défaut est 1
  • X : matrice réelle orthonormale.
  • dim : entier (dimension du sous-espace image)

Description

Calcul de l'image de A^k ; les dim premières colonnes de X forment une base de A^k . Les dernières lignes de X forment une base de l'orthogonal de l'image.

Examples

    A=rand(4,2)*rand(2,4);   // Matrice de rang 2.
    [X,dim]=range(A,1);dim   // Calcul de l'image

    y1=A*rand(4,1);          // un vecteur dans l'image de A
    y2=rand(4,1);            // un vecteur qui n'est pas dans l'image
    norm(X(dim+1:$,:)*y1)    // les derniéres composante sont nulles, y1 est
    dans l'image
    norm(X(dim+1:$,:)*y2)    // Les dernieres composantes ne sont pas nulles

    I=X(1:dim,:)'            // I une base de l'image
    coeffs=X(1:dim,:)*y1     // les composante de y1 dans la base I

    norm(I*coeffs-y1)        // test

See Also

fullrfk , rowcomp ,

Author

F. D.; INRIA ;

Used Function

La fonction range est basée sue la fonction rowcomp qui utilise la décomposition svd .


rankqr

Scilab Function
Last update : 12/01/2004

rankqr - rank revealing QR factorization

Calling Sequence

[Q,R,JPVT,RANK,SVAL]=rankqr(A, [RCOND,JPVT])

Parameters

  • A : real or complex matrix
  • RCOND : real number used to determine the effective rank of A , which is defined as the order of the largest leading triangular submatrix R11 in the QR factorization with pivoting of A , whose estimated condition number < 1/RCOND .
  • JPVT

    : integer vector on entry, if JPVT(i) is not 0, the i -th column of A is permuted to the front of AP , otherwise column i is a free column. On exit, if JPVT(i) = k , then the i -th column of A*P was the k -th column of A .

  • RANK : the effective rank of A , i.e., the order of the submatrix R11 . This is the same as the order of the submatrix T1 in the complete orthogonal factorization of A .
  • SVAL : real vector with 3 components; The estimates of some of the singular values of the triangular factor R .

    SVAL(1) is the largest singular value of R(1:RANK,1:RANK) ;

    SVAL(2) is the smallest singular value of R(1:RANK,1:RANK) ;

    SVAL(3) is the smallest singular value of R(1:RANK+1,1:RANK+1) , if RANK < MIN(M,N) , or of R(1:RANK,1:RANK) , otherwise.

Description

To compute (optionally) a rank-revealing QR factorization of a real general M-by-N real or complex matrix A , which may be rank-deficient, and estimate its effective rank using incremental condition estimation.

The routine uses a QR factorization with column pivoting:

        A * P = Q * R,  where  R = [ R11 R12 ],
                                   [  0  R22 ]

with R11 defined as the largest leading submatrix whose estimated condition number is less than 1/RCOND . The order of R11 , RANK , is the effective rank of A .

If the triangular factorization is a rank-revealing one (which will be the case if the leading columns were well- conditioned), then SVAL(1) will also be an estimate for the largest singular value of A , and SVAL(2) and SVAL(3) will be estimates for the RANK -th and (RANK+1) -st singular values of A , respectively.

By examining these values, one can confirm that the rank is well defined with respect to the chosen value of RCOND . The ratio SVAL(1)/SVAL(2) is an estimate of the condition number of R(1:RANK,1:RANK) .

Examples

A=rand(5,3)*rand(3,7);
[Q,R,JPVT,RANK,SVAL]=rankqr(A,%eps)

See Also

qr , rank ,

Used Function

Slicot library routines MB03OD, ZB03OD.


rank

Scilab Function
Last update : 16/06/2004

rank - rang

Calling Sequence

[i]=rank(X)
[i]=rank(X,tol)

Parameters

  • X : matrice réelle ou complexe
  • tol : nombre réel positif

Description

rank(X) calcule le rang "numérique" de X c'est à dire le nombre de ses valeurs singulières supérieures à norm(size(X),'inf') * norm(X) * %eps .

rank(X,tol) est le nombre de valeurs singulières de X supérieures à tol .

Notez que la valeur par défaut de tol est proportionnelle à norm(X) . Par exemple

rank([1.d-80,0;0,1.d-80]) vaut 2 !.

Examples

rank([1.d-80,0;0,1.d-80])
rank([1,0;0,1.d-80])

See Also

svd , qr , rowcomp , colcomp , lu ,


rcond

Scilab Function
Last update : 16/06/2004

rcond - estimation de l'inverse du conditionnement

Calling Sequence

rcond(X)

Parameters

  • X : matrice carrée réelle ou complexe

Description

rcond(X) est une estimation de l'inverse du conditionnement de X pour la norme l_1.

Si X est bien conditionnée, rcond(X) est proche 1. Sinon, rcond(X) est proche de 0.

[r,z]=rcond(X) renvoie rcond(X) dans r et renvoie aussi z tel que norm(X*z,1) = r*norm(X,1)*norm(z,1)

Ainsi, si rcond est très petit z est un vecteur se trouvant dans le noyau de X.

Examples

A=diag([1:10]);
rcond(A)
A(1,1)=0.000001;
rcond(A)

See Also

svd , cond , inv ,


rowcomp

Scilab Function
Last update : 06/04/2006

rowcomp - compression de lignes, image

Calling Sequence

[W,rk]=colcomp(A [,flag [,tol]])

Parameters

  • A : matrice réelle ou complexe
  • flag : chaîne de caractères optionnelle qui peut prendre les valeurs 'svd' ou 'qr' . La valeur par défaut est sqrt(%eps)*norm(A,1) .
  • tol : nombre réel non négatif. La valeur par défaut est sqrt(%eps)*norm(A,1) .
  • W : matrice carrée régulière (matrice de changement de base)
  • rk : entier (rang de" A ).

Description

Compression des colonnes de A . Ac = W*A est à lignes compressées, c'est à dire Ac=[Af;0] et les lignes de Af sont linéairement indépendantes.

flag et tol sont des paramètres optionnels : flag = 'qr' ou 'svd' ( 'svd' par défaut).

tol = paramètre de tolérance (de l'ordre de %eps par défaut).

Les rk premières colonnes de W' forment une base de l'image de A .

Un vecteur non nul x appartient à Im( A ) si W*x est à lignes compressées en accord avec Ac c'est à dire que la norme de ses dernières composantes est nulle (à la précision machine) par rapport à ses rk premières composantes.

Examples

    A=rand(5,2)*rand(2,4);          // 4 vecteurs colonne dont 2 indépendants
    [X,dim]=rowcomp(A);Xp=X';
    svd([Xp(:,1:dim),A])            // Im(A) = Im(Xp(:,1:dim)
    x=A*rand(4,1);                  // x appartient à Im(A)
    y=X*x
    norm(y(dim+1:$))/norm(y(1:dim)) // la norme est petite

See Also

colcomp , fullrf , fullrfk ,

Author

F. D.; INRIA

Used Function

La fonction rowcomp est basée sur les décompositions svd ou qr .


rowshuff

Scilab Function
Last update : 12/01/2004

rowshuff - shuffle algorithm

Calling Sequence

[Ws,Fs1]=rowshuff(Fs, [alfa])

Parameters

  • Fs : square real pencil Fs = s*E-A
  • Ws : polynomial matrix
  • Fs1 : square real pencil F1s = s*E1 -A1 with E1 non-singular
  • alfa : real number ( alfa = 0 is the default value)

Description

Shuffle algorithm: Given the pencil Fs=s*E-A , returns Ws=W(s) (square polynomial matrix) such that:

Fs1 = s*E1-A1 = W(s)*(s*E-A) is a pencil with non singular E1 matrix.

This is possible iff the pencil Fs = s*E-A is regular (i.e. invertible). The degree of Ws is equal to the index of the pencil.

The poles at infinity of Fs are put to alfa and the zeros of Ws are at alfa .

Note that (s*E-A)^-1 = (s*E1-A1)^-1 * W(s) = (W(s)*(s*E-A))^-1 *W(s)

Examples

F=randpencil([],[2],[1,2,3],[]);
F=rand(5,5)*F*rand(5,5);   // 5 x 5 regular pencil with 3 evals at 1,2,3
[Ws,F1]=rowshuff(F,-1);
[E1,A1]=pen2ea(F1);
svd(E1)           //E1 non singular
roots(det(Ws))
clean(inv(F)-inv(F1)*Ws,1.d-7)

See Also

pencan , glever , penlaur ,

Author

F. D.; ; ; ; ;


rref

Scilab Function
Last update : 12/01/2004

rref - computes matrix row echelon form by lu transformations

Calling Sequence

R=rref(A)

Parameters

  • A : m x n matrix with scalar entries
  • R : m x n matrix,row echelon form of a

Description

rref computes the row echelon form of the given matrix by left lu decomposition. If ones need the transformation used just call X=rref([A,eye(m,m)]) the row echelon form R is X(:,1:n) and the left transformation L is given by X(:,n+1:n+m) such as L*A=R

Examples

A=[1 2;3 4;5 6];
X=rref([A,eye(3,3)]);
R=X(:,1:2)
L=X(:,3:5);L*A

See Also

lu , qr ,


schur

Scilab Function
Last update : 12/01/2004

schur - [ordered] Schur decomposition of matrix and pencils

Calling Sequence

[U,T] = schur(A)
[U,dim [,T] ]=schur(A,flag)
[U,dim [,T] ]=schur(A,extern1)
[As,Es [,Q,Z]]=schur(A,E)
[As,Es [,Q],Z,dim] = schur(A,E,flag)
[Z,dim] = schur(A,E,flag)
[As,Es [,Q],Z,dim]= schur(A,E,extern2)
[Z,dim]= schur(A,E,extern2)

Parameters

  • A : real or complex square matrix.
  • E : real or complex square matrix with same dimensions as A .
  • flag : character string ( 'c' or 'd' )
  • extern1 : an ``external'', see below
  • extern2 : an ``external'', see below
  • U : orthogonal or unitary square matrix
  • Q : orthogonal or unitary square matrix
  • Z : orthogonal or unitary square matrix
  • T : upper triangular or quasi-triangular square matrix
  • As : upper triangular or quasi-triangular square matrix
  • Es : upper triangular square matrix
  • dim : integer

Description

Schur forms, ordered Schur forms of matrices and pencils

MATRIX SCHUR FORM
Usual schur form:

[U,T] = schur(A) produces a Schur matrix T and a unitary matrix U so that A = U*T*U' and U'*U = eye(U) . By itself, schur( A ) returns T . If A is complex, the Complex Schur Form is returned in matrix T . The Complex Schur Form is upper triangular with the eigenvalues of A on the diagonal. If A is real, the Real Schur Form is returned. The Real Schur Form has the real eigenvalues on the diagonal and the complex eigenvalues in 2-by-2 blocks on the diagonal.

Ordered Schur forms [U,dim]=schur(A,'c') returns an unitary matrix U which transforms A into schur form. In addition, the dim first columns of U make a basis of the eigenspace of A associated with eigenvalues with negative real parts (stable "continuous time" eigenspace).

[U,dim]=schur(A,'d') returns an unitary matrix U which transforms A into schur form. In addition, the dim first columns of U span a basis of the eigenspace of A associated with eigenvalues with magnitude lower than 1 (stable "discrete time" eigenspace).

[U,dim]=schur(A,extern1) returns an unitary matrix U which transforms A into schur form. In addition, the dim first columns of U span a basis of the eigenspace of A associated with the eigenvalues which are selected by the external function extern1 (see external for details). This external can be described by a Scilab function or by C or Fortran procedure:

a Scilab functionIf extern1 is described by a Scilab function, it should have the following calling sequence: s=extern1(Ev) , where Ev is an eigenvalue and s a boolean.
a C or Fortran procedureIf extern1 is described by a C or Fortran function it should have the following calling sequence: int extern1(double *EvR, double *EvI) where EvR and EvI are eigenvalue real and complex parts. a true or non zero returned value stands for selected eigenvalue.
PENCIL SCHUR FORMS
Usual Pencil Schur form [As,Es] = schur(A,E) produces a quasi triangular As matrix and a triangular Es matrix which are the generalized Schur form of the pair A, E .

[As,Es,Q,Z] = schur(A,E) returns in addition two unitary matrices Q and Z such that As=Q'*A*Z and Es=Q'*E*Z .

Ordered Schur forms: [As,Es,Z,dim] = schur(A,E,'c') returns the real generalized Schur form of the pencil s*E-A . In addition, the dim first columns of Z span a basis of the right eigenspace associated with eigenvalues with negative real parts (stable "continuous time" generalized eigenspace).

[As,Es,Z,dim] = schur(A,E,'d')

returns the real generalized Schur form of the pencil s*E-A . In addition, the dim first columns of Z make a basis of the right eigenspace associated with eigenvalues with magnitude lower than 1 (stable "discrete time" generalized eigenspace).

[As,Es,Z,dim] = schur(A,E,extern2)

returns the real generalized Schur form of the pencil s*E-A . In addition, the dim first columns of Z make a basis of the right eigenspace associated with eigenvalues of the pencil which are selected according to a rule which is given by the function extern2 . (see external for details). This external can be described by a Scilab function or by C or Fortran procedure:

A Scilab functionIf extern2 is described by a Scilab function, it should have the following calling sequence: s=extern2(Alpha,Beta) , where Alpha and Beta defines a generalized eigenvalue and s a boolean.
C or Fortran procedureif external extern2 is described by a C or a Fortran procedure, it should have the following calling sequence:

int extern2(double *AlphaR, double *AlphaI, double *Beta)

if A and E are real and

int extern2(double *AlphaR, double *AlphaI, double *BetaR, double *BetaI)

if A or E are complex. Alpha , and Beta defines the generalized eigenvalue. a true or non zero returned value stands for selected generalized eigenvalue.

References

Matrix schur form computations are based on the Lapack routines DGEES and ZGEES.

Pencil schur form computations are based on the Lapack routines DGGES and ZGGES.

Examples

//SCHUR FORM OF A MATRIX
//----------------------
A=diag([-0.9,-2,2,0.9]);X=rand(A);A=inv(X)*A*X;
[U,T]=schur(A);T

[U,dim,T]=schur(A,'c');
T(1:dim,1:dim)      //stable cont. eigenvalues

function t=mytest(Ev),t=abs(Ev)<0.95,endfunction
[U,dim,T]=schur(A,mytest);
T(1:dim,1:dim)

// The same function in C (a Compiler is required)
C=['int mytest(double *EvR, double *EvI) {' //the C code
   'if (*EvR * *EvR + *EvI * *EvI < 0.9025) return 1;'
   'else return 0; }';]
mputl(C,TMPDIR+'/mytest.c')

//build and link
lp=ilib_for_link('mytest','mytest.o',[],'c',TMPDIR+'/Makefile');
link(lp,'mytest','c');

//run it
[U,dim,T]=schur(A,'mytest');
//SCHUR FORM OF A PENCIL
//----------------------
F=[-1,%s, 0,   1;
    0,-1,5-%s, 0;
    0, 0,2+%s, 0;
    1, 0, 0, -2+%s];
A=coeff(F,0);E=coeff(F,1);
[As,Es,Q,Z]=schur(A,E);
Q'*F*Z //It is As+%s*Es

[As,Es,Z,dim] = schur(A,E,'c')
function t=mytest(Alpha,Beta),t=real(Alpha)<0,endfunction
[As,Es,Z,dim] = schur(A,E,mytest)

//the same function in Fortran (a Compiler is required)
ftn=['integer function mytestf(ar,ai,b)' //the fortran code
      'double precision ar,ai,b'
      'mytestf=0'
      'if(ar.lt.0.0d0) mytestf=1'
      'end']
mputl('      '+ftn,TMPDIR+'/mytestf.f')

//build and link
lp=ilib_for_link('mytestf','mytestf.o',[],'F',TMPDIR+'/Makefile');
link(lp,'mytestf','f');

//run it

[As,Es,Z,dim] = schur(A,E,'mytestf')

See Also

spec , bdiag , ricc , pbig , psmall ,


spaninter

Scilab Function
Last update : 12/01/2004

spaninter - subspace intersection

Calling Sequence

[X,dim]=spaninter(A,B [,tol])

Parameters

  • A, B : two real or complex matrices with equal number of rows
  • X : orthogonal or unitary square matrix
  • dim : integer, dimension of subspace range( A ) inter range( B )

Description

computes the intersection of range( A ) and range( B ).

The first dim columns of X span this intersection i.e. X(:,1:dim) is an orthogonal basis for

range( A ) inter range( B )

In the X basis A and B are respectively represented by:

X'*A and X'*B .

tol is a threshold ( sqrt(%eps) is the default value).

Examples

A=rand(5,3)*rand(3,4);     // A is 5 x 4, rank=3
B=[A(:,2),rand(5,1)]*rand(2,2);
[X,dim]=spaninter(A,B);
X1=X(:,1:dim);    //The intersection
svd(A),svd([X1,A])   // X1 in span(A)
svd(B),svd([B,X1])   // X1 in span(B)

See Also

spanplus , spantwo ,

Author

F. D.; ;


spanplus

Scilab Function
Last update : 12/01/2004

spanplus - sum of subspaces

Calling Sequence

[X,dim,dima]=spanplus(A,B[,tol])

Parameters

  • A, B : two real or complex matrices with equal number of rows
  • X : orthogonal or unitary square matrix
  • dim, dima : integers, dimension of subspaces
  • tol : nonnegative real number

Description

computes a basis X such that:

the first dima columns of X span Range( A ) and the following ( dim-dima ) columns make a basis of A+B relative to A .

The dim first columns of X make a basis for A+B .

One has the following canonical form for [A,B] :

         [*,*]    (dima rows)
X'*[A,B]=[0,*]    (dim-dima rows)
         [0,0]

tol is an optional argument (see function code).

Examples

A=rand(6,2)*rand(2,5);      // rank(A)=2
B=[A(:,1),rand(6,2)]*rand(3,3);   //two additional independent vectors
[X,dim,dimA]=spanplus(A,B);
dimA
dim

See Also

spaninter , im_inv , spantwo ,

Author

F. D.; ;


spantwo

Scilab Function
Last update : 12/01/2004

spantwo - sum and intersection of subspaces

Calling Sequence

[Xp,dima,dimb,dim]=spantwo(A,B, [tol])

Parameters

  • A, B : two real or complex matrices with equal number of rows
  • Xp : square non-singular matrix
  • dima, dimb, dim : integers, dimension of subspaces
  • tol : nonnegative real number

Description

Given two matrices A and B with same number of rows, returns a square matrix Xp (non singular but not necessarily orthogonal) such that :

         [A1, 0]    (dim-dimb rows)
Xp*[A,B]=[A2,B2]    (dima+dimb-dim rows)
         [0, B3]    (dim-dima rows)
         [0 , 0]

The first dima columns of inv(Xp) span range( A ).

Columns dim-dimb+1 to dima of inv(Xp) span the intersection of range(A) and range(B).

The dim first columns of inv(Xp) span range( A )+range( B ).

Columns dim-dimb+1 to dim of inv(Xp) span range( B ).

Matrix [A1;A2] has full row rank (=rank(A)). Matrix [B2;B3] has full row rank (=rank(B)). Matrix [A2,B2] has full row rank (=rank(A inter B)). Matrix [A1,0;A2,B2;0,B3] has full row rank (=rank(A+B)).

Examples

A=[1,0,0,4;
   5,6,7,8;
   0,0,11,12;
   0,0,0,16];
B=[1,2,0,0]';C=[4,0,0,1];
Sl=ss2ss(syslin('c',A,B,C),rand(A));
[no,X]=contr(Sl('A'),Sl('B'));CO=X(:,1:no);  //Controllable part
[uo,Y]=unobs(Sl('A'),Sl('C'));UO=Y(:,1:uo);  //Unobservable part
[Xp,dimc,dimu,dim]=spantwo(CO,UO);    //Kalman decomposition
Slcan=ss2ss(Sl,inv(Xp));

See Also

spanplus , spaninter ,

Author

F. D.


spchol

Scilab Function
Last update : 16/06/2004

spchol - Factorisation de Cholesky creuse

Calling Sequence

[R,P] = spchol(X)

Parameters

  • X : matrice creuse réelle ou complexe
  • P : matrice de permutation
  • R : facteur de Cholesky

Description

[R,P] = spchol(X) produit une matrice triangulaire inférieure R telle que P*R*R'*P' = X .

Examples

X=[
3.,  0.,  0.,  2.,  0.,  0.,  2.,  0.,  2.,  0.,  0. ;
0.,  5.,  4.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0. ;
0.,  4.,  5.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0. ;
2.,  0.,  0.,  3.,  0.,  0.,  2.,  0.,  2.,  0.,  0. ;
0.,  0.,  0.,  0. , 5.,  0.,  0.,  0.,  0.,  0.,  4. ;
0.,  0.,  0.,  0.,  0.,  4.,  0.,  3.,  0.,  3.,  0. ;
2.,  0.,  0.,  2.,  0.,  0.,  3.,  0.,  2.,  0.,  0. ;
0.,  0.,  0.,  0.,  0.,  3.,  0.,  4.,  0.,  3.,  0. ;
2.,  0.,  0.,  2.,  0.,  0.,  2.,  0.,  3.,  0.,  0. ;
0.,  0.,  0.,  0.,  0.,  3.,  0.,  3.,  0.,  4.,  0. ;
0.,  0.,  0.,  0.,  4.,  0.,  0.,  0.,  0.,  0.,  5.];
X=sparse(X);[R,P] = spchol(X);
max(P*R*R'*P'-X)

See Also

sparse , lusolve , luget , chol ,


spec

Scilab Function
Last update : 17/06/2004

spec - valeurs propres d'une matrice

Calling Sequence

evals=spec(A)
[X,diagevals]=spec(A)
evals=spec(A,E)
[al,be]=spec(A,E)
[al,be,Z]=spec(A,E)
[al,be]=spec(A,E)
[al,be,Q,Z]=spec(A,E)

Parameters

  • A : matrice carrée réelle ou complexe
  • E : matrice carrée réelle ou complexe de même dimensions que A
  • evals : vecteur réel ou complexe
  • diagevals : matrice carrée diagonale réelle ou complexe (les éléments diagonaux sont les valeurs propres)
  • al : vecteur réel ou complexe, al./be donnes les valeurs propres
  • be : vecteur réel ou complexe, al./be donnes les valeurs propres
  • X : matrice carrée inversible réelle ou complexe, matrices des vecteurs propres.
  • Q : matrice carrée inversible réelle ou complexe, matrices des vecteurs propres à gauche.
  • Z : atrice carrée inversible réelle ou complexe, matrices des vecteurs propres à droite.

Description

spec(A) : evals=spec(A) retourne dans le vecteur evals les valeurs propres de A .

[evals,X] =spec(A) retourne de plus les vecteurs propres (s'ils existent). Voir aussi bdiag

spec(A,B) : evals=spec(A,E) retourne le spectre du faisceau s E - A , c'est à dire les racines du déterminant de la matrice de polynômes s E - A .

[al,be] = spec(A,E) retourne le spectre du faisceau s E - A , c'est à dire les racines du déterminant de la matrice de polynômes s E - A . Les valeurs propres sont données par al./be . Si be(i) = 0 la i ième valeur propres est à l'infini. (Pour E = eye(A), al./be est spec(A) ).

[al,be,Z] = spec(A,E) retourne de plus la matrice Z des vecteurs propres généralisés à droite.

[al,be,Q,Z] = spec(A,E) retourne de plus les matrices Q et Z des vecteurs propres généralisés à droite et à gauche.

Examples

    // MATRIX EIGENVALUES
    A=diag([1,2,3]);X=rand(3,3);A=inv(X)*A*X;
    spec(A)
    //
    x=poly(0,'x');
    pol=det(x*eye()-A)
    roots(pol)
    //
    [S,X]=bdiag(A);
    clean(inv(X)*A*X)

    // PENCIL EIGENVALUES
    A=rand(3,3);
    [al,be,Z] = spec(A,eye(A));al./be
    clean(inv(Z)*A*Z)  //displaying the eigenvalues (generic matrix)
    A=A+%i*rand(A);E=rand(A);
    roots(det(%s*E-A))   //complex case

See Also

poly , det , gspec , schur , bdiag , colcomp ,

Used Function

Le calcul des valeurs propres des matrices est basé sur les routines Lapack DGEEV and ZGEEV.

Le calcul des valeurs propres des matrices est basé sur les routines Lapack DGEEV and ZGEEV.


sqroot

Scilab Function
Last update : 16/06/2004

sqroot - factorisation hermitienne W*W'

Calling Sequence

sqroot(X)

Parameters

  • X : matrice complexe ou réelle, symétrique définie non-négative

Description

renvoie W telle que X=W*W' (en utilisant svd).

Examples

X=rand(5,2)*rand(2,5);X=X*X';
W=sqroot(X)
norm(W*W'-X,1)
//
X=rand(5,2)+%i*rand(5,2);X=X*X';
W=sqroot(X)
norm(W*W'-X,1)

See Also

chol , svd ,


sva

Scilab Function
Last update : 16/06/2004

sva - approximation de valeurs singulières

Calling Sequence

[U,s,V]=sva(A,k)
[U,s,V]=sva(A,tol)

Parameters

  • A : matrice réelle ou complexe
  • k : entier
  • tol : nombre réel positif

Description

Approximation de valeurs singulières.

[U,S,V]=sva(A,k) avec k un entier >=1, renvoie U,S et V telles que B=U*S*V' est la meilleure approximation au sens l_2 de A avec rang( B )= k .

[U,S,V]=sva(A,tol) où tol est un réel positif, renvoie U,S et V tels que B=U*S*V' et la norme l_2 de A-B est inférieure à tol .

Examples

A=rand(5,4)*rand(4,5);
[U,s,V]=sva(A,2);
B=U*s*V';
svd(A)
svd(B)
clean(svd(A-B))

See Also

svd ,


svd

Scilab Function
Last update : 17/06/2004

svd - décomposition en valeurs singulières

Calling Sequence

s=svd(X)
[U,S,V]=svd(X)
[U,S,V]=svd(X,0) (obsolete)
[U,S,V]=svd(X,"e")
[U,S,V,rk]=svd(X [,tol])

Parameters

  • X : matrice réelle ou complexe
  • s : vecteur réel (valeurs singulières)
  • S : matrice réelle diagonale (valeurs singulières sur la diagonale)
  • U,V : matrices carrées unitaires (vecteurs singuliers).
  • tol : nombre réel positif

Description

[U,S,V]=svd(X) renvoie une matrice diagonale S , de même dimension que X avec des éléments diagonaux positifs classés par ordre décroissant, ainsi que deux matrices unitaires U et V telles que X = U*S*V' . [U,S,V]=svd(X,"e") renvoie la décomposition réduite : si X est une matrice m x n et que m > n alors seulement les n premières colonnes de U sont calculées et S est n x n .

s=svd(X) renvoie un vecteur s contenant les valeurs singulières.

[U,S,V,rk]=svd(X [,tol]) renvoie de plus rk , le rang "numérique" de X c'est à dire le nombre de valeurs singulières plus grandes que tol .

La valeur par défaut de tol est la même que pour la fonction rank .

Examples

    X=rand(4,2)*rand(2,4)
    svd(X)
    sqrt(spec(X*X'))

See Also

rank , qr , colcomp , rowcomp , sva , spec ,

Used Function

la décomposition svd est basée sur les routines DGESVD pour les matrices réelles et ZGESVD pour le cas complexe.


sylv

Scilab Function
Last update : 12/01/2004

sylv - Sylvester equation.

Calling Sequence

sylv(A,B,C,flag)

Parameters

  • A,B,C : three real matrices of appropriate dimensions.
  • flag character string ( 'c' or 'd' )

Description

X = sylv(A,B,C,'c') computes X , solution of the "continuous time" Sylvester equation

A*X+X*B=C

X=sylv(A,B,C,'d') computes X , solution of the "discrete time" Sylvester equation

A*X*B-X=C

Examples

A=rand(4,4);C=rand(4,3);B=rand(3,3);
X = sylv(A,B,C,'c');
norm(A*X+X*B-C)
X=sylv(A,B,C,'d')
norm(A*X*B-X-C)

See Also

lyap ,


trace

Scilab Function
Last update : 16/06/2004

trace - trace d'une matrice

Calling Sequence

trace(X)

Parameters

  • X : matrice carrée, réelle, complexe, polynomiale ou rationnelle.

Description

trace(X) calcule la trace de X .

Identique à sum(diag(X)) .

Examples

A=rand(3,3);
trace(A)-sum(spec(A))

See Also

det ,


Calculs sur les polynômes
bezout - équation de Bezout pour les polynômes
clean - nettoie une matrice (arrondi à zéro des termes très petits)
cmndred - dénominateur commun
coeff - coefficients d'une matrice de polynômes
coffg - inverse d'une matrice de polynômes
colcompr - compression des colonnes d'une matrice de polynômes
degree - degrés d'une matrice de polynômes
denom - dénominateur
derivat - dérivée d'une matrice de polynômes
determ - déterminant d'une matrice de polynômes
detr - déterminant d'un polynôme
diophant - équation diophantienne de Bezout
factors - factorisation réelle de polynômes
gcd - calcul de PGCD
hermit - forme d'Hermite
horner - évaluation d'un polynôme ou d'une fraction rationnelle
hrmt - PGDC de plusieurs polynômes
htrianr - triangularisation d'une matrice de polynômes
invr - inversion d'une matrice rationnelle (ou polynomiale)
lcm - Plus petit commun multiple (PPCM) de polynômes ou d'entiers
lcmdiag - factorisation diagonale par le plus petit commun multiple
ldiv - division longue d'une matrice de polynômes
numer - numérateurs d'une matrice rationnelle
pdiv - division de polynômes
pol2des - conversion matrice de polynômes vers forme descripteur
pol2str - conversion polynôme vers chaîne de caractères
polfact - facteurs minimaux
residu - résidu
roots - racines d'un polynôme
routh_t - Routh's table
rowcompr - compression de lignes d'une matrice de polynômes
sfact - factorisation spectrale en temps discret
simp - simplification rationnelle
simp_mode - mode de simplification des fractions rationnelles
sylm - matrice de Sylvester
systmat - system matrix


bezout

Scilab Function
Last update : 06/07/2004

bezout - équation de Bezout pour les polynômes

Calling Sequence

[pgcd,U]=bezout(p1,p2)

Parameters

  • p1, p2 : deux polynômes réels ou deux entiers (type égal à 8)

Description

[thegcd,U]=bezout(p1,p2) calcule le PGCD pgcd de p1 et p2 et de plus une matrice unimodulaire (2x2) U telle que :

[p1,p2]*U = [pgcd,0]

Le PPCM de p1 et p2 est donné par

p1*U(1,2) (ou -p2*U(2,2) )

Examples

// cas des polynômes
x=poly(0,'x');
p1=(x+1)*(x-3)^5;p2=(x-2)*(x-3)^3;
[pgcd,U]=bezout(p1,p2)
det(U)
clean([p1,p2]*U)
ppcm=p1*U(1,2)
lcm([p1,p2])
// cas des entiers
i1=int32(2*3^5); i2=int32(2^3*3^2);
[thegcd,U]=bezout(i1,i2)
V=int32([2^2*3^5, 2^3*3^2,2^2*3^4*5]);
[thegcd,U]=gcd(V)
V*U
lcm(V)

See Also

poly , roots , simp , clean , lcm ,


clean

Scilab Function
Last update : 16/06/2004

clean - nettoie une matrice (arrondi à zéro des termes très petits)

Calling Sequence

[B]=clean(A [,epsa [,epsr]])

Parameters

  • A : une matrice (scalaire, polynômes, creuse, ...)
  • epsa,epsr : nombres réels (valeurs par défaut resp. 1.d-10 et 1.d-10)

Description

Cette fonction élimine (force à zéro) les coefficients de valeur absolue < epsa et de valeur relative < epsr (relative par rapport à la norme 1 des coefficients) dans un polynôme (éventuellement matrice de polynôme ou rationnelle).

Les valeurs par défaut sont epsa=1.d-10 et epsr=1.d-10 .

Pour une matrice constante (non polynomiale) clean(A,epsa) force à zéro les termes de A plus petits que epsa .

Examples

x=poly(0,'x');
w=[x,1,2+x;3+x,2-x,x^2;1,2,3+x]/3;
w*inv(w)
clean(w*inv(w))


cmndred

Scilab Function
Last update : 16/06/2004

cmndred - dénominateur commun

Calling Sequence

[n,d]=cmndred(num,den)

Parameters

  • num, den : 2 matrices de polynômes de mêmes dimensions

Description

[n,d]=cmndred(num,den) calcule une matrice de polynômes n et un dénominateur commun d tels que :

n/d=num./den

La matrice de polynômes définie par num./den est n/d .

See Also

simp , clean ,


coeff

Scilab Function
Last update : 16/06/2004

coeff - coefficients d'une matrice de polynômes

Calling Sequence

[C]=coeff(Mp [,v])

Parameters

  • Mp : matrice de polynômes
  • v : vecteur (ligne ou colonne) d'entiers des degrés choisis
  • C : grosse matrice de coefficients

Description

C=coeff(Mp) renvoie dans une grosse matrice C les coefficients de la matrice de polynômes Mp . C est partitionnée comme C=[C0,C1,...,Ck] où les Ci sont arrangés dans l'ordre décroissant . k = maxi(degree(Mp))

C=coeff(Mp,v) renvoie la matrice des coefficients avec les degrés dans v .

See Also

poly , degree , inv_coeff ,


coffg

Scilab Function
Last update : 16/06/2004

coffg - inverse d'une matrice de polynômes

Calling Sequence

[Ns,d]=coffg(Fs)

Parameters

  • Fs : matrice carrée de polynômes

Description

coffg calcule Fs^-1 par la méthode des cofacteurs, où Fs est une matrice de polynômes.

inverse de Fs = Ns/d

d = dénominateur commun; Ns = numérateur (une matrice de polynômes).

(pour les grandes matrices, s'armer de patience... les résultats sont en général fiables)

Examples

s=poly(0,'s')
a=[ s, s^2+1; s  s^2-1];
[a1,d]=coffg(a);
(a1/d)-inv(a)

See Also

determ , detr , invr , penlaur , glever ,

Author

F. D.; ;


colcompr

Scilab Function
Last update : 16/06/2004

colcompr - compression des colonnes d'une matrice de polynômes

Calling Sequence

[Y,rk,ac]=colcompr(A);

Parameters

  • A : matrice de polynômes
  • Y : matrice carrée de polynômes (base unimodulaire à droite)
  • rk : rang normal de A
  • Ac : Ac=A*Y , matrice de polynômes

Description

Compression de colonnes de la matrice de polynômes A (compression à gauche)

Examples

s=poly(0,'s');
p=[s;s*(s+1)^2;2*s^2+s^3];
[Y,rk,ac]=colcompr(p*p');
p*p'*Y

See Also

rowcompr ,


degree

Scilab Function
Last update : 16/06/2004

degree - degrés d'une matrice de polynômes

Calling Sequence

[D]=degree(M)

Parameters

  • M : matrice de polynômes
  • D : matrice d'entiers

Description

renvoie la matrice des plus hauts degrés de M .

See Also

poly , coeff , clean ,


denom

Scilab Function
Last update : 16/06/2004

denom - dénominateur

Calling Sequence

den=denom(r)

Parameters

  • r : matrice de fractions rationnelles
  • den : matrice de polynômes

Description

den=denom(r) renvoie le dénominateur d'une matrice rationnelle R ( R peut aussi être une matrice constante ou une matrice de polynômes).

Puisque dans Scilab les matrices rationnelles sont représentées comme r=list(['r','num','den','dt'],num,den,[]) , denom(r ) est équivalent à r(3) , r('den') ou r.den) .

See Also

numer ,


derivat

Scilab Function
Last update : 16/06/2004

derivat - dérivée d'une matrice de polynômes

Calling Sequence

pd=derivat(p)

Parameters

  • p : polynôme, matrice de polynômes ou de fractions rationnelles

Description

Calcule la dérivée des polynômes ou fractions rationnelles contenus dans les termes de la matrice p.

Examples

s=poly(0,'s');
derivat(1/s)  // -1/s^2;


determ

Scilab Function
Last update : 09/06/2006

determ - déterminant d'une matrice de polynômes

Calling Sequence

res=determ(W [,k])

Parameters

  • W : matrice réelle de polynômes
  • k : entier (borne supérieure pour le degré du déterminant de W)

Description

res=determ(W [,k]) renvoie le déterminant d'une matrice réelle de polynômes (calculs fait par FFT si la taille de W est supérieure à 2*2).

k est un entier plus grand que le degré effectif du déterminant. de W .

La valeur par défaut de k est la plus petite puissance de 2 plus grande que n*maxi(degree(W)) .

Méthode (pour les matrices dont la taille est supérieure à 2*2) : évaluation du déterminant de W aux fréquences de Fourier et FFT inverse appliquée aux coefficients du déterminant.

Examples

s=poly(0,'s');
w=s*rand(10,10);
determ(w)
det(coeff(w,1))*s^10

See Also

det , detr , coffg ,

Author

F. Delebecque


detr

Scilab Function
Last update : 16/06/2004

detr - déterminant d'un polynôme

Calling Sequence

d=detr(h)

Parameters

  • h : matrice carrée de polynômes ou de fractions rationnelles

Description

d=detr(h) renvoie le déterminant d de la matrice h . Basé sur l'algorithme de Leverrier.

See Also

det , determ ,


diophant

Scilab Function
Last update : 16/06/2004

diophant - équation diophantienne de Bezout

Calling Sequence

[x,err]=diophant(p1p2,b)

Parameters

  • p1p2 : vecteur de polynômes p1p2 = [p1 p2]
  • b : polynôme
  • x : vecteur de polynômes [x1;x2]

Description

diophant résout l'équation de Bezout :

p1*x1+p2*x2=b où p1p2 est un vecteur de polynômes. Si l'équation n'est pas soluble

sinon err=0

Examples

s=poly(0,'s');p1=(s+3)^2;p2=(1+s);
x1=s;x2=(2+s);
[x,err]=diophant([p1,p2],p1*x1+p2*x2);
p1*x1+p2*x2-p1*x(1)-p2*x(2)


factors

Scilab Function
Last update : 16/06/2004

factors - factorisation réelle de polynômes

Calling Sequence

[lnum,g]=factors(pol [,'flag'])
[lnum,lden,g]=factors(rat [,'flag'])
rat=factors(rat,'flag')

Parameters

  • pol : polynôme réel
  • rat : fraction rationnelle ( rat=pol1/pol2 )
  • lnum : liste de polynômes (de degrés 1 ou 2)
  • lden : liste de polynômes (de degrés 1 ou 2)
  • g : nombre réel
  • flag : chaîne de caractères, 'c' ou 'd'

Description

renvoie les facteurs du polynôme pol dans la liste lnum et le "gain" g.

On a pol = g multiplié par le produit des termes de la liste lnum (si flag n'est pas donné). Si flag='c' , on a |pol(i omega)| = |g*prod(lnum_j(i omega)| . Si flag='d' alors on a |pol(exp(i omega))| = |g*prod(lnum_i(exp(i omega))| . Si l'argument de factors est une fraction rationnelle 1x1 rat=pol1/pol2 , les facteurs du numérateur pol1 et le dénominateur pol2 sont renvoyés dans les listes lnum et lden , respectivement.

Le "gain" est renvoyé dans g , c'est à dire rat = g multiplié par (produit des termes dans lnum) / (produit des termes dans lden).

Si flag vaut 'c' (resp. 'd' ), les racines de pol sont réfléchies par rapport à l'axe imaginaire (resp. le cercle unité), i.e. les facteurs dans lnum sont des polynômes stables. Idem si factors est appelé avec des arguments rationnels : les termes dans lnum et lden sont des polynômes stables si flag est donné. R2=factors(R1,'c') ou R2=factors(R1,'d') avec R1 une fraction rationnelle ou une liste syslin SISO : la sortie R2 est rationnelle avec un numérateur et un dénominateur stables et de même module que R1 sur l'axe imaginaire ( 'c' ) ou le cercle unité ( 'd' ).

Examples

n=poly([0.2,2,5],'z');
d=poly([0.1,0.3,7],'z');
R=syslin('d',n,d);
R1=factors(R,'d')
roots(R1('num'))
roots(R1('den'))
w=exp(2*%i*%pi*[0:0.1:1]);
norm(abs(horner(R1,w))-abs(horner(R,w)))

See Also

simp ,


gcd

Scilab Function
Last update : 06/07/2004

gcd - calcul de PGCD

Calling Sequence

[pgcd,U]=gcd(p)

Parameters

  • p : vecteur ligne de polynômes p=[p1,..,pn] ou d'entiers (type égal à 8)

Description

Calcule le PGCD des termes de p et une matrice unimodulaire (avec le polynôme inverse) U , de degré minimal tels que

p*U=[0 ... 0 pgcd]

Examples

//cas des polynômes
s=poly(0,'s');
p=[s,s*(s+1)^2,2*s^2+s^3];
[pgcd,u]=gcd(p);
p*u
//cas des entiers
V=int32([2^2*3^5, 2^3*3^2,2^2*3^4*5]);
[thegcd,U]=gcd(V)
V*U

See Also

bezout , lcm , hermit ,


hermit

Scilab Function
Last update : 16/06/2004

hermit - forme d'Hermite

Calling Sequence

[Ar,U]=hermit(A)

Parameters

  • A : matrice de polynômes
  • Ar : matrice triangulaire de polynômes
  • U : matrice unimodulaire de polynômes

Description

Forme d'Hermite : U est une matrice unimodulaire telle que A*U est sous la forme d'Hermite triangulaire :

La variable de sortie est Ar=A*U .

Attention : version expérimentale

Examples

s=poly(0,'s');
p=[s, s*(s+1)^2, 2*s^2+s^3];
[Ar,U]=hermit(p'*p);
clean(p'*p*U), det(U)

See Also

hrmt , htrianr ,


horner

Scilab Function
Last update : 16/06/2004

horner - évaluation d'un polynôme ou d'une fraction rationnelle

Calling Sequence

horner(P,x)

Parameters

  • P : polynôme ou matrice de polynômes
  • x : nombre réel, polynôme ou fraction rationnelle

Description

évalue le polynôme ou la fraction rationnelle (ou matrice de fractions rationnelles) P = P(s) quand la variable s du polynôme est remplacée par x :

horner(P,x) = P(x)

Exemple (transformation bilinéaire) : supposons que P = P(s) est une matrice de polynômes, alors la matrice de polynômes P((1+s)/(1-s)) est obtenue par horner(P,(1+s)/(1-s)) .

Pour évaluer une matrice de polynômes à des fréquences données utiliser plutôt la primitive freq .

Examples

s=poly(0,'s');M=[s,1/s];
horner(M,1)
horner(M,%i)
horner(M,1/s)

See Also

freq , repfreq , evstr ,


hrmt

Scilab Function
Last update : 16/06/2004

hrmt - PGDC de plusieurs polynômes

Calling Sequence

[pg,U]=hrmt(v)

Parameters

  • v : vecteur ligne de polynômes
  • pg : polynôme
  • U : matrice unimodulaire de polynômes

Description

[pg,U]=hrmt(v) renvoie une matrice unimodulaire U et pg = PGDC de la ligne de polynômes v tels que v*U = [pg,0] .

Examples

x=poly(0,'x');
v=[x*(x+1),x^2*(x+1),(x-2)*(x+1),(3*x^2+2)*(x+1)];
[pg,U]=hrmt(v);U=clean(U)
det(U)

See Also

gcd , htrianr ,

Author

S. Steer INRIA


htrianr

Scilab Function
Last update : 16/06/2004

htrianr - triangularisation d'une matrice de polynômes

Calling Sequence

[Ar,U,rk]=htrianr(A)

Parameters

  • A : matrice de polynômes
  • Ar : matrice de polynômes
  • U : matrice unimodulaire de polynômes
  • rk : entier, le rang normal de A

Description

triangularisation de la matrice de polynômes A .

A de taille [m,n] , m <= n .

Ar=A*U

Examples

x=poly(0,'x');
M=[x;x^2;2+x^3]*[1,x-2,x^4];
[Mu,U,rk]=htrianr(M)
det(U)
M*U(:,1:2)

See Also

hrmt , colcompr ,


invr

Scilab Function
Last update : 16/06/2004

invr - inversion d'une matrice rationnelle (ou polynomiale)

Calling Sequence

F = invr(H)

Parameters

  • H : polynôme ou matrice de polynômes
  • F : polynôme ou matrice de polynômes

Description

Si H est une matrice de polynômes ou de fractions rationnelles, invr calcule H^(-1) avec l'algorithme de Leverrier (voir code de la fonction).

Examples

s=poly(0,'s')
H=[s,s*s+2;1-s,1+s]; invr(H)
[Num,den]=coffg(H);Num/den
H=[1/s,(s+1);1/(s+2),(s+3)/s];invr(H)

See Also

glever , coffg , inv ,


lcmdiag

Scilab Function
Last update : 16/06/2004

lcmdiag - factorisation diagonale par le plus petit commun multiple

Calling Sequence

[N,D]=lcmdiag(H)
[N,D]=lcmdiag(H,flag)

Parameters

  • H : matrice de polynômes
  • N : matrice de polynômes
  • D : matrice diagonale de polynômes
  • flag : chaîne de caractères : 'row' ou 'col' (par défaut)

Description

[kN,D]=lcmdiag(H,'row') calcule une factorisation D*H=N , i.e. H=D^(-1)*N où D est une matrice diagonale avec D(k,k)=ppcm de la k-ième ligne de H.den .

[N,D]=lcmdiag(H) ou [N,D]=lcmdiag(H,'col) renvoie H=N*D^(-1) avec D diagonale et D(k,k)=ppcm de ma k-ième colonne de H.den .

Examples

s=poly(0,'s');
H=[1/s,(s+2)/s/(s+1)^2;1/(s^2*(s+2)),2/(s+2)];
[N,D]=lcmdiag(H);
N/D-H

See Also

lcm , gcd , bezout ,


lcm

Scilab Function
Last update : 06/07/2004

lcm - Plus petit commun multiple (PPCM) de polynômes ou d'entiers

Calling Sequence

[pp,fact]=lcm(p)

Parameters

  • p : vecteur de polynômes ou d'entiers (type égal à 8)
  • fact : vecteur de polynômes ou d'entiers
  • pp : polynôme ou un entier

Description

pp=lcm(p) calcule le PPCM pp du vecteur p au sens des polynômes ou des entiers.

[pp,fact]=lcm(p) calcule de plus le vecteur fact tel que :

p.*fact=pp*ones(p)

Examples

//cas des polynomes
s=poly(0,'s');
p=[s,s*(s+1)^2,s^2*(s+2)];
[pp,fact]=lcm(p);
p.*fact, pp
//cas des entiers
V=int32([2^2*3^5, 2^3*3^2,2^2*3^4*5]);
lcm(V)

See Also

gcd , bezout ,


ldiv

Scilab Function
Last update : 16/06/2004

ldiv - division longue d'une matrice de polynômes

Calling Sequence

[x]=ldiv(n,d,k)

Parameters

  • n,d : deux matrices réelles de polynômes
  • k : entier

Description

x=ldiv(n,d,k) donne les k premiers coefficients de la division longue de n par d i.e. le développement de Taylor de la matrice rationnelle [nij(z)/dij(z)] à l'infini.

Les coefficients du développement de nij/dij sont stockés dans x((i-1)*n+k,j) k=1:n

Examples

wss=ssrand(1,1,3);[a,b,c,d]=abcd(wss);
wtf=ss2tf(wss);
x1=ldiv(numer(wtf),denom(wtf),5)
x2=[c*b;c*a*b;c*a^2*b;c*a^3*b;c*a^4*b]
wssbis=markp2ss(x1',5,1,1);
wtfbis=clean(ss2tf(wssbis))
x3=ldiv(numer(wtfbis),denom(wtfbis),5)

See Also

arl2 , markp2ss , pdiv ,


numer

Scilab Function
Last update : 16/06/2004

numer - numérateurs d'une matrice rationnelle

Calling Sequence

num=numer(R)

Parameters

  • R : matrice de fractions rationnelles
  • num : matrice de polynômes

Description

num=numer(R) renvoie le numérateur num d'une matrice rationnelle R ( R peut aussi être une matrice constante ou une matrice de polynômes). numer(R) est équivalent à R(2) , R('num') ou R.num

See Also

denom ,


pdiv

Scilab Function
Last update : 16/06/2004

pdiv - division de polynômes

Calling Sequence

[R,Q]=pdiv(P1,P2)
[Q]=pdiv(P1,P2)

Parameters

  • P1 : matrice de polynômes
  • P2 : polynôme ou matrice de polynômes
  • R,Q : deux matrices de polynômes

Description

Division euclidienne élément par élément de la matrice de polynômes P1 par le polynôme P2 ou par la matrice de polynômes P2 . Rij est la matrice des restes, Qij est la matrice des quotients et P1ij = Qij*P2 + Qij ou P1ij = Qij*P2ij + Qij .

Examples

x=poly(0,'x');
p1=(1+x^2)*(1-x);p2=1-x;
[r,q]=pdiv(p1,p2)
p2*q-p1
p2=1+x;
[r,q]=pdiv(p1,p2)
p2*q+r-p1

See Also

ldiv , gcd ,


pol2des

Scilab Function
Last update : 16/06/2004

pol2des - conversion matrice de polynômes vers forme descripteur

Calling Sequence

[N,B,C]=pol2des(Ds)

Parameters

  • Ds : matrice de polynômes
  • N, B, C : 3 matrices réelles

Description

Etant donnée la matrice de polynômes Ds=D_0 +D_1 s +D_2 s^2 +... +D_k s^k , pol2des renvoie 3 matrices N, B, C , avec N nilpotente telles que :

Ds = C (s*N-eye())^-1 B

Examples

s=poly(0,'s');
G=[1,s;1+s^2,3*s^3];[N,B,C]=pol2des(G);
G1=clean(C*inv(s*N-eye())*B),G2=numer(G1)

See Also

ss2des , tf2des ,

Author

F.D.;


pol2str

Scilab Function
Last update : 16/06/2004

pol2str - conversion polynôme vers chaîne de caractères

Calling Sequence

[str]=pol2str(p)

Parameters

  • p : polynôme réel
  • str : chaîne de caractères

Description

convertit le polynôme p en une chaîne de caractères (fonction utilitaire).

See Also

string , pol2tex ,


polfact

Scilab Function
Last update : 17/06/2004

polfact - facteurs minimaux

Calling Sequence

[f]=polfact(p)

Parameters

  • p : polynôme
  • f : vecteur [f0 f1 ... fn] tel que p=prod(f)
    • f0 : constante
    • fi : polynôme

Description

f=polfact(p) renvoie les facteurs minimaux de p i.e. f=[f0 f1 ... fn] tel que p=prod(f)

See Also

lcm , cmndred , factors ,

Author

S. Steer INRIA


residu

Scilab Function
Last update : 16/06/2004

residu - résidu

Calling Sequence

[V]=residu(P,Q1,Q2)

Parameters

  • P, Q1, Q2 : polynômes ou matrice de polynômes à coefficients réels ou complexes.

Description

V=residu(P,Q1,Q2) renvoie la matrice V telle que V(i,j) est la somme des résidus de la fraction rationnelle P(i,j)/(Q1(i,j)*Q2(i,j)) calculés aux zéros de Q1(i,j) .

Q1(i,j) et Q2(i,j) ne doivent pas avoir de racines communes.

Examples

s=poly(0,'s');
H=[s/(s+1)^2,1/(s+2)];N=numer(H);D=denom(H);
w=residu(N.*horner(N,-s),D,horner(D,-s));  //N(s) N(-s) / D(s) D(-s)
sqrt(sum(w))  // La norme H2
h2norm(tf2ss(H))
//
p=(s-1)*(s+1)*(s+2)*(s+10);a=(s-5)*(s-1)*(s*s)*((s+1/2)**2);
b=(s-3)*(s+2/5)*(s+3);
residu(p,a,b)+531863/4410    // Exact
z=poly(0,'z');a=z^3+0.7*z^2+0.5*z-0.3;b=z^3+0.3*z^2+0.2*z+0.1;
atild=gtild(a,'d');btild=gtild(b,'d');
residu(b*btild,z*a,atild)-2.9488038   // Exact
a=a+0*%i;b=b+0*%i;
real(residu(b*btild,z*a,atild)-2.9488038) // Cas complexe

See Also

pfss , bdiag , roots , poly , gtild ,

Author

F Delebecque INRIA


roots

Scilab Function
Last update : 14/12/2005

roots - racines d'un polynôme

Calling Sequence

[x]=roots(p)

Parameters

  • p : polynôme à coefficients réels ou complexes ou vecteur des coefficients du polynŽôme ordonnés par puissance décroissante (compatibilité avec Matlab).

Description

x=roots(p) renvoie dans le vecteur complexe x les racines du polynôme p . Pour les polynŽômes à coéfficients réels et de degré <=100, l'algorithme rapide RPOLY est utilisé. Dans les autres cas les racines sont calculées comme valeurs propres de la matrice compagnion du polynŽôme. Pour forcer ce dernier algorithme dans tous les cas utilisez x=roots(p,'e') .

Examples

p=poly([0,10,1+%i,1-%i],'x');
roots(p)
A=rand(3,3);roots(poly(A,'x'))    // comparaison via le polynôme caractéristique
spec(A)

See Also

poly , spec , companion ,

Authors

Serge Steer (INRIA)

Bibliography

La routine RPOLY est decrite dans ACM TOMS 1 (1975) 178-189

Used Function

Le code source de rpoly.f peut être trouvé dans le repertoire routines/control de la distribution source de Scilab. Le calcul des valeurs propores est effectué en utilisant les routines DGEEV et ZGEEV de LAPACK.


routh_t

Scilab Function
Last update : 12/01/2004

routh_t - Routh's table

Calling Sequence

r=routh_t(h [,k]).

Parameters

  • h : square rational matrix

Description

r=routh_t(h,k) computes Routh's table of denominator of the system described by transfer matrix SISO h with the feedback by the gain k .

If k=poly(0,'k') we will have a polynomial matrix with dummy variable k , formal expression of the Routh table.


rowcompr

Scilab Function
Last update : 16/06/2004

rowcompr - compression de lignes d'une matrice de polynômes

Calling Sequence

[X,rk,Ac]=rowcompr(A)

Parameters

  • A : matrice de polynômes
  • Y : matrice carrée de polynômes (base unimodulaire à gauche)
  • rk : rang normal de A
  • Ac : Ac=X*A , matrice de polynômes

Description

Compression de lignes de la matrice de polynômes A .

X est une base de polynômes unimodulaire à gauche qui compresse les lignes de A . rk est le rang normal de A.

Attention : élimination des termes "petits" (à utiliser avec précaution).

See Also

colcompr ,


sfact

Scilab Function
Last update : 16/06/2004

sfact - factorisation spectrale en temps discret

Calling Sequence

F=sfact(P)

Parameters

  • P : matrice de polynômes réels

Description

Trouve F , un facteur spectral de P . P est une matrice de polynômes telle que chaque racine de P a une image miroir par rapport au cercle unité. Le problème est singulier si une racine se trouve sur le cercle unité.

sfact(P) renvoie une matrice de polynômes F(z) antistable et telle que

P = F(z)* F(1/z) *z^n

Pour les polynômes scalaires un algorithme spécifique est utilisé. Les algorithmes sont tirés du livre de Kucera.

Examples

// polynôme simple
z=poly(0,'z');
p=(z-1/2)*(2-z)
w=sfact(p);
w*numer(horner(w,1/z))
// exemple matriciel
F1=[z-1/2,z+1/2,z^2+2;1,z,-z;z^3+2*z,z,1/2-z];
P=F1*gtild(F1,'d');  // P est symétrique
F=sfact(P)
roots(det(P))
roots(det(gtild(F,'d')))  // Les racines stables
roots(det(F))             // Les racines antistables
clean(P-F*gtild(F,'d'))
// Utilisation en temps continu
s=poly(0,'s');
p=-3*(s+(1+%i))*(s+(1-%i))*(s+0.5)*(s-0.5)*(s-(1+%i))*(s-(1-%i));p=real(p);
// p(s) = polynôme dans s^2, cherche un f stable tel que p=f(s)*f(-s)
w=horner(p,(1-s)/(1+s));  // transformation bilinéaire w=p((1-s)/(1+s))
wn=numer(w);              // prend le numérateur
fn=sfact(wn);f=numer(horner(fn,(1-s)/(s+1))); // Factorisation et transformation inverse
f=f/sqrt(horner(f*gtild(f,'c'),0));f=f*sqrt(horner(p,0));      // normalisation
roots(f)    // f est stable
clean(f*gtild(f,'c')-p)    //f(s)*f(-s) est égal à p(s)

See Also

gtild , fspecg ,


simp_mode

Scilab Function
Last update : 16/06/2004

simp_mode - mode de simplification des fractions rationnelles

Calling Sequence

mod=simp_mode()
simp_mode(mod)

Parameters

  • mod : un booléen

Description

Une simplification rationnelle est effectuée après chaque opération sur les fractions rationnelles. Il est possible de changer cela avec la fonction simp_mode .

simp_mod(%t) passe en mode de simplification systématique.

simp_mod(%f) empêche les simplifications.

mod=simp_mod() renvoie dans mod le mode de simplification courant.

Examples

s=poly(0,'s');
mod=simp_mode()
simp_mode(%f);hns=s/s
simp_mode(%t);hns=s/s
simp_mode(mod);

See Also

simp ,


simp

Scilab Function
Last update : 16/06/2004

simp - simplification rationnelle

Calling Sequence

[N1,D1]=simp(N,D)
H1=simp(H)

Parameters

  • N,D : polynômes réels ou matrices de polynômes réels
  • H : matrice de fractions rationnelles (i.e matrice avec des termes n/d , n et d polynômes réels)

Description

[n1,d1]=simp(n,d) calcule deux polynômes n1 et d1 tels que n1/d1 = n/d .

Si N et D sont des matrices de polynômes le calcul est fait élément par élément.

H1=simp(H) est aussi valide (chaque terme de H est simplifié dans H1 ).

Attention :

- pas de seuil i.e. simp ne peut pas forcer une simplification.

- Pour les systèmes dynamiques linéaires avec un intégrateur la simplification change le gain statique. ( H(0) pour les systèmes continus ou H(1) pour les systèmes discrets)

- Pour les données complexes, simp renvoie ses entrées.

- Une simplification est effectuée après la plupart des opérations rationnelles. Il est possible de la supprimer en utilisant la fonction simp_mode .

Examples

s=poly(0,'s');
[n,d]=simp((s+1)*(s+2),(s+1)*(s-2))

simp_mode(%F);hns=s/s
simp_mode(%T);hns=s/s

See Also

roots , trfmod , poly , clean , simp_mode ,


sylm

Scilab Function
Last update : 16/06/2004

sylm - matrice de Sylvester

Calling Sequence

[S]=sylm(a,b)

Parameters

  • a,b : deux polynômes
  • S : matrice

Description

sylm(a,b) renvoie la matrice de Sylvester associée aux polynômes a et b , i.e. la matrice S telle que :

coeff( a*x + b*y )' = S * [coeff(x)';coeff(y)'] .

La dimension de S est égale à degree(a)+degree(b) .

Si a et b sont premiers entre eux alors

rank(sylm(a,b))=degree(a)+degree(b)) et les instructions

  u = sylm(a,b) \ eye(na+nb,1)
  x = poly(u(1:nb),'z','coeff')
  y = poly(u(nb+1:na+nb),'z','coeff')

calculent les facteurs de Bezout x ainsi que y de degré minimum tels que a*x+b*y = 1


systmat

Scilab Function
Last update : 12/01/2004

systmat - system matrix

Calling Sequence

[Sm]=systmat(Sl);

Parameters

  • Sl : linear system ( syslin list) or descriptor system
  • Sm : matrix pencil

Description

System matrix of the linear system Sl ( syslin list) in state-space form (utility function).

 Sm = [-sI + A   B;
      [    C     D]

For a descriptor system ( Sl=list('des',A,B,C,D,E) ), systmat returns:

 Sm = [-sE + A   B;
      [    C     D]

See Also

ss2des , sm2des , sm2ss ,


Contrôle et théorie des systèmes
abcd - state-space matrices
abinv - AB invariant subspace
arhnk - Hankel norm approximant
arl2 - SISO model realization by L2 transfer approximation
balreal - balanced realization
bilin - general bilinear transform
cainv - Dual of abinv
calfrq - frequency response discretization
canon - canonical controllable form
cls2dls - bilinear transform
colregul - removing poles and zeros at infinity
cont_frm - transfer to controllable state-space
cont_mat - controllability matrix
contr - controllability, controllable subspace, staircase
contrss - controllable part
csim - simulation (time response) of linear system
ctr_gram - controllability gramian
dbphi - frequency response to phase and magnitude representation
ddp - disturbance decoupling
des2tf - descriptor to transfer function conversion
dscr - discretization of linear system
dsimul - state space discrete time simulation
dt_ility - detectability test
equil - balancing of pair of symmetric matrices
equil1 - balancing (nonnegative) pair of matrices
feedback - feedback operation
flts - time response (discrete time, sampled system)
frep2tf - transfer function realization from frequency response
freq - frequency response
freson - peak frequencies
g_margin - gain margin
gfrancis - Francis equations for tracking
imrep2ss - state-space realization of an impulse response
invsyslin - system inversion
kpure - continuous SISO system limit feedback gain
krac2 - continuous SISO system limit feedback gain
lin - linearization
linmeq - Sylvester and Lyapunov equations solver
lqe - linear quadratic estimator (Kalman Filter)
lqg - LQG compensator
lqg2stan - LQG to standard problem
lqr - LQ compensator (full state)
ltitr - discrete time response (state space)
markp2ss - Markov parameters to state-space
minreal - minimal balanced realization
minss - minimal realization
obs_gram - observability gramian
obscont - observer based controller
observer - observer design
obsv_mat - observability matrix
obsvss - observable part
p_margin - phase margin
pfss - partial fraction decomposition
phasemag - phase and magnitude computation
ppol - pole placement
projsl - linear system projection
repfreq - frequency response
ricc - Riccati equation
rowregul - removing poles and zeros at infinity
rtitr - discrete time response (transfer matrix)
sm2des - system matrix to descriptor
sm2ss - system matrix to state-space
specfact - spectral factor
ss2des - (polynomial) state-space to descriptor form
ss2ss - state-space to state-space conversion, feedback, injection
ss2tf - conversion from state-space to transfer function
st_ility - stabilizability test
stabil - stabilization
svplot - singular-value sigma-plot
sysfact - system factorization
syssize - size of state-space system
tf2ss - transfer to state-space
time_id - SISO least square identification
trzeros - transmission zeros and normal rank
ui_observer - unknown input observer
unobs - unobservable subspace
zeropen - zero pencil


abcd

Scilab Function
Last update : 12/01/2004

abcd - state-space matrices

Calling Sequence

[A,B,C,D]=abcd(sl)

Parameters

  • sl : linear system ( syslin list) in state-space or transfer form
  • A,B,C,D : real matrices of appropriate dimensions

Description

returns the A,B,C,D matrices from a linear system Sl .

Utility function. For transfer matrices Sl is converted into state-space form by tf2ss .

The matrices A,B,C,D are the elements 2 to 5 of the syslin list Sl , i.e. [A,B,C,D] = Sl(2:5) .

Examples

A=diag([1,2,3]);B=[1;1;1];C=[2,2,2];
sys=syslin('c',A,B,C);
sys("A")
sys("C")
[A1,B1,C1,D1]=abcd(sys);
A1
systf=ss2tf(sys);
[a,b,c,d]=abcd(systf)
spec(a)
c*b-C*B
c*a*b-C*A*B

See Also

syslin , ssrand ,


abinv

Scilab Function
Last update : 12/01/2004

abinv - AB invariant subspace

Calling Sequence

[X,dims,F,U,k,Z]=abinv(Sys,alfa,beta,flag)

Parameters

  • Sys : syslin list containing the matrices [A,B,C,D] .
  • alfa : (optional) real number or vector (possibly complex, location of closed loop poles)
  • beta : (optional) real number or vector (possibly complex, location of closed loop poles)
  • flag : (optional) character string 'ge' (default) or 'st' or 'pp'
  • X : orthogonal matrix of size nx (dim of state space).
  • dims : integer row vector dims=[dimR,dimVg,dimV,noc,nos] with dimR<=dimVg<=dimV<=noc<=nos . If flag='st' , (resp. 'pp' ), dims has 4 (resp. 3) components.
  • F : real matrix (state feedback)
  • k : integer (normal rank of Sys )
  • Z : non-singular linear system ( syslin list)

Description

Output nulling subspace (maximal unobservable subspace) for Sys = linear system defined by a syslin list containing the matrices [A,B,C,D] of Sys . The vector dims=[dimR,dimVg,dimV,noc,nos] gives the dimensions of subspaces defined as columns of X according to partition given below. The dimV first columns of X i.e V=X(:,1:dimV) , span the AB-invariant subspace of Sys i.e the unobservable subspace of (A+B*F,C+D*F) . ( dimV=nx iff C^(-1)(D)=X).

The dimR first columns of X i.e. R=X(:,1:dimR) spans the controllable part of Sys in V , (dimR<=dimV) . ( dimR=0 for a left invertible system). R is the maximal controllability subspace of Sys in kernel(C) .

The dimVg first columns of X spans Vg =maximal AB-stabilizable subspace of Sys . (dimR<=dimVg<=dimV) .

F is a decoupling feedback: for X=[V,X2] (X2=X(:,dimV+1:nx)) one has X2'*(A+B*F)*V=0 and (C+D*F)*V=0 .

The zeros od Sys are given by : X0=X(:,dimR+1:dimV); spec(X0'*(A+B*F)*X0) i.e. there are dimV-dimR closed-loop fixed modes.

If the optional parameter alfa is given as input, the dimR controllable modes of (A+BF) in V are set to alfa (or to [alfa(1), alfa(2), ...] . ( alfa can be a vector (real or complex pairs) or a (real) number). Default value alfa=-1 .

If the optional real parameter beta is given as input, the noc-dimV controllable modes of (A+BF) "outside" V are set to beta (or [beta(1),beta(2),...] ). Default value beta=-1 .

In the X,U bases, the matrices [X'*(A+B*F)*X,X'*B*U;(C+D*F)*X,D*U] are displayed as follows:

[A11,*,*,*,*,*]  [B11 * ]
[0,A22,*,*,*,*]  [0   * ]
[0,0,A33,*,*,*]  [0   * ]
[0,0,0,A44,*,*]  [0  B42]
[0,0,0,0,A55,*]  [0   0 ]
[0,0,0,0,0,A66]  [0   0 ]

[0,0,0,*,*,*]    [0  D2]

where the X-partitioning is defined by dims and the U-partitioning is defined by k .

A11 is (dimR x dimR) and has its eigenvalues set to alfa(i)'s . The pair (A11,B11) is controllable and B11 has nu-k columns. A22 is a stable (dimVg-dimR x dimVg-dimR) matrix. A33 is an unstable (dimV-dimVg x dimV-dimVg) matrix (see st_ility ).

A44 is (noc-dimV x noc-dimV) and has its eigenvalues set to beta(i)'s . The pair (A44,B42) is controllable. A55 is a stable (nos-noc x nos-noc) matrix. A66 is an unstable (nx-nos x nx-nos) matrix (see st_ility ).

Z is a column compression of Sys and k is the normal rank of Sys i.e Sys*Z is a column-compressed linear system. k is the column dimensions of B42,B52,B62 and D2 . [B42;B52;B62;D2] is full column rank and has rank k .

If flag='st' is given, a five blocks partition of the matrices is returned and dims has four components. If flag='pp' is given a four blocks partition is returned. In case flag='ge' one has dims=[dimR,dimVg,dimV,dimV+nc2,dimV+ns2] where nc2 (resp. ns2 ) is the dimension of the controllable (resp. stabilizable) pair (A44,B42) (resp. ( [A44,*;0,A55],[B42;0]) ). In case flag='st' one has dims=[dimR,dimVg,dimVg+nc,dimVg+ns] and in case flag='pp' one has dims=[dimR,dimR+nc,dimR+ns] . nc (resp. ns ) is here the dimension of the controllable (resp. stabilizable) subspace of the blocks 3 to 6 (resp. 2 to 6).

This function can be used for the (exact) disturbance decoupling problem.

DDPS:
   Find u=Fx+Rd=[F,R]*[x;d] which rejects Q*d and stabilizes the plant:

    xdot = Ax+Bu+Qd
       y = Cx+Du+Td

DDPS has a solution if Im(Q) is included in Vg + Im(B) and stabilizability
assumption is satisfied.
Let G=(X(:,dimVg+1:$))'= left annihilator of Vg i.e. G*Vg=0;
B2=G*B; Q2=G*Q; DDPS solvable iff [B2;D]*R + [Q2;T] =0 has a solution.
The pair F,R  is the solution  (with F=output of abinv).
Im(Q2) is in Im(B2) means row-compression of B2=>row-compression of Q2
Then C*[(sI-A-B*F)^(-1)+D]*(Q+B*R) =0   (<=>G*(Q+B*R)=0)

Examples

nu=3;ny=4;nx=7;
nrt=2;ngt=3;ng0=3;nvt=5;rk=2;
flag=list('on',nrt,ngt,ng0,nvt,rk);
Sys=ssrand(ny,nu,nx,flag);alfa=-1;beta=-2;
[X,dims,F,U,k,Z]=abinv(Sys,alfa,beta);
[A,B,C,D]=abcd(Sys);dimV=dims(3);dimR=dims(1);
V=X(:,1:dimV);X2=X(:,dimV+1:nx);
X2'*(A+B*F)*V
(C+D*F)*V
X0=X(:,dimR+1:dimV); spec(X0'*(A+B*F)*X0)
trzeros(Sys)
spec(A+B*F)   //nr=2 evals at -1 and noc-dimV=2 evals at -2.
clean(ss2tf(Sys*Z))
// 2nd Example
nx=6;ny=3;nu=2;
A=diag(1:6);A(2,2)=-7;A(5,5)=-9;B=[1,2;0,3;0,4;0,5;0,0;0,0];
C=[zeros(ny,ny),eye(ny,ny)];D=[0,1;0,2;0,3];
sl=syslin('c',A,B,C,D);//sl=ss2ss(sl,rand(6,6))*rand(2,2);
[A,B,C,D]=abcd(sl);  //The matrices of sl.
alfa=-1;beta=-2;
[X,dims,F,U,k,Z]=abinv(sl,alfa,beta);dimVg=dims(2);
clean(X'*(A+B*F)*X)
clean(X'*B*U)
clean((C+D*F)*X)
clean(D*U)
G=(X(:,dimVg+1:$))';
B2=G*B;nd=3;
R=rand(nu,nd);Q2T=-[B2;D]*R;
p=size(G,1);Q2=Q2T(1:p,:);T=Q2T(p+1:$,:);
Q=G\Q2;   //a valid [Q;T] since
[G*B;D]*R + [G*Q;T]  // is zero
closed=syslin('c',A+B*F,Q+B*R,C+D*F,T+D*R); // closed loop: d-->y
ss2tf(closed)       // Closed loop is zero
spec(closed('A'))   //The plant is not stabilizable!
[ns,nc,W,sl1]=st_ility(sl);
[A,B,C,D]=abcd(sl1);A=A(1:ns,1:ns);B=B(1:ns,:);C=C(:,1:ns);
slnew=syslin('c',A,B,C,D);  //Now stabilizable
//Fnew=stabil(slnew('A'),slnew('B'),-11);
//slnew('A')=slnew('A')+slnew('B')*Fnew;
//slnew('C')=slnew('C')+slnew('D')*Fnew;
[X,dims,F,U,k,Z]=abinv(slnew,alfa,beta);dimVg=dims(2);
[A,B,C,D]=abcd(slnew);
G=(X(:,dimVg+1:$))';
B2=G*B;nd=3;
R=rand(nu,nd);Q2T=-[B2;D]*R;
p=size(G,1);Q2=Q2T(1:p,:);T=Q2T(p+1:$,:);
Q=G\Q2;   //a valid [Q;T] since
[G*B;D]*R + [G*Q;T]  // is zero
closed=syslin('c',A+B*F,Q+B*R,C+D*F,T+D*R); // closed loop: d-->y
ss2tf(closed)       // Closed loop is zero
spec(closed('A'))

See Also

cainv , st_ility , ssrand , ss2ss , ddp ,

Author

F.D.


arhnk

Scilab Function
Last update : 12/01/2004

arhnk - Hankel norm approximant

Calling Sequence

[slm]=arhnk(sl,ord,[tol])

Parameters

  • sl : linear system ( syslin list)
  • ord : integer, order of the approximant
  • tol : threshold for rank determination in equil1

Description

computes slm , the optimal Hankel norm approximant of the stable continuous-time linear system sl with matrices [A,B,C,D] .

Examples

A=diag([-1,-2,-3,-4,-5]);B=rand(5,1);C=rand(1,5);
sl=syslin('c',A,B,C);
slapprox=arhnk(sl,2);
[nk,W]=hankelsv(sl);nk
[nkred,Wred]=hankelsv(slapprox);nkred

See Also

equil , equil1 , hankelsv ,


arl2

Scilab Function
Last update : 12/01/2004

arl2 - SISO model realization by L2 transfer approximation

Calling Sequence

h=arl2(y,den0,n [,imp])
h=arl2(y,den0,n [,imp],'all')
[den,num,err]=arl2(y,den0,n [,imp])
[den,num,err]=arl2(y,den0,n [,imp],'all')

Parameters

  • y : real vector or polynomial in z^-1 , it contains the coefficients of the Fourier's series of the rational system to approximate (the impulse response)
  • den0 : a polynomial which gives an initial guess of the solution, it may be poly(1,'z','c')
  • n : integer, the degree of approximating transfer function (degree of den)
  • imp : integer in (0,1,2) (verbose mode)
  • h : transfer function num/den or transfer matrix (column vector) when flag 'all' is given.
  • den : polynomial or vector of polynomials, contains the denominator(s) of the solution(s)
  • num : polynomial or vector of polynomials, contains the numerator(s) of the solution(s)
  • err : real constant or vector , the l2-error achieved for each solutions

Description

[den,num,err]=arl2(y,den0,n [,imp]) finds a pair of polynomials num and den such that the transfer function num/den is stable and its impulse response approximates (with a minimal l2 norm) the vector y assumed to be completed by an infinite number of zeros.

If y(z) = y(1)(1/z)+y(2)(1/z^2)+ ...+ y(ny)(1/z^ny)

then l2-norm of num/den - y(z) is err .

n is the degree of the polynomial den .

The num/den transfer function is a L2 approximant of the Fourier's series of the rational system.

Various intermediate results are printed according to imp .

[den,num,err]=arl2(y,den0,n [,imp],'all') returns in the vectors of polynomials num and den a set of local optimums for the problem. The solutions are sorted with increasing errors err . In this case den0 is already assumed to be poly(1,'z','c')

Examples

v=ones(1,20);
xbasc();
plot2d1('enn',0,[v';zeros(80,1)],2,'051',' ',[1,-0.5,100,1.5])

[d,n,e]=arl2(v,poly(1,'z','c'),1)
plot2d1('enn',0,ldiv(n,d,100),2,'000')
[d,n,e]=arl2(v,d,3)
plot2d1('enn',0,ldiv(n,d,100),3,'000')
[d,n,e]=arl2(v,d,8)
plot2d1('enn',0,ldiv(n,d,100),5,'000')

[d,n,e]=arl2(v,poly(1,'z','c'),4,'all')
plot2d1('enn',0,ldiv(n(1),d(1),100),10,'000')

See Also

ldiv , imrep2ss , time_id , armax , frep2tf ,


balreal

Scilab Function
Last update : 12/01/2004

balreal - balanced realization

Calling Sequence

[slb [,U] ] = balreal(sl)

Parameters

  • sl,slb : linear systems ( syslin lists)

Description

Balanced realization of linear system sl=[A,B,C,D] . sl can be a continuous-time or discrete-time state-space system. sl is assumed stable.

slb=[inv(U)*A*U ,inv(U)*B , C*U , D]

is the balanced realization.

slb is returned as a syslin list.

Examples

A=diag([-1,-2,-3,-4,-5]);B=rand(5,2);C=rand(1,5);
sl=syslin('c',A,B,C);
[slb,U]=balreal(sl);
Wc=clean(ctr_gram(slb))
W0=clean(obs_gram(slb))

See Also

ctr_gram , obs_gram , hankelsv , equil , equil1 ,


bilin

Scilab Function
Last update : 12/01/2004

bilin - general bilinear transform

Calling Sequence

[sl1]=bilin(sl,v)

Parameters

  • sl,sl1 : linear systems ( syslin lists)
  • v : real vector with 4 entries ( v=[a,b,c,d] )

Description

Given a linear system in state space form, sl=syslin(dom,A,B,C,D) ( syslin list), sl1=bilin(sl,v) returns in sl1 a linear system with matrices [A1,B1,C1,D1] such that the transfer function H1(s)=C1*inv(s*eye()-A1)*B1+D1 is obtained from H(z)=C*inv(z*eye()-A)*B+D by replacing z by z=(a*s+b)/(c*s+d) . One has w=bilin(bilin(w,[a,b,c,d]),[d,-b,-c,a])

Examples

s=poly(0,'s');z=poly(0,'z');
w=ssrand(1,1,3);
wtf=ss2tf(w);v=[2,3,-1,4];a=v(1);b=v(2);c=v(3);d=v(4);
[horner(wtf,(a*z+b)/(c*z+d)),ss2tf(bilin(w,[a,b,c,d]))]
clean(ss2tf(bilin(bilin(w,[a,b,c,d]),[d,-b,-c,a]))-wtf)

See Also

horner , cls2dls ,


cainv

Scilab Function
Last update : 12/01/2004

cainv - Dual of abinv

Calling Sequence

[X,dims,J,Y,k,Z]=cainv(Sl,alfa,beta,flag)

Parameters

  • Sl : syslin list containing the matrices [A,B,C,D] .
  • alfa : real number or vector (possibly complex, location of closed loop poles)
  • beta : real number or vector (possibly complex, location of closed loop poles)
  • flag : (optional) character string 'ge' (default) or 'st' or 'pp'
  • X : orthogonal matrix of size nx (dim of state space).
  • dims : integer row vector dims=[nd1,nu1,dimS,dimSg,dimN] (5 entries, nondecreasing order).If flag='st' , (resp. 'pp' ), dims has 4 (resp. 3) components.
  • J : real matrix (output injection)
  • Y : orthogonal matrix of size ny (dim of output space).
  • k : integer (normal rank of Sl )
  • Z : non-singular linear system ( syslin list)

Description

cainv finds a bases (X,Y) (of state space and output space resp.) and output injection matrix J such that the matrices of Sl in bases (X,Y) are displayed as:

                  [A11,*,*,*,*,*]                [*]
                  [0,A22,*,*,*,*]                [*]
   X'*(A+J*C)*X = [0,0,A33,*,*,*]   X'*(B+J*D) = [*]
                  [0,0,0,A44,*,*]                [0]
                  [0,0,0,0,A55,*]                [0]
                  [0,0,0,0,0,A66]                [0]

          Y*C*X = [0,0,C13,*,*,*]          Y*D = [*]
                  [0,0,0,0,0,C26]                [0]

The partition of X is defined by the vector dims=[nd1,nu1,dimS,dimSg,dimN] and the partition of Y is determined by k .

Eigenvalues of A11 (nd1 x nd1) are unstable. Eigenvalues of A22 (nu1-nd1 x nu1-nd1) are stable.

The pair (A33, C13) (dimS-nu1 x dimS-nu1, k x dimS-nu1) is observable, and eigenvalues of A33 are set to alfa .

Matrix A44 (dimSg-dimS x dimSg-dimS) is unstable. Matrix A55 (dimN-dimSg,dimN-dimSg) is stable

The pair (A66,C26) (nx-dimN x nx-dimN) is observable, and eigenvalues of A66 set to beta .

The dimS first columns of X span S= smallest (C,A) invariant subspace which contains Im(B), dimSg first columns of X span Sg the maximal "complementary detectability subspace" of Sl

The dimN first columns of X span the maximal "complementary observability subspace" of Sl . ( dimS=0 if B(ker(D))=0).

If flag='st' is given, a five blocks partition of the matrices is returned and dims has four components. If flag='pp' is given a four blocks partition is returned (see abinv).

This function can be used to calculate an unknown input observer:

// DDEP: dot(x)=A x + Bu + Gd
//           y= Cx   (observation)
//           z= Hx    (z=variable to be estimated, d=disturbance)
//  Find: dot(w) = Fw + Ey + Ru such that
//          zhat = Mw + Ny
//           z-Hx goes to zero at infinity
//  Solution exists iff Ker H contains Sg(A,C,G) inter KerC (assuming detectability)
//i.e. H is such that:
// For any W which makes a column compression of [Xp(1:dimSg,:);C]
// with Xp=X' and [X,dims,J,Y,k,Z]=cainv(syslin('c',A,G,C));
// [Xp(1:dimSg,:);C]*W = [0 | *] one has
// H*W = [0 | *]  (with at least as many aero columns as above).

See Also

abinv , dt_ility , ui_observer ,


calfrq

Scilab Function
Last update : 12/01/2004

calfrq - frequency response discretization

Calling Sequence

[frq,split]=calfrq(h,[fmin,fmax])

Parameters

  • h : SISO linear system ( syslin list)
  • fmin,fmax : real scalars (min and max frequencies)
  • frq : row vector (discretization of interval)
  • split : vector of frq splitting points indexes

Description

frequency response discretization ; frq is the discretization of [fmin,fmax] such that the peaks in the frequency response are well represented.

Default values for fmin and fmax are 1.d-3 , 1.d+3 if h is continuous-time or 1.d-3 , 1/(2*h('dt')) if h is discrete-time.

Singularities are located between frq(split(k)) and frq(split(k)+1) for k>1 .

Examples

s=poly(0,'s')
h=syslin('c',(s^2+2*0.9*10*s+100)/(s^2+2*0.3*10.1*s+102.01))
h1=h*syslin('c',(s^2+2*0.1*15.1*s+228.01)/(s^2+2*0.9*15*s+225))
[f1,spl]=calfrq(h1,0.01,1000);
rf=repfreq(h1,f1);
plot2d(real(rf)',imag(rf)')

See Also

bode , black , nyquist , freq , repfreq , logspace ,


canon

Scilab Function
Last update : 12/01/2004

canon - canonical controllable form

Calling Sequence

[Ac,Bc,U,ind]=canon(A,B)

Parameters

  • Ac,Bc : canonical form
  • U : current basis (square nonsingular matrix)
  • ind : vector of integers, controllability indices

Description

gives the canonical controllable form of the pair (A,B) .

Ac=inv(U)*A*U, Bc=inv(U)*B

The vector ind is made of the epsilon_i 's indices of the pencil [sI - A , B] (decreasing order). For example with ind=[3,2] , Ac and Bc are as follows:

      [*,*,*,*,*]           [*]
      [1,0,0,0,0]           [0]
Ac=   [0,1,0,0,0]        Bc=[0]
      [*,*,*,*,*]           [*]
      [0,0,0,1,0]           [0]

If (A,B) is controllable, by an appropriate choice of F the * entries of Ac+Bc*F can be arbitrarily set to desired values (pole placement).

Examples

A=[1,2,3,4,5;
   1,0,0,0,0;
   0,1,0,0,0;
   6,7,8,9,0;
   0,0,0,1,0];
B=[1,2;
   0,0;
   0,0;
   2,1;
   0,0];
X=rand(5,5);A=X*A*inv(X);B=X*B;    //Controllable pair
[Ac,Bc,U,ind]=canon(A,B);  //Two indices --> ind=[3.2];
index=1;for k=1:size(ind,'*')-1,index=[index,1+sum(ind(1:k))];end
Acstar=Ac(index,:);Bcstar=Bc(index,:);
s=poly(0,'s');
p1=s^3+2*s^2-5*s+3;p2=(s-5)*(s-3);
//p1 and p2 are desired closed-loop polynomials with degrees 3,2
c1=coeff(p1);c1=c1($-1:-1:1);c2=coeff(p2);c2=c2($-1:-1:1);
Acstardesired=[-c1,0,0;0,0,0,-c2];
//Acstardesired(index,:) is companion matrix with char. pol=p1*p2
F=Bcstar\(Acstardesired-Acstar);   //Feedbak gain
Ac+Bc*F         // Companion form
spec(A+B*F/U)   // F/U is the gain matrix in original basis.

See Also

obsv_mat , cont_mat , ctr_gram , contrss , ppol , contr , stabil ,

Author

F.D.


cls2dls

Scilab Function
Last update : 12/01/2004

cls2dls - bilinear transform

Calling Sequence

[sl1]=cls2dls(sl,T [,fp])

Parameters

  • sl,sl1 : linear systems ( syslin lists)
  • T : real number, the sampling period
  • fp : prevarping frequency in hertz

Description

given sl=[A,B,C,D] ( syslin list),a continuous time system cls2dls returns the sampled system obtained by the bilinear transform s=(2/T)*(z-1)/(z+1) .

Examples

s=poly(0,'s');z=poly(0,'z');
sl=syslin('c',(s+1)/(s^2-5*s+2));  //Continuous-time system in transfer form
slss=tf2ss(sl);  //Now in state-space form
sl1=cls2dls(slss,0.2);  //sl1= output of cls2dls
sl1t=ss2tf(sl1) // Converts in transfer form
sl2=horner(sl,(2/0.2)*(z-1)/(z+1))   //Compare sl2 and sl1

See Also

horner ,


colregul

Scilab Function
Last update : 12/01/2004

colregul - removing poles and zeros at infinity

Calling Sequence

[Stmp,Ws]=colregul(Sl,alfa,beta)

Parameters

  • Sl,Stmp : syslin lists
  • alfa,beta : reals (new pole and zero positions)

Description

computes a prefilter Ws such that Stmp=Sl*Ws is proper and with full rank D matrix.

Poles at infinity of Sl are moved to alfa ;

Zeros at infinity of Sl are moved to beta ;

Sl is a assumed to be a left invertible linear system ( syslin list) in state-space representation with possibly a polynomial D matrix.

See Also

invsyslin , inv , rowregul , rowshuff ,

Author

F. D. , R. N. ;


contrss

Scilab Function
Last update : 12/01/2004

contrss - controllable part

Calling Sequence

[slc]=contrss(sl [,tol])

Parameters

  • sl : linear system ( syslin list)
  • tol : is a threshold for controllability (see contr ). default value is sqrt(%eps) .

Description

returns the controllable part of the linear system sl = (A,B,C,D) in state-space form.

Examples

A=[1,1;0,2];B=[1;0];C=[1,1];sl=syslin('c',A,B,C);  //Non minimal
slc=contrss(sl);
sl1=ss2tf(sl);sl2=ss2tf(slc);      //Compare sl1 and sl2

See Also

cont_mat , ctr_gram , cont_frm , contr ,


contr

Scilab Function
Last update : 12/01/2004

contr - controllability, controllable subspace, staircase

Calling Sequence

n=contr(A,B [,tol])
[n,U]=contr(A,B [,tol])
[n,U,ind,V,Ac,Bc]=contr(A,B,[,tol])

Parameters

  • A, B : real matrices
  • tol : tolerance parameter
  • n : dimension of controllable subspace.
  • U : orthogonal change of basis which puts (A,B) in canonical form.
  • V : orthogonal matrix, change of basis in the control space.
  • Ac : block Hessenberg matrix Ac=U'*A*V
  • Bc : is U'*B*V .
  • ind : p integer vector associated with controllability indices (dimensions of subspaces B, B+A*B,...=ind(1),ind(1)+ind(2),... )

Description

[n,[U]]=contr(A,B,[tol]) gives the controllable form of an (A,B) pair.( dx/dt = A x + B u or x(n+1) = A x(n) +b u(n) ). The n first columns of U make a basis for the controllable subspace.

If V=U(:,1:n) , then V'*A*V and V'*B give the controllable part of the (A,B) pair.

The pair (Bc, Ac) is in staircase controllable form.

                        |B |sI-A      *  . . .  *      *       |
                        | 1|    11       .      .      .       |
                        |  |  A    sI-A    .    .      .       |
                        |  |   21      22    .  .      .       |
                        |  |        .     .     *      *       |
     [U'BV|sI - U'AU] = |0 |     0    .     .                  |
                        |  |            A     sI-A     *       |
                        |  |             p,p-1    pp           |
                        |  |                                   |
                        |0 |         0          0   sI-A       |
                        |  |                            p+1,p+1|

Reference

Slicot library (see ab01od in SCIDIR/routines/slicot).

Examples

W=ssrand(2,3,5,list('co',3));  //cont. subspace has dim 3.
A=W("A");B=W("B");
[n,U]=contr(A,B);n
A1=U'*A*U;
spec(A1(n+1:$,n+1:$))  //uncontrollable modes
spec(A+B*rand(3,5))

See Also

canon , cont_mat , unobs , stabil , st_ility ,


cont_frm

Scilab Function
Last update : 12/01/2004

cont_frm - transfer to controllable state-space

Calling Sequence

[sl]=cont_frm(NUM,den)

Parameters

  • NUM : polynomial matrix
  • den : polynomial
  • sl : syslin list, sl=[A,B,C,D] .

Description

controllable state-space form of the transfer NUM/den .

Examples

s=poly(0,'s');NUM=[1+s,s];den=s^2-5*s+1;
sl=cont_frm(NUM,den);
slss=ss2tf(sl);       //Compare with NUM/den

See Also

tf2ss , canon , contr ,


cont_mat

Scilab Function
Last update : 12/01/2004

cont_mat - controllability matrix

Calling Sequence

Cc=cont_mat(A,B)
Cc=cont_mat(sl)

Parameters

  • a,b : two real matrices of appropriate dimensions
  • sl : linear system ( syslin list)

Description

cont_mat returns the controllability matrix of the pair A,B (resp. of the system sl=[A,B,C,D] ).

Cc=[B, AB, A^2 B,..., A^(n-1) B]

See Also

ctr_gram , contr , canon , st_ility ,


csim

Scilab Function
Last update : 12/01/2004

csim - simulation (time response) of linear system

Calling Sequence

[y [,x]]=csim(u,t,sl,[x0 [,tol]])

Parameters

  • u : function, list or string (control)
  • t : real vector specifying times with, t(1) is the initial time ( x0=x(t(1)) ).
  • sl : list ( syslin )
  • y : a matrix such that y=[y(t(i)] , i=1,..,n
  • x : a matrix such that x=[x(t(i)] , i=1,..,n
  • tol : a 2 vector [atol rtol] defining absolute and relative tolerances for ode solver (see ode)

Description

simulation of the controlled linear system sl . sl is assumed to be a continuous-time system represented by a syslin list.

u is the control and x0 the initial state.

y is the output and x the state.

The control can be:

1. a function : [inputs]=u(t)

2. a list : list(ut,parameter1,....,parametern) such that: inputs=ut(t,parameter1,....,parametern) ( ut is a function)

3. the string "impuls" for impulse response calculation (here sl is assumed SISO without direct feed through and x0=0 )

4. the string "step" for step response calculation (here sl is assumed SISO without direct feed-through and x0=0 )

5. a vector giving the values of u correponding to each t value.

Examples

s=poly(0,'s');rand('seed',0);w=ssrand(1,1,3);w('A')=w('A')-2*eye();
t=0:0.05:5;
//impulse(w) = step (s * w)
xbasc(0);xset("window",0);xselect();
plot2d([t',t'],[(csim('step',t,tf2ss(s)*w))',0*t'])
xbasc(1);xset("window",1);xselect();
plot2d([t',t'],[(csim('impulse',t,w))',0*t'])
//step(w) = impulse (s^-1 * w)
xbasc(3);xset("window",3);xselect();
plot2d([t',t'],[(csim('step',t,w))',0*t'])
xbasc(4);xset("window",4);xselect();
plot2d([t',t'],[(csim('impulse',t,tf2ss(1/s)*w))',0*t'])

//input defined by a time function
deff('u=input(t)','u=abs(sin(t))')
xbasc();plot2d([t',t'],[(csim(input,t,w))',0*t'])

See Also

syslin , dsimul , flts , ltitr , rtitr , ode , impl ,


ctr_gram

Scilab Function
Last update : 12/01/2004

ctr_gram - controllability gramian

Calling Sequence

[Gc]=ctr_gram(A,B [,dom])
[Gc]=ctr_gram(sl)

Parameters

  • A,B : two real matrices of appropriate dimensions
  • dom : character string ( 'c' (default value) or 'd' )
  • sl : linear system, syslin list

Description

Controllability gramian of (A,B) or sl (a syslin linear system).

dom character string giving the time domain : "d" for a discrete time system and "c" for continuous time (default case).

Examples

A=diag([-1,-2,-3]);B=rand(3,2);
Wc=ctr_gram(A,B)
U=rand(3,3);A1=U*A/U;B1=U*B;
Wc1=ctr_gram(A1,B1)    //Not invariant!

See Also

equil1 , obs_gram , contr , cont_mat , cont_frm , contrss ,

Author

S. Steer INRIA 1988


dbphi

Scilab Function
Last update : 12/01/2004

dbphi - frequency response to phase and magnitude representation

Calling Sequence

[db,phi] =dbphi(repf)

Parameters

  • db,phi : vector of gains (db) and phases (degrees)
  • repf : vector of complex frequency response

Description

db(k) is the magnitude of repf(k) expressed in dB i.e. db(k)=20*log(abs(repf(k)))/log(10) and phi(k) is the phase of repf(k) expressed in degrees.

See Also

repfreq , bode ,


ddp

Scilab Function
Last update : 12/01/2004

ddp - disturbance decoupling

Calling Sequence

[Closed,F,G]=ddp(Sys,zeroed,B1,D1)
[Closed,F,G]=ddp(Sys,zeroed,B1,D1,flag,alfa,beta)

Parameters

  • Sys : syslin list containing the matrices (A,B2,C,D2) .
  • zeroed : integer vector, indices of outputs of Sys which are zeroed.
  • B1 : real matrix
  • D1 : real matrix. B1 and D1 have the same number of columns.
  • flag : string 'ge' or 'st' (default) or 'pp' .
  • alfa : real or complex vector (loc. of closed loop poles)
  • beta : real or complex vector (loc. of closed loop poles)

Description

Exact disturbance decoupling (output nulling algorithm). Given a linear system, and a subset of outputs, z, which are to be zeroed, characterize the inputs w of Sys such that the transfer function from w to z is zero. Sys is a linear system {A,B2,C,D2} with one input and two outputs ( i.e. Sys: u-->(z,y) ), part the following system defined from Sys and B1,D1 :

  xdot =  A x + B1  w + B2  u
     z = C1 x + D11 w + D12 u
     y = C2 x + D21 w + D22 u

outputs of Sys are partitioned into (z,y) where z is to be zeroed, i.e. the matrices C and D2 are:

     C=[C1;C2]         D2=[D12;D22]
     C1=C(zeroed,:)    D12=D2(zeroed,:)

The matrix D1 is partitioned similarly as D1=[D11;D21] with D11=D1(zeroed,:) . The control is u=Fx+Gw and one looks for matriced F,G such that the closed loop system: w-->z given by

  xdot= (A+B2*F)  x + (B1 + B2*G) w
    z = (C1+D12F) x + (D11+D12*G) w

has zero transfer transfer function.

flag='ge' : no stability constraints. flag='st' : look for stable closed loop system (A+B2*F stable). flag='pp' : eigenvalues of A+B2*F are assigned to alfa and beta .

Closed is a realization of the w-->y closed loop system

  xdot= (A+B2*F)  x + (B1 + B2*G) w
    y = (C2+D22*F) x + (D21+D22*G) w

Stability (resp. pole placement) requires stabilizability (resp. controllability) of (A,B2).

Examples

rand('seed',0);nx=6;nz=3;nu=2;ny=1;
A=diag(1:6);A(2,2)=-7;A(5,5)=-9;B2=[1,2;0,3;0,4;0,5;0,0;0,0];
C1=[zeros(nz,nz),eye(nz,nz)];D12=[0,1;0,2;0,3];
Sys12=syslin('c',A,B2,C1,D12);
C=[C1;rand(ny,nx)];D2=[D12;rand(ny,size(D12,2))];
Sys=syslin('c',A,B2,C,D2);
[A,B2,C1,D12]=abcd(Sys12);  //The matrices of Sys12.
alfa=-1;beta=-2;flag='ge';
[X,dims,F,U,k,Z]=abinv(Sys12,alfa,beta,flag);
clean(X'*(A+B2*F)*X)
clean(X'*B2*U)
clean((C1+D12*F)*X)
clean(D12*U);
//Calculating an ad-hoc B1,D1
G1=rand(size(B2,2),3);
B1=-B2*G1;
D11=-D12*G1;
D1=[D11;rand(ny,size(B1,2))];

[Closed,F,G]=ddp(Sys,1:nz,B1,D1,'st',alfa,beta);
closed=syslin('c',A+B2*F,B1+B2*G,C1+D12*F,D11+D12*G);
ss2tf(closed)

See Also

abinv , ui_observer ,

Author

F.D.


des2tf

Scilab Function
Last update : 12/01/2004

des2tf - descriptor to transfer function conversion

Calling Sequence

[S]=des2tf(sl)
[Bfs,Bis,chis]=des2tf(sl)

Parameters

  • sl : list (linear system in descriptor form)
  • Bfs, Bis : two polynomial matrices
  • chis : polynomial
  • S : rational matrix

Description

Given the linear system in descriptor form i.e. Sl=list('des',A,B,C,D,E) , des2tf converts sl into its transfer function representation:

S=C*(s*E-A)^(-1)*B+D

Called with 3 outputs arguments des2tf returns Bfs and Bis two polynomial matrices, and chis polynomial such that:

S=Bfs/chis - Bis

chis is the determinant of (s*E-A) (up to a xcative constant);

Examples

s=poly(0,'s');
G=[1/(s+1),s;1+s^2,3*s^3];
Descrip=tf2des(G);Tf1=des2tf(Descrip)
Descrip2=tf2des(G,"withD");Tf2=des2tf(Descrip2)
[A,B,C,D,E]=Descrip2(2:6);Tf3=C*inv(s*E-A)*B+D

See Also

glever , pol2des , tf2des , ss2tf , des2ss , rowshuff ,

Author

F. D.


dscr

Scilab Function
Last update : 12/01/2004

dscr - discretization of linear system

Calling Sequence

[sld [,r]]=dscr(sl,dt [,m])

Parameters

  • sl : syslin list containing [A,B,C,D] .
  • dt : real number, sampling period
  • m : covariance of the input noise (continuous time)(default value=0)
  • r : covariance of the output noise (discrete time) given if m is given as input
  • sld : sampled (discrete-time) linear system, syslin list

Description

Discretization of linear system. sl is a continuous-time system:

dx/dt=A*x+B*u (+ noise) .

sld is the discrete-time system obtained by sampling sl with the sampling period dt .

Examples

s=poly(0,'s');
Sys=syslin('c',[1,1/(s+1);2*s/(s^2+2),1/s])
ss2tf(dscr(tf2ss(Sys),0.1))

See Also

syslin , flts , dsimul ,


dsimul

Scilab Function
Last update : 12/01/2004

dsimul - state space discrete time simulation

Calling Sequence

y=dsimul(sl,u)

Parameters

  • sl : syslin list describing a discrete time linear system
  • u : real matrix of appropriate dimension
  • y : output of sl

Description

Utility function. If [A,B,C,D]=abcd(sl) and x0=sl('X0') , dsimul returns y=C*ltitr(A,B,u,x0)+D*u i.e. the time response of sl to the input u . sl is assumed to be in state space form ( syslin list).

Examples

z=poly(0,'z');
h=(1-2*z)/(z^2-0.2*z+1);
sl=tf2ss(h);
u=zeros(1,20);u(1)=1;
x1=dsimul(sl,u)   //Impulse response
u=ones(1,20);
x2=dsimul(sl,u);  //Step response

See Also

syslin , flts , ltitr ,


dt_ility

Scilab Function
Last update : 12/01/2004

dt_ility - detectability test

Calling Sequence

[k, [n [,U [,Sld ] ] ]]=dt_ility(Sl [,tol])

Parameters

  • Sl : linear system ( syslin list)
  • n : dimension of unobservable subspace
  • k : dimension of unstable, unobservable subspace ( k<=n ).
  • U : orthogonal matrix
  • Sld : linear system ( syslin list)
  • tol : threshold for controllability test.

Description

Detectability test for sl , a linear system in state-space representation. U is a basis whose k first columns span the unstable, unobservable subspace of Sl (intersection of unobservable subspace of (A,C) and unstable subspace of A ). Detectability means k=0 .

Sld = (U'*A*U,U'*B,C*U,D) displays the "detectable part" of Sl=(A,B,C,D) , i.e.

         [*,*,*]
U'*A*U = [0,*,*]
         [0,0,*]

C*U = [0,0,*]

with (A33,C3) observable (dimension nx-n ), A22 stable (dimension n-k ) and A11 unstable (dimension k ).

Examples

A=[2,1,1;0,-2,1;0,0,3];
C=[0,0,1];
X=rand(3,3);A=inv(X)*A*X;C=C*X;
W=syslin('c',A,[],C);
[k,n,U,W1]=dt_ility(W);
W1("A")
W1("C")

See Also

contr , st_ility , unobs , stabil ,


equil1

Scilab Function
Last update : 12/01/2004

equil1 - balancing (nonnegative) pair of matrices

Calling Sequence

[T [,siz]]=equil1(P,Q [,tol])

Parameters

  • P, Q : two non-negative symmetric matrices
  • T : nonsingular matrix
  • siz : vector of three integers
  • tol : threshold

Description

equil1 computes t such that:

P1=T*P*T' and Q1=inv(T)'*Q*inv(T) are as follows:

P1 = diag(S1,S2,0,0) and Q1 = diag(S1,0,S3,0) with S1,S2,S3 positive and diagonal matrices with respective dimensions siz=[n1,n2,n3]

tol is a threshold for rank determination in SVD

Examples

S1=rand(2,2);S1=S1*S1';
S2=rand(2,2);S2=S2*S2';
S3=rand(2,2);S3=S3*S3';
P=sysdiag(S1,S2,zeros(4,4));
Q=sysdiag(S1,zeros(2,2),S3,zeros(2,2));
X=rand(8,8);
P=X*P*X';Q=inv(X)'*Q*inv(X);
[T,siz]=equil1(P,Q);
P1=clean(T*P*T')
Q1=clean(inv(T)'*Q*inv(T))

See Also

balreal , minreal , equil , hankelsv ,

Author

S. Steer 1987


equil

Scilab Function
Last update : 12/01/2004

equil - balancing of pair of symmetric matrices

Calling Sequence

T=equil(P,Q)

Parameters

  • P, Q : two positive definite symmetric matrices
  • T : nonsingular matrix

Description

equil returns t such that:

T*P*T' and inv(T)'*Q*inv(T) are both equal to a same diagonal and positive matrix.

Examples

P=rand(4,4);P=P*P';
Q=rand(4,4);Q=Q*Q';
T=equil(P,Q)
clean(T*P*T')
clean(inv(T)'*Q*inv(T))

See Also

equil1 , balanc , ctr_gram ,


feedback

Scilab Function
Last update : 12/01/2004

feedback - feedback operation

Calling Sequence

Sl=Sl1/.Sl2

Parameters

  • Sl1,Sl2 : linear systems ( syslin list) in state-space or transfer form, or ordinary gain matrices.
  • Sl : linear system ( syslin list) in state-space or transfer form

Description

The feedback operation is denoted by /. (slashdot). This command returns Sl=Sl1*(I+Sl2*Sl1)^-1 , i.e the (negative) feedback of Sl1 and Sl2 . Sl is the transfer v -> y for y = Sl1 u , u = v - Sl2 y .

The result is the same as Sl=LFT([0,I;I,-Sl2],Sl1) .

Caution: do not use with decimal point (e.g. 1/.1 is ambiguous!)

Examples

S1=ssrand(2,2,3);S2=ssrand(2,2,2);
W=S1/.S2;
ss2tf(S1/.S2)
//Same operation by LFT:
ss2tf(lft([zeros(2,2),eye(2,2);eye(2,2),-S2],S1))
//Other approach: with constant feedback
BigS=sysdiag(S1,S2); F=[zeros(2,2),eye(2,2);-eye(2,2),zeros(2,2)];
Bigclosed=BigS/.F;
W1=Bigclosed(1:2,1:2);   //W1=W (in state-space).
ss2tf(W1)
//Inverting
ss2tf(S1*inv(eye()+S2*S1))

See Also

lft , sysdiag , augment , obscont ,


flts

Scilab Function
Last update : 12/01/2004

flts - time response (discrete time, sampled system)

Calling Sequence

[y [,x]]=flts(u,sl [,x0])
[y]=flts(u,sl [,past])

Parameters

  • u : matrix (input vector)
  • sl : list (linear system syslin )
  • x0 : vector (initial state ; default value= 0 )
  • past : matrix (of the past ; default value= 0 )
  • x,y : matrices (state and output)

Description

State-space form:

sl is a syslin list containing the matrices of the following linear system

sl=syslin('d',A,B,C,D) (see syslin ):

  x[t+1] = A x[t] + B u[t]
  y[t] = C x[t] + D u[t]

or, more generally, if D is a polynomial matrix ( p = degree(D(z)) ) :

Transfer form:

y=flts(u,sl[,past]) . Here sl is a linear system in transfer matrix representation i.e

sl=syslin('d',transfer_matrix) (see syslin ).

is the matrix of past values of u and y.

nd is the maximum of degrees of lcm's of each row of the denominator matrix of sl.

u=[u0 u1 ... un]  (input)
y=[y0 y1 ... yn]  (output)

p is the difference between maximum degree of numerator and maximum degree of denominator

Examples

sl=syslin('d',1,1,1);u=1:10;
y=flts(u,sl);
plot2d2("onn",(1:size(u,'c'))',y')
[y1,x1]=flts(u(1:5),sl);y2=flts(u(6:10),sl,x1);
y-[y1,y2]

//With polynomial D:
z=poly(0,'z');
D=1+z+z^2; p =degree(D);
sl=syslin('d',1,1,1,D);
y=flts(u,sl);[y1,x1]=flts(u(1:5),sl);
y2=flts(u(5-p+1:10),sl,x1);  // (update)
y-[y1,y2]

//Delay (transfer form): flts(u,1/z)
// Usual responses
z=poly(0,'z');
h=(1-2*z)/(z^2+0.3*z+1)
u=zeros(1,20);u(1)=1;
imprep=flts(u,tf2ss(h));   //Impulse response
plot2d2("onn",(1:size(u,'c'))',imprep')
u=ones(1,20);
stprep=flts(u,tf2ss(h));   //Step response
plot2d2("onn",(1:size(u,'c'))',stprep')
//
// Other examples
A=[1 2 3;0 2 4;0 0 1];B=[1 0;0 0;0 1];C=eye(3,3);Sys=syslin('d',A,B,C);
H=ss2tf(Sys); u=[1;-1]*(1:10);
//
yh=flts(u,H); ys=flts(u,Sys);
norm(yh-ys,1)
//hot restart
[ys1,x]=flts(u(:,1:4),Sys);ys2=flts(u(:,5:10),Sys,x);
norm([ys1,ys2]-ys,1)
//
yh1=flts(u(:,1:4),H);yh2=flts(u(:,5:10),H,[u(:,2:4);yh(:,2:4)]);
norm([yh1,yh2]-yh,1)
//with D<>0
D=[-3 8;4 -0.5;2.2 0.9];
Sys=syslin('d',A,B,C,D);
H=ss2tf(Sys); u=[1;-1]*(1:10);
rh=flts(u,H); rs=flts(u,Sys);
norm(rh-rs,1)
//hot restart
[ys1,x]=flts(u(:,1:4),Sys);ys2=flts(u(:,5:10),Sys,x);
norm([ys1,ys2]-rs,1)
//With H:
yh1=flts(u(:,1:4),H);yh2=flts(u(:,5:10),H,[u(:,2:4); yh1(:,2:4)]);
norm([yh1,yh2]-rh)

See Also

ltitr , dsimul , rtitr ,


frep2tf

Scilab Function
Last update : 15/01/2004

frep2tf - transfer function realization from frequency response

Calling Sequence

[h [,err]]=frep2tf(frq,repf,dg [,dom,tols,weight])

Parameters

  • frq : vector of frequencies in Hz.
  • repf : vector of frequency response
  • dg : degree of linear system
  • dom : time domain ( 'c' or 'd' or dt )
  • tols : a vector of size 3 giving the relative and absolute tolerance and the maximum number of iterations (default values are rtol=1.e-2; atol=1.e-4, N=10 ).
  • weight : vector of weights on frequencies
  • h : SISO transfer function
  • err : error (for example if dom='c' sum(abs(h(2i*pi*frq) - rep)^2)/size(frq,*) )

Description

Frequency response to transfer function conversion. The order of h is a priori given in dg which must be provided. The following linear system is solved in the least square sense.

 weight(k)*(n( phi_k) - d(phi_k)*rep_k)=0, k=1,..,n

where phi_k= 2*%i*%pi*frq when dom='c' and phi_k=exp(2*%i*%pi*dom*frq if not. If the weight vector is not given a default penalization is used (when dom='c' ).

A stable and minimum phase system can be obtained by using function factors .

Examples

s=poly(0,'s');
h=syslin('c',(s-1)/(s^3+5*s+20))
frq=0:0.05:3;repf=repfreq(h,frq);
clean(frep2tf(frq,repf,3))

Sys=ssrand(1,1,10);
frq=logspace(-3,2,200);
[frq,rep]=repfreq(Sys,frq);  //Frequency response of Sys
[Sys2,err]=frep2tf(frq,rep,10);Sys2=clean(Sys2)//Sys2 obtained from freq. resp of Sys
[frq,rep2]=repfreq(Sys2,frq); //Frequency response of Sys2
xbasc();bode(frq,[rep;rep2])   //Responses of Sys and Sys2
[sort(spec(Sys('A'))),sort(roots(Sys2('den')))] //poles

dom=1/1000; // Sampling time
z=poly(0,'z');
h=syslin(dom,(z^2+0.5)/(z^3+0.1*z^2-0.5*z+0.08))
frq=(0:0.01:0.5)/dom;repf=repfreq(h,frq);
[Sys2,err]=frep2tf(frq,repf,3,dom);
[frq,rep2]=repfreq(Sys2,frq); //Frequency response of Sys2
xbasc();plot2d1("onn",frq',abs([repf;rep2])');

See Also

imrep2ss , arl2 , time_id , armax , frfit ,


freq

Scilab Function
Last update : 12/01/2004

freq - frequency response

Calling Sequence

[x]=freq(A,B,C [,D],f)
[x]=freq(NUM,DEN,f)

Parameters

  • A, B, C, D : real matrices of respective dimensions nxn, nxp, mxn, mxp .
  • NUM,DEN : polynomial matrices of dimension mxp
  • x : real or complex matrix

Description

x=freq(A,B,C [,D],f) returns a real or complex mxp*t matrix such that:

x(:,k*p:(k+1)*p)= C*inv(f(k)*eye()-A)*B + D .

Thus, for f taking values along the imaginary axis or on the unit circle x is the continuous or discrete time frequency response of (A,B,C,D) .

x=freq(NUM,DEN,f) returns a real or complex matrix x such that columns k*(p-1)+1 to k*p of x contain the matrix NUM(f(k))./DEN(f(k))

Examples

s=poly(0,'s');
sys=(s+1)/(s^3-5*s+4)
rep=freq(sys("num"),sys("den"),[0,0.9,1.1,2,3,10,20])
[horner(sys,0),horner(sys,20)]
//
Sys=tf2ss(sys);
[A,B,C,D]=abcd(Sys);
freq(A,B,C,[0,0.9,1.1,2,3,10,20])

See Also

repfreq , horner ,


freson

Scilab Function
Last update : 12/01/2004

freson - peak frequencies

Calling Sequence

fr=freson(h)

Parameters

  • h : syslin list
  • fr : vector of peak frequencies in Hz

Description

returns the vector of peak frequencies in Hz for the SISO plant h

Examples

h=syslin('c',-1+%s,(3+2*%s+%s^2)*(50+0.1*%s+%s^2))
fr=freson(h)
bode(h)
g=20*log(abs(repfreq(h,fr)))/log(10)

See Also

frep2tf , zgrid , h_norm ,


gfrancis

Scilab Function
Last update : 12/01/2004

gfrancis - Francis equations for tracking

Calling Sequence

[L,M,T]=gfrancis(Plant,Model)

Parameters

  • Plant : syslin list
  • Model : syslin list
  • L,M,T : real matrices

Description

Given the the linear plant:

    x'= F*x + G*u
    y = H*x + J*u

and the linear model

    xm'= A*xm + B*um
    ym = C*xm + D*um

the goal is for the plant to track the model i.e. e = y - ym ---> 0 while keeping stable the state x(t) of the plant. u is given by feedforward and feedback

 u = L*xm + M*um + K*(x-T*xm) = [K , L-K*T] *(x,xm) + M*um

The matrices T,L,M satisfy generalized Francis equations

    F*T + G*L = T*A
    H*T + J*L = C
          G*M = T*B
          J*M = D

The matrix K must be chosen as stabilizing the pair (F,G) See example of use in directory demos/tracking .

Examples

Plant=ssrand(1,3,5);
[F,G,H,J]=abcd(Plant);
nw=4;nuu=2;A=rand(nw,nw);
st=maxi(real(spec(A)));A=A-st*eye(A);
B=rand(nw,nuu);C=2*rand(1,nw);D=0*rand(C*B);
Model=syslin('c',A,B,C,D);
[L,M,T]=gfrancis(Plant,Model);
norm(F*T+G*L-T*A,1)
norm(H*T+J*L-C,1)
norm(G*M-T*B,1)
norm(J*M-D,1)

See Also

lqg , ppol ,


g_margin

Scilab Function
Last update : 12/01/2004

g_margin - gain margin

Calling Sequence

[gm [,fr]]=g_margin(h)

Parameters

  • h : syslin list representing a linear system in state-space or transfer form

Description

returns gm , the gain margin in dB of h (SISO plant) and fr , the achieved corresponding frequency in hz. The gain margin is values of the system gain at points where the nyquist plot crosses the negative real axis.

Examples

h=syslin('c',-1+%s,3+2*%s+%s^2)
[g,fr]=g_margin(h)
[g,fr]=g_margin(h-10)
nyquist(h-10)

See Also

p_margin , black , chart , nyquist ,


imrep2ss

Scilab Function
Last update : 12/01/2004

imrep2ss - state-space realization of an impulse response

Calling Sequence

[sl]=imrep2ss(v [,deg])

Parameters

  • v : vector coefficients of impulse response, v(:,k) is the kth sample
  • deg : integer (order required)
  • sl : syslin list

Description

Impulse response to linear system conversion (one input). v must have an even number of columns.

Examples

s=poly(0,'s');
H=[1/(s+0.5);2/(s-0.4)]   //strictly proper
np=20;w=ldiv(H('num'),H('den'),np);
rep=[w(1:np)';w(np+1:2*np)'];   //The impulse response
H1=ss2tf(imrep2ss(rep))
z=poly(0,'z');
H=(2*z^2-3.4*z+1.5)/(z^2-1.6*z+0.8)     //Proper transfer function
u=zeros(1,20);u(1)=1;
rep=rtitr(H('num'),H('den'),u);   //Impulse rep.
//   <=> rep=ldiv(H('num'),H('den'),20)
w=z*imrep2ss(rep)   //Realization with shifted impulse response
// i.e strictly proper to proper
H2=ss2tf(w);

See Also

frep2tf , arl2 , time_id , armax , markp2ss , ldiv ,


invsyslin

Scilab Function
Last update : 12/01/2004

invsyslin - system inversion

Calling Sequence

[sl2]=invsyslin(sl1)

Parameters

  • sl1,sl2 : syslin lists (linear systems in state space representation)

Description

Utility function. Computes the state form of the inverse sl2 of the linear system sl1 (which is also given in state form).

The D -matrix is supposed to be full rank. Old stuff used by inv(S) when S is a syslin list.

See Also

rowregul , inv ,


kpure

Scilab Function
Last update : 12/01/2004

kpure - continuous SISO system limit feedback gain

Calling Sequence

g=kpure(sys)

Parameters

  • sys : SISO linear system (syslin)
  • g : constant

Description

kpure(sys) computes the gains g such that the system sys feedback by g ( sys/.g ) has poles on imaginary axis.

Examples

s=poly(0,'s');
h=syslin('c',(s-1)/(1+5*s+s^2+s^3))
xbasc();evans(h)
g=kpure(h)
hf=h/.g(1)
roots(denom(hf))

See Also

evans , krac2 ,


krac2

Scilab Function
Last update : 12/01/2004

krac2 - continuous SISO system limit feedback gain

Calling Sequence

g=krac2(sys)

Parameters

  • sys : SISO linear system (syslin)
  • g : constant

Description

krac2(sys) computes the gains g such that the system sys fedback by g ( sys/.g ) has 2 real equal poles.

Examples

h=syslin('c',352*poly(-5,'s')/poly([0,0,2000,200,25,1],'s','c'));
xbasc();evans(h,100)
g=krac2(h)
hf1=h/.g(1);roots(denom(hf1))
hf2=h/.g(2);roots(denom(hf2))

See Also

evans , kpure ,


linmeq

Scilab Function
Last update : 12/01/2004

linmeq - Sylvester and Lyapunov equations solver

Calling Sequence

[X(,sep)] = linmeq(task,A,(B,)C,flag,trans(,schur))

Parameters

  • task : integer option to determine the equation type:
    • =1 : solve the Sylvester equation (1a) or (1b);
    • =2 : solve the Lyapunov equation (2a) or (2b);
    • =3 : solve for the Cholesky factor op(X) the Lyapunov equation (3a) or (3b).
  • A : real matrix
  • B : real matrix
  • C : real matrix
  • flag : (optional) integer vector of length 3 or 2 containing options.
    • task = 1 : flag has length 3
      • flag(1) = 0 : solve the continuous-time equation (1a); otherwise, solve the discrete-time equation (1b).
      • flag(2) = 1 : A is (quasi) upper triangular;
      • flag(2) = 2 : A is upper Hessenberg;
      • otherwise A is in general form.
      • flag(3) = 1 : B is (quasi) upper triangular;
      • flag(3) = 2 : B is upper Hessenberg;
      • otherwise, B is in general form.
    • task = 2 : flag has length 2
      • flag(1) : if 0 solve continuous-time equation (2a), otherwise, solve discrete-time equation (2b).
      • flag(2) = 1 : A is (quasi) upper triangular otherwise, A is in general form.
    • task = 3 : flag has length 2
      • flag(1) = 0 : solve continuous-time equation (3a); otherwise, solve discrete-time equation (3b).
      • flag(2) = 1 : A is (quasi) upper triangular; otherwise, A is in general form.

    Default: flag(1) = 0, flag(2) = 0 (, flag(3) = 0).

  • trans : (optional) integer specifying a transposition option.
    • = 0 : solve the equations (1) - (3) with op(M) = M.
    • = 1 : solve the equations (1) - (3) with op(M) = M'.
    • = 2 : solve the equations (1) with op(A) = A'; op(B) = B;
    • = 3 : solve the equations (1) with op(A) = A; op(B) = B'.

    Default: trans = 0.

  • schur : (optional) integer specifying whether the Hessenberg-Schur or Schur method should be used. Available for task = 1.
    • = 1 : Hessenberg-Schur method (one matrix is reduced to Schur form).
    • = 2 : Schur method (two matrices are reduced to Schur form).

    Default: schur = 1.

  • X :
  • sep : (optional) estimator of Sep(op(A),-op(A)') for (2.a) or Sepd(A,A') for (2.b).

Description

linmeq function for solving Sylvester and Lyapunov equations using SLICOT routines SB04MD, SB04ND, SB04PD, SB04QD, SB04RD, SB03MD, and SB03OD.

       [X] = linmeq(1,A,B,C,flag,trans,schur)
   [X,sep] = linmeq(2,A,C,flag,trans)
       [X] = linmeq(2,A,C,flag,trans)
       [X] = linmeq(3,A,C,flag,trans)

linmeq solves various Sylvester and Lyapunov matrix equations:

        op(A)*X + X*op(B) = C,                           (1a)

        op(A)*X*op(B) + X = C,                           (1b)

        op(A)'*X + X*op(A) = C,                          (2a)

        op(A)'*X*op(A) - X = C,                          (2b)

        op(A)'*(op(X)'*op(X)) + (op(X)'*op(X))*op(A) =
                              -  op(C)'*op(C),           (3a)

        op(A)'*(op(X)'*op(X))*op(A) - op(X)'*op(X) =
                                    - op(C)'*op(C),      (3b)

where op(M) = M, or M'.

Comments

  • 1. For equation (1a) or (1b), when schur = 1, the Hessenberg-Schur method is used, reducing one matrix to Hessenberg form and the other one to a real Schur form. Otherwise, both matrices are reduced to real Schur forms. If one or both matrices are already reduced to Schur/Hessenberg forms, this could be specified by flag(2) and flag(3). For general matrices, the Hessenberg-Schur method could be significantly more efficient than the Schur method.
  • 2. For equation (2a) or (2b), matrix C is assumed symmetric.
  • 3. For equation (3a) or (3b), matrix A must be stable or convergent, respectively.
  • 4. For equation (3a) or (3b), the computed matrix X is the Cholesky factor of the solution, i.e., the real solution is op(X)'*op(X), where X is an upper triangular matrix.

    • Revisions

    V. Sima, Katholieke Univ. Leuven, Belgium, May 1999, May, Sep. 2000. V. Sima, University of Bucharest, Romania, May 2000.

    Examples

//(1a)
n=40;m=30;
A=rand(n,n);C=rand(n,m);B=rand(m,m);
X = linmeq(1,A,B,C);
norm(A*X+X*B-C,1)
//(1b)
flag=[1,0,0]
X = linmeq(1,A,B,C,flag);
norm(A*X*B+X-C,1)
//(2a)
A=rand(n,n);C=rand(A);C=C+C';
X = linmeq(2,A,C);
norm(A'*X + X*A -C,1)
//(2b)
X = linmeq(2,A,C,[1 0]);
norm(A'*X*A -X-C,1)
//(3a)
A=rand(n,n);
A=A-(max(real(spec(A)))+1)*eye(); //shift eigenvalues
C=rand(A);
X=linmeq(3,A,C);
norm(A'*X'*X+X'*X*A +C'*C,1)
//(3b)
A = [-0.02, 0.02,-0.10, 0.02,-0.03, 0.12;
      0.02, 0.14, 0.12,-0.10,-0.02,-0.14;
     -0.10, 0.12, 0.05, 0.03,-0.04,-0.04;
      0.02,-0.10, 0.03,-0.06, 0.08, 0.11;
     -0.03,-0.02,-0.04, 0.08, 0.14,-0.07;
      0.12,-0.14,-0.04, 0.11,-0.07, 0.04]

C=rand(A);
X=linmeq(3,A,C,[1 0]);
norm(A'*X'*X*A - X'*X +C'*C,1)

    See Also

    sylv , lyap ,

    Author

    H. Xu, TU Chemnitz, FR Germany, Dec. 1998.


lin

Scilab Function
Last update : 12/01/2004

lin - linearization

Calling Sequence

[A,B,C,D]=lin(sim,x0,u0)
[sl]=lin(sim,x0,u0)

Parameters

  • sim : function
  • x0, u0 : vectors of compatible dimensions
  • A,B,C,D : real matrices
  • sl : syslin list

Description

linearization of the non-linear system [y,xdot]=sim(x,u) around x0,u0 .

sim is a function which computes y and xdot .

The output is a linear system ( syslin list) sl or the four matrices (A,B,C,D)

For example, if ftz is the function passed to ode e.g.

[zd]=ftz(t,z,u)

and if we assume that y=x

[z]=ode(x0,t0,tf,list(ftz,u) compute x(tf) .

If simula is the following function:

deff('[y,xd]=simula(x,u)','xd=ftz(tf,x,u); y=x;');

the tangent linear system sl can be obtained by:

[A,B,C,D]=lin(simula,z,u)
sl = syslin('c',A,B,C,D,x0)

Examples

deff('[y,xdot]=sim(x,u)','xdot=[u*sin(x);-u*x^2];y=xdot(1)+xdot(2)')
sl=lin(sim,1,2);

See Also

external , derivat ,


lqe

Scilab Function
Last update : 12/01/2004

lqe - linear quadratic estimator (Kalman Filter)

Calling Sequence

[K,X]=lqe(P21)

Parameters

  • P21 : syslin list
  • K, X : real matrices

Description

lqe returns the Kalman gain for the filtering problem in continuous or discrete time.

P21 is a syslin list representing the system P21=[A,B1,C2,D21]

The input to P21 is a white noise with variance:

     [B1 ]               [Q  S]
BigV=[   ] [ B1' D21'] = [    ]
     [D21]               [S' R]

X is the solution of the stabilizing Riccati equation and A+K*C2 is stable.

In continuous time:

(A-S*inv(R)*C2)*X+X*(A-S*inv(R)*C2)'-X*C2'*inv(R)*C2*X+Q-S*inv(R)*S'=0

K=-(X*C2'+S)*inv(R)

In discrete time:

X=A*X*A'-(A*X*C2'+B1*D21')*pinv(C2*X*C2'+D21*D21')*(C2*X*A'+D21*B1')+B1*B1'

K=-(A*X*C2'+B1*D21')*pinv(C2*X*C2'+D21*D21')

xhat(t+1)= E(x(t+1)| y(0),...,y(t)) (one-step predicted x ) satisfies the recursion:

xhat(t+1)=(A+K*C2)*xhat(t) - K*y(t).

See Also

lqr ,

Author

F. D.


lqg2stan

Scilab Function
Last update : 12/01/2004

lqg2stan - LQG to standard problem

Calling Sequence

[P,r]=lqg2stan(P22,bigQ,bigR)

Parameters

  • P22 : syslin list (nominal plant) in state-space form
  • bigQ : [Q,S;S',N] (symmetric) weighting matrix
  • bigR : [R,T;T',V] (symmetric) covariance matrix
  • r : 1 x 2 row vector = (number of measurements, number of inputs) (dimension of the 2,2 part of P )
  • P : syslin list (augmented plant)

Description

lqg2stan returns the augmented plant for linear LQG (H2) controller design.

P22=syslin(dom,A,B2,C2) is the nominal plant; it can be in continuous time ( dom='c' ) or discrete time ( dom='d' ).

  .
  x = Ax + w1 + B2u
  y = C2x + w2

for continuous time plant.

  x[n+1]= Ax[n] + w1 + B2u
      y = C2x + w2

for discrete time plant.

The (instantaneous) cost function is [x' u'] bigQ [x;u] .

The covariance of [w1;w2] is E[w1;w2] [w1',w2'] = bigR

If [B1;D21] is a factor of bigQ , [C1,D12] is a factor of bigR and [A,B2,C2,D22] is a realization of P22, then P is a realization of [A,[B1,B2],[C1,-C2],[0,D12;D21,D22] . The (negative) feedback computed by lqg stabilizes P22 , i.e. the poles of cl=P22/.K are stable.

Examples

ny=2;nu=3;nx=4;
P22=ssrand(ny,nu,nx);
bigQ=rand(nx+nu,nx+nu);bigQ=bigQ*bigQ';
bigR=rand(nx+ny,nx+ny);bigR=bigR*bigR';
[P,r]=lqg2stan(P22,bigQ,bigR);K=lqg(P,r);  //K=LQG-controller
spec(h_cl(P,r,K))      //Closed loop should be stable
//Same as Cl=P22/.K; spec(Cl('A'))
s=poly(0,'s')
lqg2stan(1/(s+2),eye(2,2),eye(2,2))

See Also

lqg , lqr , lqe , obscont , h_inf , augment , fstabst , feedback ,

Author

F.D.


lqg

Scilab Function
Last update : 12/01/2004

lqg - LQG compensator

Calling Sequence

[K]=lqg(P,r)

Parameters

  • P : syslin list (augmented plant) in state-space form
  • r : 1x2 row vector = (number of measurements, number of inputs) (dimension of the 2,2 part of P )
  • K : syslin list (controller)

Description

lqg computes the linear optimal LQG (H2) controller for the "augmented" plant P=syslin('c',A,B,C,D) (continuous time) or P=syslin('d',A,B,C,D) (discrete time).

The function lqg2stan returns P and r given the nominal plant, weighting terms and variances of noises.

K is given by the following ABCD matrices: [A+B*Kc+Kf*C+Kf*D*Kc,-Kf,Kc,0] where Kc=lqr(P12) is the controller gain and Kf=lqe(P21) is the filter gain. See example in lqg2stan .

See Also

lqg2stan , lqr , lqe , h_inf , obscont ,

Author

F.D.


lqr

Scilab Function
Last update : 12/01/2004

lqr - LQ compensator (full state)

Calling Sequence

[K,X]=lqr(P12)

Parameters

  • P12 : syslin list (state-space linear system)
  • K,X : two real matrices

Description

lqr computes the linear optimal LQ full-state gain for the plant P12=[A,B2,C1,D12] in continuous or discrete time.

P12 is a syslin list (e.g. P12=syslin('c',A,B2,C1,D12) ).

The cost function is l2-norm of z'*z with z=C1 x + D12 u i.e. [x,u]' * BigQ * [x;u] where

      [C1' ]               [Q  S]
BigQ= [    ]  * [C1 D12] = [    ]
      [D12']               [S' R]

The gain K is such that A + B2*K is stable.

X is the stabilizing solution of the Riccati equation.

For a continuous plant:

(A-B2*inv(R)*S')'*X+X*(A-B2*inv(R)*S')-X*B2*inv(R)*B2'*X+Q-S*inv(R)*S'=0

K=-inv(R)*(B2'*X+S)

For a discrete plant:

X=A'*X*A-(A'*X*B2+C1'*D12)*pinv(B2'*X*B2+D12'*D12)*(B2'*X*A+D12'*C1)+C1'*C1;

K=-pinv(B2'*X*B2+D12'*D12)*(B2'*X*A+D12'*C1)

An equivalent form for X is

X=Abar'*inv(inv(X)+B2*inv(r)*B2')*Abar+Qbar

with Abar=A-B2*inv(R)*S' and Qbar=Q-S*inv(R)*S'

The 3-blocks matrix pencils associated with these Riccati equations are:

               discrete                           continuous
   |I   0    0|   | A    0    B2|         |I   0   0|   | A    0    B2|
  z|0   A'   0| - |-Q    I    -S|        s|0   I   0| - |-Q   -A'   -S|
   |0   B2'  0|   | S'   0     R|         |0   0   0|   | S'  -B2'   R|

Caution: It is assumed that matrix R is non singular. In particular, the plant must be tall (number of outputs >= number of inputs).

Examples

A=rand(2,2);B=rand(2,1);   //two states, one input
Q=diag([2,5]);R=2;     //Usual notations x'Qx + u'Ru
Big=sysdiag(Q,R);    //Now we calculate C1 and D12
[w,wp]=fullrf(Big);C1=wp(:,1:2);D12=wp(:,3:$);   //[C1,D12]'*[C1,D12]=Big
P=syslin('c',A,B,C1,D12);    //The plant (continuous-time)
[K,X]=lqr(P)
spec(A+B*K)    //check stability
norm(A'*X+X*A-X*B*inv(R)*B'*X+Q,1)  //Riccati check
P=syslin('d',A,B,C1,D12);    // Discrete time plant
[K,X]=lqr(P)
spec(A+B*K)   //check stability
norm(A'*X*A-(A'*X*B)*pinv(B'*X*B+R)*(B'*X*A)+Q-X,1) //Riccati check

See Also

lqe , gcare , leqr ,

Author

F.D.;


ltitr

Scilab Function
Last update : 12/01/2004

ltitr - discrete time response (state space)

Calling Sequence

[X]=ltitr(A,B,U,[x0])
[xf,X]=ltitr(A,B,U,[x0])

Parameters

  • A,B : real matrices of appropriate dimensions
  • U,X : real matrices
  • x0,xf : real vectors (default value=0 for x0 ))

Description

calculates the time response of the discrete time system

         x[t+1] = Ax[t] + Bu[t].

The inputs ui 's are the columns of the U matrix

        U=[u0,u1,...,un];

x0 is the vector of initial state (default value : 0) ;

X is the matrix of outputs (same number of columns as U ).

        X=[x0,x1,x2,...,xn]

xf is the vector of final state xf=X[n+1]

Examples

A=eye(2,2);B=[1;1];
x0=[-1;-2];
u=[1,2,3,4,5];
x=ltitr(A,B,u,x0)
x1=A*x0+B*u(1)
x2=A*x1+B*u(2)
x3=A*x2+B*u(3) //....

See Also

rtitr , flts ,


markp2ss

Scilab Function
Last update : 12/01/2004

markp2ss - Markov parameters to state-space

Calling Sequence

[sl]=markp2ss(markpar,n,nout,nin)

Parameters

  • markpar : matrix
  • n,nout,nin : integers
  • Sl : syslin list

Description

given a set of n Markov parameters stacked in the (row)-matrix markpar of size nout X (n*nin) markp2ss returns a state-space linear system sl ( syslin list) such that with [A,B,C,D]=abcd(sl) :

   C*B = markpar(1:nout,1:nin),
   C*A*B =markpar(1:nout,nin+1:2*nin),....

Examples

W=ssrand(2,3,4);   //random system with 2 outputs and 3 inputs
[a,b,c,d]=abcd(W);
markpar=[c*b,c*a*b,c*a^2*b,c*a^3*b,c*a^4*b];
S=markp2ss(markpar,5,2,3);
[A,B,C,D]=abcd(S);
Markpar=[C*B,C*A*B,C*A^2*B,C*A^3*B,C*A^4*B];
norm(markpar-Markpar,1)
//Caution... c*a^5*b is not C*A^5*B !

See Also

frep2tf , tf2ss , imrep2ss ,


minreal

Scilab Function
Last update : 12/01/2004

minreal - minimal balanced realization

Calling Sequence

slb=minreal(sl [,tol])

Parameters

  • sl,slb : syslin lists
  • tol : real (threshold)

Description

[ae,be,ce]=minreal(a,b,c,domain [,tol]) returns the balanced realization of linear system sl ( syslin list).

sl is assumed stable.

tol threshold used in equil1 .

Examples

A=[-eye(2,2),rand(2,2);zeros(2,2),-2*eye(2,2)];
B=[rand(2,2);zeros(2,2)];C=rand(2,4);
sl=syslin('c',A,B,C);
slb=minreal(sl);
ss2tf(sl)
ss2tf(slb)
ctr_gram(sl)
clean(ctr_gram(slb))
clean(obs_gram(slb))

See Also

minss , balreal , arhnk , equil , equil1 ,

Author

S. Steer INRIA 1987


minss

Scilab Function
Last update : 12/01/2004

minss - minimal realization

Calling Sequence

[slc]=minss( sl [,tol])

Parameters

  • sl,slc : syslin lists (linear systems in state-space form)
  • tol : real (threshold for rank determination (see contr ))

Description

minss returns in slc a minimal realization of sl .

Examples

sl=syslin('c',[1 0;0 2],[1;0],[2 1]);
ssprint(sl);
ssprint(minss(sl))

See Also

contr , minreal , arhnk , contrss , obsvss , balreal ,


obscont

Scilab Function
Last update : 12/01/2004

obscont - observer based controller

Calling Sequence

[K]=obscont(P,Kc,Kf)
[J,r]=obscont(P,Kc,Kf)

Parameters

  • P : syslin list (nominal plant) in state-space form, continuous or discrete time
  • Kc : real matrix, (full state) controller gain
  • Kf : real matrix, filter gain
  • K : syslin list (controller)
  • J : syslin list (extended controller)
  • r : 1x2 row vector

Description

obscont returns the observer-based controller associated with a nominal plant P with matrices [A,B,C,D] ( syslin list).

The full-state control gain is Kc and the filter gain is Kf . These gains can be computed, for example, by pole placement.

A+B*Kc and A+Kf*C are (usually) assumed stable.

K is a state-space representation of the compensator K: y->u in:

xdot = A x + B u, y=C x + D u, zdot= (A + Kf C)z -Kf y +B u, u=Kc z

K is a linear system ( syslin list) with matrices given by: K=[A+B*Kc+Kf*C+Kf*D*Kc,Kf,-Kc] .

The closed loop feedback system Cl: v ->y with (negative) feedback K (i.e. y = P u, u = v - K y , or xdot = A x + B u, y = C x + D u, zdot = (A + Kf C) z - Kf y + B u, u = v -F z ) is given by Cl = P/.(-K)

The poles of Cl ( spec(cl('A')) ) are located at the eigenvalues of A+B*Kc and A+Kf*C .

Invoked with two output arguments obscont returns a (square) linear system K which parametrizes all the stabilizing feedbacks via a LFT.

Let Q an arbitrary stable linear system of dimension r(2) x r(1) i.e. number of inputs x number of outputs in P . Then any stabilizing controller K for P can be expressed as K=lft(J,r,Q) . The controller which corresponds to Q=0 is K=J(1:nu,1:ny) (this K is returned by K=obscont(P,Kc,Kf) ). r is size(P) i.e the vector [number of outputs, number of inputs];

Examples

ny=2;nu=3;nx=4;P=ssrand(ny,nu,nx);[A,B,C,D]=abcd(P);
Kc=-ppol(A,B,[-1,-1,-1,-1]);  //Controller gain
Kf=-ppol(A',C',[-2,-2,-2,-2]);Kf=Kf';    //Observer gain
cl=P/.(-obscont(P,Kc,Kf));spec(cl('A'))   //closed loop system
[J,r]=obscont(P,Kc,Kf);
Q=ssrand(nu,ny,3);Q('A')=Q('A')-(maxi(real(spec(Q('A'))))+0.5)*eye(Q('A'))
//Q is a stable parameter
K=lft(J,r,Q);
spec(h_cl(P,K))  // closed-loop A matrix (should be stable);

See Also

ppol , lqg , lqr , lqe , h_inf , lft , syslin , feedback , observer ,

Author

F.D. ; ;


observer

Scilab Function
Last update : 12/01/2004

observer - observer design

Calling Sequence

Obs=observer(Sys,J)
[Obs,U,m]=observer(Sys [,flag,alfa])

Parameters

  • Sys : syslin list (linear system)
  • J : nx x ny constant matrix (output injection matrix)
  • flag : character strings ( 'pp' or 'st' (default))
  • alfa : location of closed-loop poles (optional parameter, default=-1)
  • Obs : linear system ( syslin list), the observer
  • U : orthogonal matrix (see dt_ility )
  • m : integer (dimension of unstable unobservable ( st ) or unobservable ( pp ) subspace)

Description

Obs=observer(Sys,J) returns the observer Obs=syslin(td,A+J*C,[B+J*D,-J],eye(A)) obtained from Sys by a J output injection. (td is the time domain of Sys ). More generally, observer returns in Obs an observer for the observable part of linear system Sys : dotx=A x + Bu, y=Cx + Du represented by a syslin list. Sys has nx state variables, nu inputs and ny outputs. Obs is a linear system with matrices [Ao,Bo,Identity] , where Ao is no x no , Bo is no x (nu+ny) , Co is no x no and no=nx-m .

Input to Obs is [u,y] and output of Obs is:

xhat=estimate of x modulo unobservable subsp. (case flag='pp' ) or

xhat=estimate of x modulo unstable unobservable subsp. (case flag='st' )

case flag='st' : z=H*x can be estimated with stable observer iff H*U(:,1:m)=0 and assignable poles of the observer are set to alfa(1),alfa(2),...

case flag='pp' : z=H*x can be estimated with given error spectrum iff H*U(:,1:m)=0 all poles of the observer are assigned and set to alfa(1),alfa(2),...

If H satifies the constraint: H*U(:,1:m)=0 (ker(H) contains unobs-subsp. of Sys) one has H*U=[0,H2] and the observer for z=H*x is H2*Obs with H2=H*U(:,m+1:nx) i.e. Co, the C-matrix of the observer for H*x, is Co=H2.

In the particular case where the pair (A,C) of Sys is observable, one has m=0 and the linear system U*Obs (resp. H*U*Obs ) is an observer for x (resp. Hx ). The error spectrum is alpha(1),alpha(2),...,alpha(nx) .

Examples

nx=5;nu=1;ny=1;un=3;us=2;Sys=ssrand(ny,nu,nx,list('dt',us,us,un));
//nx=5 states, nu=1 input, ny=1 output,
//un=3 unobservable states, us=2 of them unstable.
[Obs,U,m]=observer(Sys);  //Stable observer (default)
W=U';H=W(m+1:nx,:);[A,B,C,D]=abcd(Sys);  //H*U=[0,eye(no,no)];
Sys2=ss2tf(syslin('c',A,B,H))  //Transfer u-->z
Idu=eye(nu,nu);Sys3=ss2tf(H*U(:,m+1:$)*Obs*[Idu;Sys])
//Transfer u-->[u;y=Sys*u]-->Obs-->xhat-->HUxhat=zhat  i.e. u-->output of Obs
//this transfer must equal Sys2, the u-->z transfer  (H2=eye).

See Also

dt_ility , unobs , stabil ,

Author

F.D.


obsvss

Scilab Function
Last update : 12/01/2004

obsvss - observable part

Calling Sequence

[Ao,Bo,Co]=obsvss(A,B,C [,tol])
[slo]=obsvss(sl [,tol])

Parameters

  • A,B,C,Ao,Bo,Co : real matrices
  • sl,slo : syslin lists
  • tol : real (threshold) (default value 100*%eps )

Description

slo=(Ao,Bo,Co) is the observable part of linear system sl=(A,B,C) ( syslin list)

tol threshold to test controllability (see contr ); default value = 100*%eps

See Also

contr , contrss , obsv_mat , obs_gram ,


obsv_mat

Scilab Function
Last update : 12/01/2004

obsv_mat - observability matrix

Calling Sequence

[O]=obsv_mat(A,C)
[O]=obsv_mat(sl)

Parameters

  • A,C,O : real matrices
  • sl : syslin list

Description

obsv_mat returns the observability matrix:

O=[C; CA; CA^2;...; CA^(n-1) ]

See Also

contrss , obsvss , obs_gram ,


obs_gram

Scilab Function
Last update : 12/01/2004

obs_gram - observability gramian

Calling Sequence

Go=obs_gram(A,C [,dom])
Go=obs_gram(sl)

Parameters

  • A,C : real matrices (of appropriate dimensions)
  • dom : string ( "d' or "c" (default value))
  • sl : syslin list

Description

Observability gramian of the pair (A,C) or linear system sl ( syslin list). dom is the domain which can be

"c": continuous system (default)
"d": discrete system

Examples

A=-diag(1:3);C=rand(2,3);
Go=obs_gram(A,C,'c');     // <=> w=syslin('c',A,[],C); Go=obs_gram(w);
norm(Go*A+A'*Go+C'*C,1)
norm(lyap(A,-C'*C,'c')-Go,1)
A=A/4; Go=obs_gram(A,C,'d');    //discrete time case
norm(lyap(A,-C'*C,'d')-Go,1)

See Also

ctr_gram , obsvss , obsv_mat , lyap ,


pfss

Scilab Function
Last update : 12/01/2004

pfss - partial fraction decomposition

Calling Sequence

elts=pfss(Sl)
elts=pfss(Sl,rmax)
elts=pfss(Sl,'cord')
elts=pfss(Sl,rmax,'cord')

Parameters

  • Sl syslin list (state-space or transfer linear system) rmax : real number controlling the conditioning of block diagoanalization cord : character string 'c' or 'd' .

Description

Partial fraction decomposition of the linear system Sl (in state-space form, transfer matrices are automatically converted to state-space form by tf2ss ):

elts is the list of linear systems which add up to Sl i.e. elts=list(S1,S2,S3,...,Sn) with:

Sl = S1 + S2 +... +Sn .

Each Si contains some poles of S according to the block-diagonalization of the A matrix of S .

For non proper systems the polynomial part of Sl is put in the last entry of elts .

If Sl is given in transfer form, it is first converted into state-space and each subsystem Si is then converted in transfer form.

The A matrix is of the state-space is put into block diagonal form by function bdiag . The optional parameter rmax is sent to bdiag . If rmax should be set to a large number to enforce block-diagonalization.

If the optional flag cord='c' is given the elements in elts are sorted according to the real part (resp. magnitude if cord='d' ) of the eigenvalues of A matrices.

Examples

W=ssrand(1,1,6);
elts=pfss(W);
W1=0;for k=1:size(elts), W1=W1+ss2tf(elts(k));end
clean(ss2tf(W)-W1)

See Also

pbig , bdiag , coffg , dtsi ,

Author

F.D.;


phasemag

Scilab Function
Last update : 22/12/2005

phasemag - phase and magnitude computation

Calling Sequence

[phi,db]=phasemag(z [,mod])

Parameters

  • z : matrix or row vector of complex numbers.
  • mod : character string
    • mod='c' : "continuous" representation between -infinity and +360 degrees (default)
    • mod='m' : representation between -360 and 0 degrees
  • phi : phases (in degree) of z .
  • db : magnitude (in Db)

Description

phasemag computes the phases and magnitudes of the entries of a complex matrix. For mod='c' phasemag computes phi(:,i+1) to minimize the distance with phi(:,i) , i.e. it tries to obtain a "continuous representation" of the phase.

To obtain the phase between -%pi and %pi use phi=atan(imag(z),real(z))

Examples

s=poly(0,'s');
h=syslin('c',1/((s+5)*(s+10)*(100+6*s+s*s)*(s+.3)));
[frq,rf]=repfreq(h,0.1,20,0.005);
scf();
plot2d(frq',phasemag(rf,'c')');
scf();
plot2d(frq',phasemag(rf,'m')');

See Also

repfreq , gainplot , atan , bode ,


ppol

Scilab Function
Last update : 12/01/2004

ppol - pole placement

Calling Sequence

[K]=ppol(A,B,poles)

Parameters

  • A,B : real matrices of dimensions nxn and nxm .
  • poles : real or complex vector of dimension n .
  • K : real matrix (negative feedback gain)

Description

K=ppol(A,B,poles) returns a mxn gain matrix K such that the eigenvalues of A-B*K are poles . The pair (A,B) must be controllable. Complex number in poles must appear in conjugate pairs.

An output-injection gain F for (A,C) is obtained as follows:

Ft=ppol(A',C',poles); F=Ft'

The algorithm is by P.H. Petkov.

Examples

A=rand(3,3);B=rand(3,2);
F=ppol(A,B,[-1,-2,-3]);
spec(A-B*F)

See Also

canon , stabil ,


projsl

Scilab Function
Last update : 12/01/2004

projsl - linear system projection

Calling Sequence

[slp]=projsl(sl,Q,M)

Parameters

  • sl,slp : syslin lists
  • Q,M : matrices (projection factorization)

Description

slp = projected model of sl where Q*M is the full rank factorization of the projection.

If (A,B,C,D) is the representation of sl , the projected model is given by (M*A*Q,M*B,C*Q,D) .

Usually, the projection Q*M is obtained as the spectral projection of an appropriate auxiliary matrix W e.g. W = product of (weighted) gramians or product of Riccati equations.

Examples

rand('seed',0);sl=ssrand(2,2,5);[A,B,C,D]=abcd(sl);poles=spec(A)
[Q,M]=pbig(A,0,'c');  //keeping unstable poles
slred=projsl(sl,Q,M);spec(slred('A'))
sl('D')=rand(2,2);  //making proper system
trzeros(sl)  //zeros of sl
wi=inv(sl);  //wi=inverse in state-space
[q,m]=psmall(wi('A'),2,'d');  //keeping small zeros (poles of wi) i.e. abs(z)<2
slred2=projsl(sl,q,m);
trzeros(slred2)  //zeros of slred2 = small zeros of sl
//  Example keeping second order modes
A=diag([-1,-2,-3]);
sl=syslin('c',A,rand(3,2),rand(2,3));[nk2,W]=hankelsv(sl)
[Q,M]=pbig(W,nk2(2)-%eps,'c');    //keeping 2 eigenvalues of W
slr=projsl(sl,Q,M);  //reduced model
hankelsv(slr)

See Also

pbig ,

Author

F. D.;


p_margin

Scilab Function
Last update : 12/01/2004

p_margin - phase margin

Calling Sequence

[phm,fr]=p_margin(h)
phm=p_margin(h)

Parameters

  • h : SISO linear system ( syslin list).
  • phm : phase margin (in degree)
  • fr : corresponding frequency (hz)

Description

The phase margin is the values of the phase at points where the nyquist plot of h crosses the unit circle.

Examples

h=syslin('c',-1+%s,3+2*%s+%s^2)
[p,fr]=p_margin(h)
[p,fr]=p_margin(h+0.7)
nyquist(h+0.7)
t=(0:0.1:2*%pi)';plot2d(sin(t),cos(t),-3,'000')

See Also

chart , black , g_margin , nyquist ,

Author

S. S.


repfreq

Scilab Function
Last update : 12/01/2004

repfreq - frequency response

Calling Sequence

[ [frq,] repf]=repfreq(sys,fmin,fmax [,step])
[ [frq,] repf]=repfreq(sys [,frq])
[ frq,repf,splitf]=repfreq(sys,fmin,fmax [,step])
[ frq,repf,splitf]=repfreq(sys [,frq])

Parameters

  • sys : syslin list : SIMO linear system
  • fmin,fmax : two real numbers (lower and upper frequency bounds)
  • frq : real vector of frequencies (Hz)
  • step : logarithmic discretization step
  • splitf : vector of indexes of critical frequencies.
  • repf : vector of the complex frequency response

Description

repfreq returns the frequency response calculation of a linear system. If sys(s) is the transfer function of Sys , repf(k) equals sys(s) evaluated at s= %i*frq(k)*2*%pi for continuous time systems and at exp(2*%i*%pi*dt*frq(k)) for discrete time systems ( dt is the sampling period).

db(k) is the magnitude of repf(k) expressed in dB i.e. db(k)=20*log10(abs(repf(k))) and phi(k) is the phase of repf(k) expressed in degrees.

If fmin,fmax,step are input parameters, the response is calculated for the vector of frequencies frq given by: frq=[10.^((log10(fmin)):step:(log10(fmax))) fmax];

If step is not given, the output parameter frq is calculated by frq=calfrq(sys,fmin,fmax) .

Vector frq is splitted into regular parts with the split vector. frq(splitf(k):splitf(k+1)-1) has no critical frequency. sys has a pole in the range [frq(splitf(k)),frq(splitf(k)+1)] and no poles outside.

Examples

A=diag([-1,-2]);B=[1;1];C=[1,1];
Sys=syslin('c',A,B,C);
frq=0:0.02:5;w=frq*2*%pi; //frq=frequencies in Hz ;w=frequencies in rad/sec;
[frq1,rep] =repfreq(Sys,frq);
[db,phi]=dbphi(rep);
Systf=ss2tf(Sys)    //Transfer function of Sys
x=horner(Systf,w(2)*sqrt(-1))    // x is Systf(s) evaluated at s = i w(2)
rep=20*log(abs(x))/log(10)   //magnitude of x in dB
db(2)    // same as rep
ang=atan(imag(x),real(x));   //in rad.
ang=ang*180/%pi              //in degrees
phi(2)
repf=repfreq(Sys,frq);
repf(2)-x

See Also

bode , freq , calfrq , horner , nyquist , dbphi ,

Author

S. S.


ricc

Scilab Function
Last update : 12/01/2004

ricc - Riccati equation

Calling Sequence

[X,RCOND,FERR]=ricc(A,B,C,"cont""method")
[X,RCOND,FERR]=ricc(F,G,H,"disc","method")

Parameters

  • A,B,C : real matrices of appropriate dimensions
  • F,G,H : real matrices of appropriate dimensions
  • X : real matrix
  • "cont","disc"' : imposed string (flag for continuous or discrete)
  • method : 'schr' or 'sign' for continuous-time systems and 'schr' or 'invf' for discrete-tyme systems

Description

Riccati solver.

Continuous time:

  X=ricc(A,B,C,'cont')

gives a solution to the continuous time ARE

  A'*X+X*A-X*B*X+C=0 .

B and C are assumed to be nonnegative definite. (A,G) is assumed to be stabilizable with G*G' a full rank factorization of B .

(A,H) is assumed to be detectable with H*H' a full rank factorization of C .

Discrete time:

  X=ricc(F,G,H,'disc')

gives a solution to the discrete time ARE

  X=F'*X*F-F'*X*G1*((G2+G1'*X*G1)^-1)*G1'*X*F+H

F is assumed invertible and G = G1*inv(G2)*G1' .

One assumes (F,G1) stabilizable and (C,F) detectable with C'*C full rank factorization of H . Use preferably ric_desc .

C, D are symmetric .It is assumed that the matrices A, C and D are such that the corresponding matrix pencil has N eigenvalues with moduli less than one.

Error bound on the solution and a condition estimate are also provided. It is assumed that the matrices A, C and D are such that the corresponding Hamiltonian matrix has N eigenvalues with negative real parts.

Examples

//Standard formulas to compute Riccati solutions
A=rand(3,3);B=rand(3,2);C=rand(3,3);C=C*C';R=rand(2,2);R=R*R'+eye();
B=B*inv(R)*B';
X=ricc(A,B,C,'cont');
norm(A'*X+X*A-X*B*X+C,1)
H=[A -B;-C -A'];
[T,d]=schur(eye(H),H,'cont');T=T(:,1:d);
X1=T(4:6,:)/T(1:3,:);
norm(X1-X,1)
[T,d]=schur(H,'cont');T=T(:,1:d);
X2=T(4:6,:)/T(1:3,:);
norm(X2-X,1)
//       Discrete time case
F=A;B=rand(3,2);G1=B;G2=R;G=G1/G2*G1';H=C;
X=ricc(F,G,H,'disc');
norm(F'*X*F-(F'*X*G1/(G2+G1'*X*G1))*(G1'*X*F)+H-X)
H1=[eye(3,3) G;zeros(3,3) F'];
H2=[F zeros(3,3);-H eye(3,3)];
[T,d]=schur(H2,H1,'disc');T=T(:,1:d);X1=T(4:6,:)/T(1:3,:);
norm(X1-X,1)
Fi=inv(F);
Hami=[Fi Fi*G;H*Fi F'+H*Fi*G];
[T,d]=schur(Hami,'d');T=T(:,1:d);
Fit=inv(F');
Ham=[F+G*Fit*H -G*Fit;-Fit*H Fit];
[T,d]=schur(Ham,'d');T=T(:,1:d);X2=T(4:6,:)/T(1:3,:);
norm(X2-X,1)

See Also

riccati , ric_desc , schur ,

Author

P. Petkov

Used Function

See SCIDIR/routines/control/riccpack>


rowregul

Scilab Function
Last update : 12/01/2004

rowregul - removing poles and zeros at infinity

Calling Sequence

[Stmp,Ws]=rowregul(Sl,alfa,beta)

Parameters

  • Sl,Stmp : syslin lists
  • alfa,beta : real numbers (new pole and zero positions)

Description

computes a postfilter Ws such that Stmp=Ws*Sl is proper and with full rank D matrix.

Poles at infinity of Sl are moved to alfa ;

Zeros at infinity of Sl are moved to beta ;

Sl is a assumed to be a right invertible linear system ( syslin list) in state-space representation with possibly a polynomial D matrix.

This function is the dual of colregul (see function code).

Examples

s=%s;
w=[1/s,0;s/(s^3+2),2/s];
Sl=tf2ss(w);
[Stmp,Ws]=rowregul(Sl,-1,-2);
Stmp('D')     // D matrix of Stmp
clean(ss2tf(Stmp))

See Also

invsyslin , colregul ,

Author

F. D. , R. N. ;


rtitr

Scilab Function
Last update : 12/01/2004

rtitr - discrete time response (transfer matrix)

Calling Sequence

[y]=rtitr(Num,Den,u [,up,yp])

Parameters

  • Num,Den : polynomial matrices (resp. dimensions : n x m and n x n )
  • u : real matrix (dimension m x (t+1)
  • up,yp : real matrices ( up dimension m x (maxi(degree(Den))) (default values= 0 ) , yp dimension n x (maxi(degree(Den))) )
  • y : real matrix

Description

y=rtitr(Num,Den,u [,up,yp]) returns the time response of the discrete time linear system with transfer matrix Den^-1 Num for the input u , i.e y and u are such that Den y = Num u at t=0,1,...

If d1=maxi(degree(Den)) , and d2=maxi(degree(Num)) the polynomial matrices Den(z) and Num(z) may be written respectively as:

  D(z)= D_0  + D_1  z + ... + D_d1   z^d1
  N(z)= N_0  + N_1  z + ... + N_d2   z^d2

and Den y = Num u is interpreted as the recursion:

  D(0)y(t)+D(1)y(t+1)+...+ D(d1)y(t+d1)= N(0) u(t) +....+ N(d2) u(t+d2)

It is assumed that D(d1) is non singular.

The columns of u are the inputs of the system at t=0,1,...,T:

  u=[u(0) , u(1),...,u(T)]

The outputs at t=0,1,...,T+d1-d2 are the columns of the matrix y :

  y=[y(0), y(1),  .... y(T+d1-d2)]

up and yp define the initial conditions for t < 0 i.e

  up=[u(-d1), ..., u(-1)  ]
  yp=[y(-d1), ...  y(-1)  ]

Depending on the relative values of d1 and d2 , some of the leftmost components of up , yp are ignored. The default values of up and yp are zero: up = 0*ones(m,d1), yp=0*ones(n,d1)

Examples

z=poly(0,'z');
Num=1+z;Den=1+z;u=[1,2,3,4,5];
rtitr(Num,Den,u)-u
//Other examples
//siso
//causal
n1=1;d1=poly([1 1],'z','coeff');       // y(j)=-y(j-1)+u(j-1)
r1=[0 1 0 1 0 1 0 1 0 1 0];
r=rtitr(n1,d1,ones(1,10));norm(r1-r,1)
//hot restart
r=rtitr(n1,d1,ones(1,9),1,0);norm(r1(2:11)-r)
//non causal
n2=poly([1 1 1],'z','coeff');d2=d1;    // y(j)=-y(j-1)+u(j-1)+u(j)+u(j+1)
r2=[2 1 2 1 2 1 2 1 2];
r=rtitr(n2,d2,ones(1,10));norm(r-r2,1)
//hot restart
r=rtitr(n2,d2,ones(1,9),1,2);norm(r2(2:9)-r,1)
//
//MIMO example
//causal
d1=d1*diag([1 0.5]);n1=[1 3 1;2 4 1];r1=[5;14]*r1;
r=rtitr(n1,d1,ones(3,10));norm(r1-r,1)
//
r=rtitr(n1,d1,ones(3,9),[1;1;1],[0;0]);
norm(r1(:,2:11)-r,1)
//polynomial n1  (same ex.)
n1(1,1)=poly(1,'z','c');r=rtitr(n1,d1,ones(3,10));norm(r1-r,1)
//
r=rtitr(n1,d1,ones(3,9),[1;1;1],[0;0]);
norm(r1(:,2:11)-r,1)
//non causal
d2=d1;n2=n2*n1;r2=[5;14]*r2;
r=rtitr(n2,d2,ones(3,10));norm(r2-r)
//
r=rtitr(n2,d2,ones(3,9),[1;1;1],[10;28]);
norm(r2(:,2:9)-r,1)
//
//  State-space or transfer
a = [0.21 , 0.63 , 0.56 , 0.23 , 0.31
     0.76 , 0.85 , 0.66 , 0.23 , 0.93
     0 , 0.69 , 0.73 , 0.22 , 0.21
     0.33 , 0.88 , 0.2 , 0.88 , 0.31
     0.67 , 0.07 , 0.54 , 0.65 , 0.36];
b = [0.29 , 0.5 , 0.92
     0.57 , 0.44 , 0.04
     0.48 , 0.27 , 0.48
     0.33 , 0.63 , 0.26
     0.59 , 0.41 , 0.41];
c = [0.28 , 0.78 , 0.11 , 0.15 , 0.84
     0.13 , 0.21 , 0.69 , 0.7 , 0.41];
d = [0.41 , 0.11 , 0.56
     0.88 , 0.2 , 0.59];
s=syslin('d',a,b,c,d);
h=ss2tf(s);num=h('num');den=h('den');den=den(1,1)*eye(2,2);
u=1;u(3,10)=0;r3=flts(u,s);
r=rtitr(num,den,u);norm(r3-r,1)

See Also

ltitr , exp , flts ,


sm2des

Scilab Function
Last update : 12/01/2004

sm2des - system matrix to descriptor

Calling Sequence

[Des]=sm2des(Sm);

Parameters

  • Sm : polynomial matrix (pencil system matrix)
  • Des : descriptor system ( list('des',A,B,C,D,E) )

Description

Utility function: converts the system matrix:

 Sm = [-sE + A   B;
      [    C     D]

to descriptor system Des=list('des',A,B,C,D,E) ).

See Also

ss2des , sm2ss ,


sm2ss

Scilab Function
Last update : 12/01/2004

sm2ss - system matrix to state-space

Calling Sequence

[Sl]=sm2ss(Sm);

Parameters

  • Sm : polynomial matrix (pencil system matrix)
  • Sl : linear system ( syslin list)

Description

Utility function: converts the system matrix:

 Sm = [-sI + A   B;
      [    C     D]

to linear system in state-space representation ( syslin ) list.

See Also

ss2des ,


specfact

Scilab Function
Last update : 12/01/2004

specfact - spectral factor

Calling Sequence

[W0,L]=specfact(A,B,C,D)

Description

Given a spectral density matrix phi(s) :

                 -1                   -1
     R + C*(s*I-A) * B  +  B'*(-s*I-A') * C'  with R=D+D' > 0

specfact computes W0 and L such that W(s)=W0+L*(s*I-A)^-1*B is a spectral factor of of PHI(s) , i.e.

phi(s)=W'(-s)*W(s)

Examples

A=diag([-1,-2]);B=[1;1];C=[1,1];D=1;s=poly(0,'s');
W1=syslin('c',A,B,C,D);
phi=gtild(W1,'c')+W1;
phis=clean(ss2tf(phi))
clean(phis-horner(phis,-s)');   //check this is 0...
[A,B,C,D]=abcd(W1);
[W0,L]=specfact(A,B,C,D);
W=syslin('c',A,B,L,W0)
Ws=ss2tf(W);
horner(Ws,-s)*Ws

See Also

gtild , sfact , fspecg ,

Author

F. D.


ss2des

Scilab Function
Last update : 12/01/2004

ss2des - (polynomial) state-space to descriptor form

Calling Sequence

S=ss2des(Sl)
S=ss2des(Sl,flag)

Parameters

  • Sl : syslin list: proper or improper linear system.
  • flag : character string "withD"
  • S : list

Description

Given the linear system in state-space representation Sl ( syslin list), with a D matrix which is either polynomial or constant, but not zero ss2des returns a descriptor system as list('des',A,B,C,0,E) such that:

Sl=C*(s*E-A)^(-1)*B

If the flag "withD" is given, S=list('des',A,B,C,D,E) with a D matrix of maximal rank.

Examples

s=poly(0,'s');
G=[1/(s+1),s;1+s^2,3*s^3];Sl=tf2ss(G);
S=ss2des(Sl)
S1=ss2des(Sl,"withD")
Des=des2ss(S);Des(5)=clean(Des(5))
Des1=des2ss(S1)

See Also

pol2des , tf2des , des2ss ,

Author

F. D.; ;


ss2ss

Scilab Function
Last update : 12/01/2004

ss2ss - state-space to state-space conversion, feedback, injection

Calling Sequence

[Sl1,right,left]=ss2ss(Sl,T, [F, [G , [flag]]])

Parameters

  • Sl : linear system ( syslin list) in state-space form
  • T : square (non-singular) matrix
  • Sl1, right, left : linear systems (syslin lists) in state-space form
  • F : real matrix (state feedback gain)
  • G : real matrix (output injection gain)

Description

Returns the linear system Sl1=[A1,B1,C1,D1] where A1=inv(T)*A*T, B1=inv(T)*B, C1=C*T, D1=D .

Optional parameters F and G are state feedback and output injection respectively.

For example, Sl1=ss2ss(Sl,T,F) returns Sl1 with:

and right is a non singular linear system such that Sl1=Sl*right .

Sl1*inv(right) is a factorization of Sl .

Sl1=ss2ss(Sl,T,0*F,G) returns Sl1 with:

and left is a non singular linear system such that Sl1=left*Sl ( right=Id if F=0 ).

When both F and G are given, Sl1=left*Sl*right .

-When flag is used and flag=1 an output injection as follows is used and then a feedback is performed, F must be of size (m+p,n)

( x is in R^n , y in R^p, u in R^m ).

right and left have the following property:

  Sl1 =  left*sysdiag(sys,eye(p,p))*right
-When flag is used and flag=2 a feedback ( F must be of size (m,n) ) is performed and then the above output injection is applied. right and left have the following property:

  Sl1 = left*sysdiag(sys*right,eye(p,p)))

Examples

Sl=ssrand(2,2,5); trzeros(Sl)       // zeros are invariant:
Sl1=ss2ss(Sl,rand(5,5),rand(2,5),rand(5,2));
trzeros(Sl1), trzeros(rand(2,2)*Sl1*rand(2,2))
// output injection [ A + GC, (B+GD,-G)]
//                  [   C   , (D   , 0)]
p=1,m=2,n=2; sys=ssrand(p,m,n);

// feedback (m,n)  first and then output injection.

F1=rand(m,n);
G=rand(n,p);
[sys1,right,left]=ss2ss(sys,rand(n,n),F1,G,2);

// Sl1 equiv left*sysdiag(sys*right,eye(p,p)))

res=clean(ss2tf(sys1) - ss2tf(left*sysdiag(sys*right,eye(p,p))))

// output injection then feedback (m+p,n)
F2=rand(p,n); F=[F1;F2];
[sys2,right,left]=ss2ss(sys,rand(n,n),F,G,1);

// Sl1 equiv left*sysdiag(sys,eye(p,p))*right

res=clean(ss2tf(sys2)-ss2tf(left*sysdiag(sys,eye(p,p))*right))

// when F2= 0; sys1 and sys2 are the same
F2=0*rand(p,n);F=[F1;F2];
[sys2,right,left]=ss2ss(sys,rand(n,n),F,G,1);

res=clean(ss2tf(sys2)-ss2tf(sys1))

See Also

projsl , feedback ,


ss2tf

Scilab Function
Last update : 12/01/2004

ss2tf - conversion from state-space to transfer function

Calling Sequence

[h]=ss2tf(sl)
[Ds,NUM,chi]=ss2tf(sl)
[h]=ss2tf(sl,"b")
[Ds,NUM,chi]=ss2tf(sl,"b")
[h]=ss2tf(sl,rmax)
[Ds,NUM,chi]=ss2tf(sl,rmax)

Parameters

  • sl : linear system ( syslin list)
  • h : transfer matrix

Description

Called with three outputs [Ds,NUM,chi]=ss2tf(sl) returns the numerator polynomial matrix NUM , the characteristic polynomial chi and the polynomial part Ds separately i.e.:

h=NUM/chi + Ds

Method:

One uses the characteristic polynomial and det(A+Eij)=det(A)+C(i,j) where C is the adjugate matrix of A .

With rmax or "b" argument uses a block diagonalization of sl.A matrix and applies "Leverrier" algorithm on blocks. If given, rmax controls the conditionning (see bdiag).

Examples

s=poly(0,'s');
h=[1,1/s;1/(s^2+1),s/(s^2-2)]
sl=tf2ss(h);
h=clean(ss2tf(sl))
[Ds,NUM,chi]=ss2tf(sl)

See Also

tf2ss , syslin , nlev , glever ,


stabil

Scilab Function
Last update : 12/01/2004

stabil - stabilization

Calling Sequence

F=stabil(A,B,alfa)
K=stabil(Sys,alfa,beta)

Parameters

  • A : square real matrix ( nx x nx )
  • B : real matrix ( nx x nu )
  • alfa, beta : real or complex vector (in conjugate pairs) or real number.
  • F : real matrix ( nx x nu )
  • Sys : linear system ( syslin list) ( m inputs, p outputs).
  • K : linear system ( p inputs, m outputs)

Description

F=stabil(A,B,alfa) returns a gain matrix F such that A+B*F is stable if pair (A,B) is stabilizable. Assignable poles are set to alfa(1),alfa(2),... . If (A,B) is not stabilizable a warning is given and assignable poles are set to alfa(1),alfa(2),... . If alfa is a number all eigenvalues are set to this alfa (default value is alfa=-1 ).

K=stabil(Sys,alfa,beta) returns K , a compensator for Sys such that (A,B) -controllable eigenvalues are set to alfa and (C,A) -observable eigenvalues are set to beta .

All assignable closed loop poles (which are given by the eigenvalues of Aclosed=h_cl(Sys,K) are set to alfa(i) 's and beta(j) 's.

Examples

// Gain:
Sys=ssrand(0,2,5,list('st',2,3,3));
A=Sys('A');B=Sys('B');F=stabil(A,B);
spec(A) //2 controllable modes 2 unstable uncontrollable modes
//and one stable uncontrollable mode
spec(A+B*F) //the two controllable modes are set to -1.
// Compensator:
Sys=ssrand(3,2,5,list('st',2,3,3)); //3 outputs, 2 inputs, 5 states
//2 controllables modes, 3 controllable or stabilizable modes.
K=stabil(Sys,-2,-3);  //Compensator for Sys.
spec(Sys('A'))
spec(h_cl(Sys,K))   //K Stabilizes what can be stabilized.

See Also

st_ility , contr , ppol ,


st_ility

Scilab Function
Last update : 12/01/2004

st_ility - stabilizability test

Calling Sequence

[ns, [nc, [,U [,Slo] ]]]=st_ility(Sl [,tol])

Parameters

  • Sl : syslin list (linear system)
  • ns : integer (dimension of stabilizable subspace)
  • nc : integer (dimension of controllable subspace nc <= ns )
  • U : basis such that its ns (resp. nc ) first components span the stabilizable (resp. controllable) subspace
  • Slo : a linear system ( syslin list)
  • tol : threshold for controllability detection (see contr)

Description

Slo=( U'*A*U, U'*B, C*U, D, U'*x0 ) ( syslin list) displays the stabilizable form of Sl . Stabilizability means ns=nx (dim. of A matrix).

         [*,*,*]            [*]
U'*A*U = [0,*,*]     U'*B = [0]
         [0,0,*]            [0]

where (A11,B1) (dim(A11)= nc ) is controllable and A22 (dim(A22)= ns-nc ) is stable. "Stable" means real part of eigenvalues negative for a continuous linear system, and magnitude of eigenvalues lower than one for a discrete-time system (as defined by syslin ).

Examples

A=diag([0.9,-2,3]);B=[0;0;1];Sl=syslin('c',A,B,[]);
[ns,nc,U]=st_ility(Sl);
U'*A*U
U'*B
[ns,nc,U]=st_ility(syslin('d',A,B,[]));
U'*A*U
U'*B

See Also

dt_ility , contr , stabil , ssrand ,

Author

S. Steer INRIA 1988


svplot

Scilab Function
Last update : 25/05/2004

svplot - singular-value sigma-plot

Calling Sequence

[SVM]=svplot(sl,[w])

Parameters

  • sl : syslin list (continuous, discrete or sampled system)
  • w : real vector (optional parameter)

Description

computes for the system sl=(A,B,C,D) the singular values of its transfer function matrix:

             G(jw) = C(jw*I-A)B^-1+D
or
             G(exp(jw)) = C(exp(jw)*I-A)B^-1+D
or
             G(exp(jwT)) = C(exp(jw*T)*I-A)B^-1+D

evaluated over the frequency range specified by w . (T is the sampling period, T=sl('dt') for sampled systems).

sl is a syslin list representing the system [A,B,C,D] in state-space form. sl can be continous or discrete time or sampled system.

The i -th column of the output matrix SVM contains the singular values of G for the i -th frequency value w(i) .

SVM = svplot(sl)

is equivalent to

SVM = svplot(sl,logspace(-3,3))  (continuous)

SVM = svplot(sl,logspace(-3,%pi)) (discrete)

Examples

x=logspace(-3,3);
y=svplot(ssrand(2,2,4),x);
xbasc();plot2d1("oln",x',20*log(y')/log(10));
xgrid(12)
xtitle("Singular values plot","(Rd/sec)", "Db");

Author

F.D; ;


sysfact

Scilab Function
Last update : 12/01/2004

sysfact - system factorization

Calling Sequence

[S,Series]=sysfact(Sys,Gain,flag)

Parameters

  • Sys : syslin list containing the matrices [A,B,C,D] .
  • Gain : real matrix
  • flag : string 'post' or 'pre'
  • S : syslin list
  • Series : syslin list

Description

If flag equals 'post' , sysfact returns in S the linear system with ABCD matrices (A+B*Gain, B , Gain, I) , and Series , a minimal realization of the series system Sys*S . If flag equals 'pre' , sysfact returns the linear system (A+Gain*C, Gain , C, I) and Series , a minimal realization of the series system S*Sys .

Examples

//Kalman filter
Sys=ssrand(3,2,4);Sys('D')=rand(3,2);
S=sysfact(Sys,lqr(Sys),'post');
ww=minss(Sys*S);
ss2tf(gtild(ww)*ww),Sys('D')'*Sys('D')
//Kernel
Sys=ssrand(2,3,4);
[X,d,F,U,k,Z]=abinv(Sys);
ss2tf(Sys*Z)
ss2tf(Sys*sysfact(Sys,F,'post')*U)

See Also

lqr , lqe ,

Author

F.D.


syssize

Scilab Function
Last update : 12/01/2004

syssize - size of state-space system

Calling Sequence

[r,nx]=syssize(Sl)

Parameters

  • Sl : linear system ( syslin list) in state-space
  • r : 1 x 2 real vector
  • nx : integer

Description

returns in r the vector [number of outputs, number of inputs] of the linear system Sl . nx is the number of states of Sl .

See Also

size ,


tf2ss

Scilab Function
Last update : 12/01/2004

tf2ss - transfer to state-space

Calling Sequence

sl=tf2ss(h [,tol])

Parameters

  • h : rational matrix
  • tol : may be the constant rtol or the 2 vector [rtol atol]
    • rtol :tolerance used when evaluating observability.
    • atol :absolute tolerance used when evaluating observability.
  • sl : linear system ( syslin list sl=[A,B,C,D(s)] )

Description

transfer to state-space conversion:

h=C*(s*eye()-A)^-1*B+D(s)

Examples

s=poly(0,'s');
H=[2/s,(s+1)/(s^2-5)];
Sys=tf2ss(H)
clean(ss2tf(Sys))

See Also

ss2tf , tf2des , des2tf ,


time_id

Scilab Function
Last update : 12/01/2004

time_id - SISO least square identification

Calling Sequence

[H [,err]]=time_id(n,u,y)

Parameters

  • n : order of transfer
  • u : one of the following
    • u1 : a vector of inputs to the system
    • "impuls" : if y is an impulse response
    • "step" : if y is a step response.
  • y : vector of response.
  • H : rational function with degree n denominator and degree n-1 numerator if y(1)==0 or rational function with degree n denominator and numerator if y(1)<>0.
  • err : ||y - impuls(H,npt)||^2 , where impuls(H,npt) are the npt first coefficients of impulse response of H

Description

Identification of discrete time response. If y is strictly proper ( y(1)=0 ) then time_id computes the least square solution of the linear equation: Den*y-Num*u=0 with the constraint coeff(Den,n):=1 . if y(1)~=0 then the algorithm first computes the proper part solution and then add y(1) to the solution

Examples

z=poly(0,'z');
h=(1-2*z)/(z^2-0.5*z+5)
rep=[0;ldiv(h('num'),h('den'),20)]; //impulse response
H=time_id(2,'impuls',rep)
//  Same example with flts and u
u=zeros(1,20);u(1)=1;
rep=flts(u,tf2ss(h));        //impulse response
H=time_id(2,u,rep)
//  step response
u=ones(1,20);
rep=flts(u,tf2ss(h));     //step response.
H=time_id(2,'step',rep)
H=time_id(3,u,rep)    //with u as input and too high order required

See Also

imrep2ss , arl2 , armax , frep2tf ,

Author

Serge Steer INRIA


trzeros

Scilab Function
Last update : 12/01/2004

trzeros - transmission zeros and normal rank

Calling Sequence

[tr]=trzeros(Sl)
[nt,dt,rk]=trzeros(Sl)

Parameters

  • Sl : linear system ( syslin list)
  • nt : complex vectors
  • dt : real vector
  • rk : integer (normal rank of Sl)

Description

Called with one output argument, trzeros(Sl) returns the transmission zeros of the linear system Sl .

Sl may have a polynomial (but square) D matrix.

Called with 2 output arguments, trzeros returns the transmission zeros of the linear system Sl as tr=nt./dt ;

(Note that some components of dt may be zeros)

Called with 3 output arguments, rk is the normal rank of Sl

Transfer matrices are converted to state-space.

If Sl is a (square) polynomial matrix trzeros returns the roots of its determinant.

For usual state-space system trzeros uses the state-space algorithm of Emami-Naeni & Van Dooren.

If D is invertible the transmission zeros are the eigenvalues of the " A matrix" of the inverse system : A - B*inv(D)*C ;

If C*B is invertible the transmission zeros are the eigenvalues of N*A*M where M*N is a full rank factorization of eye(A)-B*inv(C*B)*C ;

For systems with a polynomial D matrix zeros are calculated as the roots of the determinant of the system matrix.

Caution: the computed zeros are not always reliable, in particular in case of repeated zeros.

Examples

W1=ssrand(2,2,5);trzeros(W1)    //call trzeros
roots(det(systmat(W1)))         //roots of det(system matrix)
s=poly(0,'s');W=[1/(s+1);1/(s-2)];W2=(s-3)*W*W';[nt,dt,rk]=trzeros(W2);
St=systmat(tf2ss(W2));[Q,Z,Qd,Zd,numbeps,numbeta]=kroneck(St);
St1=Q*St*Z;rowf=(Qd(1)+Qd(2)+1):(Qd(1)+Qd(2)+Qd(3));
colf=(Zd(1)+Zd(2)+1):(Zd(1)+Zd(2)+Zd(3));
roots(St1(rowf,colf)), nt./dt     //By Kronecker form

See Also

gspec , kroneck ,


ui_observer

Scilab Function
Last update : 12/01/2004

ui_observer - unknown input observer

Calling Sequence

[UIobs,J,N]=ui_observer(Sys,reject,C1,D1)
[UIobs,J,N]=ui_observer(Sys,reject,C1,D1,flag,alfa,beta)

Parameters

  • Sys : syslin list containing the matrices (A,B,C2,D2) .
  • reject : integer vector, indices of inputs of Sys which are unknown.
  • C1 : real matrix
  • D1 : real matrix. C1 and D1 have the same number of rows.
  • flag : string 'ge' or 'st' (default) or 'pp' .
  • alfa : real or complex vector (loc. of closed loop poles)
  • beta : real or complex vector (loc. of closed loop poles)

Description

Unknown input observer.

Sys: (w,u) --> y is a (A,B,C2,D2) syslin linear system with two inputs w and u, w being the unknown input. The matrices B and D2 of Sys are (implicitly) partitioned as: B=[B1,B2] and D2=[D21,D22] with B1=B(:,reject) and D21=D2(:,reject) where reject = indices of unknown inputs. The matrices C1 and D1 define z = C1 x + D1 (w,u) , the to-be-estimated output.

The matrix D1 is (implicitly) partitioned as D1=[D11,D12] with D11=D(:,reject)

The data (Sys, reject,C1, D1) define a 2-input 2-output system:

  xdot =  A x + B1  w + B2  u
     z = C1 x + D11 w + D12 u
     y = C2 x + D21 w + D22 u

An observer (u,y) --> zhat is looked for the output z.

flag='ge' no stability constraints flag='st' stable observer (default) flag='pp' observer with pole placement alfa,beta = desired location of closed loop poles (default -1, -2) J=y-output to x-state injection. N=y-output to z-estimated output injection.

UIobs = linear system (u,y) --> zhat such that: The transfer function: (w,u) --> z equals the composed transfer function: [0,I; UIobs Sys] (w,u) -----> (u,y) -----> zhat i.e. transfer function of system {A,B,C1,D1} equals transfer function UIobs*[0,I; Sys]

Stability (resp. pole placement) requires detectability (resp. observability) of (A,C2).

Examples

A=diag([3,-3,7,4,-4,8]);
B=[eye(3,3);zeros(3,3)];
C=[0,0,1,2,3,4;0,0,0,0,0,1];
D=[1,2,3;0,0,0];
rand('seed',0);w=ss2ss(syslin('c',A,B,C,D),rand(6,6));
[A,B,C,D]=abcd(w);
B=[B,matrix(1:18,6,3)];D=[D,matrix(-(1:6),2,3)];
reject=1:3;
Sys=syslin('c',A,B,C,D);
N1=[-2,-3];C1=-N1*C;D1=-N1*D;
nw=length(reject);nu=size(Sys('B'),2)-nw;
ny=size(Sys('C'),1);nz=size(C1,1);
[UIobs,J,N]=ui_observer(Sys,reject,C1,D1);

W=[zeros(nu,nw),eye(nu,nu);Sys];UIobsW=UIobs*W;
//(w,u) --> z=UIobs*[0,I;Sys](w,u)
clean(ss2tf(UIobsW));
wu_to_z=syslin('c',A,B,C1,D1);clean(ss2tf(wu_to_z));
clean(ss2tf(wu_to_z)-ss2tf(UIobsW),1.d-7)
/////2nd example//////
nx=2;ny=3;nwu=2;Sys=ssrand(ny,nwu,nx);
C1=rand(1,nx);D1=[0,1];
UIobs=ui_observer(Sys,1,C1,D1);

See Also

cainv , ddp , abinv ,

Author

F.D.


unobs

Scilab Function
Last update : 12/01/2004

unobs - unobservable subspace

Calling Sequence

[n,[U]]=unobs(A,C,[tol])

Parameters

  • A, C : real matrices
  • tol : tolerance used when evaluating ranks (QR factorizations).
  • n : dimension of unobservable subspace.
  • U : orthogonal change of basis which puts (A,B) in canonical form.

Description

[n,[U]]=unobs(A,C,[tol]) gives the unobservable form of an (A,C) pair. The n first columns of U make a basis for the unobservable subspace.

The (2,1) block (made of last nx-n rows and n first columns) of U'*A*U is zero and and the n first columns of C*U are zero.

Examples

A=diag([1,2,3]);C=[1,0,0];
unobs(A,C)

See Also

contr , contrss , canon , cont_mat , spantwo , dt_ility ,


zeropen

Scilab Function
Last update : 12/01/2004

zeropen - zero pencil

Calling Sequence

[Z,U]=zeropen(Sl)

Parameters

  • Sl : a linear system ( syslin list in state-space form [A,B,C,D] )
  • Z : matrix pencil Z=s*E-A
  • U : square orthogonal matrix

Description

Z = sE - F is the zero pencil of the linear system Sl with matrices [A,B,C,D] . Utility function.

With U row compression of [B;D] i.e, U*[B;D]=[0;*] ; one has:

U*[-sI+A |B;   [ Z |0;
      C  |D] = [ * |*]

The zeros of Z are the zeros of Sl .

See Also

systmat , kroneck ,


Contrôle robuste
augment - augmented plant
bstap - hankel approximant
ccontrg - central H-infinity controller
colinout - inner-outer factorization
copfac - right coprime factorization
dcf - double coprime factorization
des2ss - descriptor to state-space
dhinf - H_infinity design of discrete-time systems
dhnorm - discrete H-infinity norm
dtsi - stable anti-stable decomposition
fourplan - augmented plant to four plants
fspecg - stable factorization
fstabst - Youla's parametrization
gamitg - H-infinity gamma iterations
gcare - control Riccati equation
gfare - filter Riccati equation
gtild - tilde operation
h2norm - H2 norm
h_cl - closed loop matrix
h_inf - H-infinity (central) controller
h_inf_st - static H_infinity problem
h_norm - H-infinity norm
hankelsv - Hankel singular values
hinf - H_infinity design of continuous-time systems
lcf - normalized coprime factorization
leqr - H-infinity LQ gain (full state)
lft - linear fractional transformation
linf - infinity norm
linfn - infinity norm
lqg_ltr - LQG with loop transform recovery
macglov - Mac Farlane Glover problem
mucomp - mu (structured singular value) calculation
nehari - Nehari approximant
parrot - Parrot's problem
ric_desc - Riccati equation
riccati - Riccati equation
rowinout - inner-outer factorization
sensi - sensitivity functions
tf2des - transfer function to descriptor


augment

Scilab Function
Last update : 12/01/2004

augment - augmented plant

Calling Sequence

[P,r]=augment(G)
[P,r]=augment(G,flag1)
[P,r]=augment(G,flag1,flag2)

Parameters

  • G : linear system ( syslin list), the nominal plant
  • flag1 : one of the following (upper case) character string: 'S' , 'R' , 'T' 'SR' , 'ST' , 'RT' 'SRT'
  • flag2 : one of the following character string: 'o' (stands for 'output', this is the default value) or 'i' (stands for 'input').
  • P : linear system ( syslin list), the ``augmented'' plant
  • r : 1x2 row vector, dimension of P22 = G

Description

If flag1='SRT' (default value), returns the "full" augmented plant

    [ I | -G]   -->'S'
    [ 0 |  I]   -->'R'
P = [ 0 |  G]   -->'T'
    [-------]
    [ I | -G]

'S' , 'R' , 'T' refer to the first three (block) rows of P respectively.

If one of these letters is absent in flag1 , the corresponding row in P is missing.

If G is given in state-space form, the returned P is minimal. P is calculated by: [I,0,0;0,I,0;-I,0,I;I,0,0]*[I,-G;0,I;I,0] .

The augmented plant associated with input sensitivity functions, namely

    [ I | -I]   -->'S'  (input sensitivity)
    [ G | -G]   -->'R'  (G*input sensitivity)
P = [ 0 |  I]   -->'T'  (K*G*input sensitivity)
    [-------]
    [ G | -G]

is obtained by the command [P,r]=augment(G,flag,'i') . For state-space G , this P is calculated by: [I,-I;0,0;0,I;0,0]+[0;I;0;I]*G*[I,-I] and is thus generically minimal.

Note that weighting functions can be introduced by left-multiplying P by a diagonal system of appropriate dimension, e.g., P = sysdiag(W1,W2,W3,eye(G))*P .

Sensitivity functions can be calculated by lft . One has:

For output sensitivity functions [P,r]=augment(P,'SRT'): lft(P,r,K)=[inv(eye()+G*K);K*inv(eye()+G*K);G*K*inv(eye()+G*K)];

For input sensitivity functions [P,r]=augment(P,'SRT','i'): lft(P,r,K)=[inv(eye()+K*G);G*inv(eye()+K*G);K*G*inv(eye()+G*K)];

Examples

G=ssrand(2,3,2); //Plant
K=ssrand(3,2,2); //Compensator
[P,r]=augment(G,'T');
T=lft(P,r,K);   //Complementary sensitivity function
Ktf=ss2tf(K);Gtf=ss2tf(G);
Ttf=ss2tf(T);T11=Ttf(1,1);
Oloop=Gtf*Ktf;
Tn=Oloop*inv(eye(Oloop)+Oloop);
clean(T11-Tn(1,1));
//
[Pi,r]=augment(G,'T','i');
T1=lft(Pi,r,K);T1tf=ss2tf(T1); //Input Complementary sensitivity function
Oloop=Ktf*Gtf;
T1n=Oloop*inv(eye(Oloop)+Oloop);
clean(T1tf(1,1)-T1n(1,1))

See Also

lft , sensi ,


bstap

Scilab Function
Last update : 12/01/2004

bstap - hankel approximant

Calling Sequence

[Q]=bstap(Sl)

Parameters

  • sl : linear system ( syslin list) assumed continuous-time and anti-stable.
  • Q : best stable approximation of Sl ( syslin list).

Description

Computes the best approximant Q of the linear system Sl

where

||T||

is the H-infinity norm of the Hankel operator associated with Sl .

See Also

syslin ,


ccontrg

Scilab Function
Last update : 12/01/2004

ccontrg - central H-infinity controller

Calling Sequence

[K]=ccontrg(P,r,gamma);

Parameters

  • P : syslin list (linear system in state-space representation)
  • r : 1x2 row vector, dimension of the 2,2 part of P
  • gamma : real number

Description

returns a realization K of the central controller for the general standard problem in state-space form.

Note that gamma must be > gopt (ouput of gamitg )

P contains the parameters of plant realization (A,B,C,D) ( syslin list) with

B = ( B1 , B2 ) ,        C= ( C1 ) ,    D = ( D11  D12)
                            ( C2 )          ( D21  D22)

r(1) and r(2) are the dimensions of D22 (rows x columns)

See Also

gamitg , h_inf ,

Author

P. Gahinet (INRIA);


colinout

Scilab Function
Last update : 12/01/2004

colinout - inner-outer factorization

Calling Sequence

[Inn,X,Gbar]=colinout(G)

Parameters

  • G : linear system ( syslin list) [A,B,C,D]
  • Inn : inner factor ( syslin list)
  • Gbar : outer factor ( syslin list)
  • X : row-compressor of G ( syslin list)

Description

Inner-outer factorization (and column compression) of (lxp) G =[A,B,C,D] with l<=p.

G is assumed to be fat ( l<=p ) without zero on the imaginary axis and with a D matrix which is full row rank.

G must also be stable for having Gbar stable.

Dual of rowinout .

See Also

syslin , rowinout ,


copfac

Scilab Function
Last update : 12/01/2004

copfac - right coprime factorization

Calling Sequence

[N,M,XT,YT]=copfac(G [,polf,polc,tol])

Parameters

  • G : syslin list (continuous-time linear system )
  • polf, polc : respectively the poles of XT and YT and the poles of n and M (default values =-1).
  • tol : real threshold for detecting stable poles (default value 100*%eps )
  • N,M,XT,YT : linear systems represented by syslin lists

Description

[N,M,XT,YT]=copfac(G,[polf,polc,[tol]]) returns a right coprime factorization of G .

G = N*M^-1 where N and M are stable, proper and right coprime. (i.e. [N M] left-invertible with stability)

XT and YT satisfy:

[XT -YT].[M N]' = eye (Bezout identity)

G is assumed stabilizable and detectable.

See Also

syslin , lcf ,


dcf

Scilab Function
Last update : 12/01/2004

dcf - double coprime factorization

Calling Sequence

[N,M,X,Y,NT,MT,XT,YT]=dcf(G,[polf,polc,[tol]])

Parameters

  • G : syslin list (continuous-time linear system)
  • polf, polc : respectively the poles of XT and YT and the poles of N and M (default values = -1 ).
  • tol : real threshold for detecting stable poles (default value 100*%eps ).
  • N,M,XT,YT,NT,MT,X,Y : linear systems represented by syslin lists

Description

returns eight stable systems (N,M,X,Y,NT,MT,XT,YT) for the doubly coprime factorization

G must be stabilizable and detectable.

See Also

copfac ,


des2ss

Scilab Function
Last update : 12/01/2004

des2ss - descriptor to state-space

Calling Sequence

[Sl]=des2ss(A,B,C,D,E [,tol])
[Sl]=des2ss(Des)

Parameters

  • A,B,C,D,E : real matrices of appropriate dimensions
  • Des : list
  • Sl : syslin list
  • tol : real parameter (threshold) (default value 100*%eps ).

Description

Descriptor to state-space transform.

Sl=des2ss(A,B,C,D,E) returns a linear system Sl equivalent to the descriptor system (E,A,B,C,D) .

For index one (E,A) pencil, explicit formula is used and for higher index pencils rowshuff is used.

Sl=des2ss(Des) with Des=list('des',A,B,C,D,E) returns a linear system Sl in state-space form with possibly a polynomial D matrix.

A generalized Leverrier algorithm is used.

Examples

s=poly(0,'s');G=[1/(s-1),s;1,2/s^3];
S1=tf2des(G);S2=tf2des(G,"withD");
W1=des2ss(S1);W2=des2ss(S2);
clean(ss2tf(W1))
clean(ss2tf(W2))

See Also

des2tf , glever , rowshuff ,


dhinf

Scilab Function
Last update : 12/01/2004

dhinf - H_infinity design of discrete-time systems

Calling Sequence

[AK,BK,CK,DK,(RCOND)] = dishin(A,B,C,D,ncon,nmeas,gamma)

Parameters

  • A : the n-by-n system state matrix A.
  • B : the n-by-m system input matrix B.
  • C : the p-by-n system output matrix C.
  • D : the p-by-m system matrix D.
  • ncon : the number of control inputs. m >= ncon >= 0, p-nmeas >= ncon.
  • nmeas : the number of measurements. p >= nmeas >= 0, m-ncon >= nmeas.
  • gamma : the parameter gamma used in H_infinity design. It is assumed that gamma is sufficiently large so that the controller is admissible. gamma >= 0.
  • AK : the n-by-n controller state matrix AK.
  • BK : the n-by-nmeas controller input matrix BK.
  • CK : the ncon-by-n controller output matrix CK.
  • DK : the ncon-by-nmeas controller matrix DK.
  • RCOND : a vector containing estimates of the reciprocal condition numbers of the matrices which are to be inverted and estimates of the reciprocal condition numbers of the Riccati equations which have to be solved during the computation of the controller. (See the description of the algorithm in [1].)
    • RCOND (1) contains the reciprocal condition number of the matrix R3,
    • RCOND (2) contains the reciprocal condition number of the matrix R1 - R2'*inv(R3)*R2
    • RCOND (3) contains the reciprocal condition number of the matrix V21,
    • RCOND (4) contains the reciprocal condition number of the matrix St3,
    • RCOND (5) contains the reciprocal condition number of the matrix V12,
    • RCOND (6) contains the reciprocal condition number of the matrix Im2 + DKHAT*D22,
    • RCOND (7) contains the reciprocal condition number of the X-Riccati equation,
    • RCOND (8) contains the reciprocal condition number of the Z-Riccati equation.

Description

[AK,BK,CK,DK,(RCOND)] = dhinf(A,B,C,D,ncon,nmeas, gamma) To compute the matrices of an H-infinity (sub)optimal n-state controller

         | AK | BK |
     K = |----|----|,
         | CK | DK |

for the discrete-time system

         | A  | B1  B2  |   | A | B |
     P = |----|---------| = |---|---|,
         | C1 | D11 D12 |   | C | D |
         | C2 | D21 D22 |

and for a given value of gamma, where B2 has column size of the number of control inputs (ncon) and C2 has row size of the number of measurements (nmeas) being provided to the controller.

References

[1] P.Hr. Petkov, D.W. Gu and M.M. Konstantinov. Fortran 77 routines for Hinf and H2 design of linear discrete-time control systems. Report99-8, Department of Engineering, Leicester University, April 1999.

Examples

//example from Niconet report SLWN1999-12
//Hinf
A=[-0.7  0    0.3  0   -0.5 -0.1
   -0.6  0.2 -0.4 -0.3  0    0
   -0.5  0.7 -0.1  0    0   -0.8
   -0.7  0    0   -0.5 -1    0
    0    0.3  0.6 -0.9  0.1 -0.4
    0.5 -0.8  0    0    0.2 -0.9];
B=[-1 -2 -2  1  0
    1  0  1 -2  1
   -3 -4  0  2 -2
    1 -2  1  0 -1
    0  1 -2  0  3
    1  0  3 -1 -2];
C=[ 1 -1  2 -2  0 -3
   -3  0  1 -1  1  0
    0  2  0 -4  0 -2
    1 -3  0  0  3  1
    0  1 -2  1  0 -2];
D=[1 -1 -2  0  0
   0  1  0  1  0
   2 -1 -3  0  1
   0  1  0  1 -1
   0  0  1  2  1];

ncon=2
nmeas=2
gam=111.30;
[AK,BK,CK,DK] = dhinf(A,B,C,D,ncon,nmeas,gam)

See Also

hinf , h_inf ,


dhnorm

Scilab Function
Last update : 12/01/2004

dhnorm - discrete H-infinity norm

Calling Sequence

hinfnorm=dhnorm(sl,[tol],[normax])

Parameters

  • sl : the state space system ( syslin list) (discrete-time)
  • tol : tolerance in bisection step, default value 0.01
  • normax : upper bound for the norm , default value is 1000
  • hinfnorm : the discrete infinity norm of Sl

Description

produces the discrete-time infinity norm of a state-space system (the maximum over all frequencies on the unit circle of the maximum singular value).

See Also

h_norm , linfn ,


dtsi

Scilab Function
Last update : 12/01/2004

dtsi - stable anti-stable decomposition

Calling Sequence

[Ga,Gs,Gi]=dtsi(G,[tol])

Parameters

  • G : linear system ( syslin list)
  • Ga : linear system ( syslin list) antistable and strictly proper
  • Gs : linear system ( syslin list) stable and strictly proper
  • Gi : real matrix (or polynomial matrix for improper systems)
  • tol : optional parameter for detecting stables poles. Default value: 100*%eps

Description

returns the stable-antistable decomposition of G :

G = Ga + Gs + Gi , (Gi = G(oo))

G can be given in state-space form or in transfer form.

See Also

syslin , pbig , psmall , pfss ,


fourplan

Scilab Function
Last update : 12/01/2004

fourplan - augmented plant to four plants

Calling Sequence

[P11,P12,P21,P22]=fourplan(P,r)

Parameters

  • P : syslin list (linear system)
  • r : 1x2 row vector, dimension of P22
  • P11,P12,P21,P22 : syslin lists.

Description

Utility function.

P being partitioned as follows:

P=[ P11 P12;
    P21 P22]

with size(P22)=r this function returns the four linear systems P11,P12,P21,P22 .

See Also

lqg , lqg2stan , lqr , lqe , lft ,


fspecg

Scilab Function
Last update : 12/01/2004

fspecg - stable factorization

Calling Sequence

[gm]=fspecg(g).

Parameters

  • g,gm : syslin lists (linear systems in state-space representation)

Description

returns gm with gm and gm^-1 stable such that:

gtild(g)*g = gtild(gm)*gm

g and gm are continuous-time linear systems in state-space form.

Imaginary-axis poles are forbidden.


fstabst

Scilab Function
Last update : 12/01/2004

fstabst - Youla's parametrization

Calling Sequence

[J]=fstabst(P,r)

Parameters

  • P : syslin list (linear system)
  • r : 1x2 row vector, dimension of P22
  • J : syslin list (linear system in state-space representation)

Description

Parameterization of all stabilizing feedbacks.

P is partitioned as follows:

P=[ P11 P12;
    P21 P22]

(in state-space or transfer form: automatic conversion in state-space is done for the computations)

r = size of P22 subsystem, (2,2) block of P

          J =[ J11 J12;
               J21 J22]

K is a stabilizing controller for P (i.e. P22 ) iff K=lft(J,r,Q) with Q stable.

The central part of J , J11 is the lqg regulator for P

This J is such that defining T as the 2-port lft of P and J : [T,rt]=lft(P,r,J,r) one has that T12 is inner and T21 is co-inner.

Examples

ny=2;nu=3;nx=4;
P22=ssrand(ny,nu,nx);
bigQ=rand(nx+nu,nx+nu);bigQ=bigQ*bigQ';
bigR=rand(nx+ny,nx+ny);bigR=bigR*bigR';
[P,r]=lqg2stan(P22,bigQ,bigR);
J=fstabst(P,r);
Q=ssrand(nu,ny,1);Q('A')=-1;  //Stable Q
K=lft(J,r,Q);
A=h_cl(P,r,K); spec(A)

See Also

obscont , lft , lqg , lqg2stan ,


gamitg

Scilab Function
Last update : 12/01/2004

gamitg - H-infinity gamma iterations

Calling Sequence

[gopt]=gamitg(G,r,prec [,options]);

Parameters

  • G : syslin list (plant realization )
  • r : 1x2 row vector (dimension of G22 )
  • prec : desired relative accuracy on the norm
  • option : string 't'
  • gopt : real scalar, optimal H-infinity gain

Description

gopt=gamitg(G,r,prec [,options]) returns the H-infinity optimal gain gopt .

G contains the state-space matrices [A,B,C,D] of the plant with the usual partitions:

   B = ( B1 , B2 ) ,    C = ( C1 ) ,    D = ( D11  D12)
                            ( C2 )          ( D21  D22)

These partitions are implicitly given in r : r(1) and r(2) are the dimensions of D22 (rows x columns)

With option='t' , gamitg traces each bisection step, i.e., displays the lower and upper bounds and the current test point.

See Also

ccontrg , h_inf ,

Author

P. Gahinet


gcare

Scilab Function
Last update : 12/01/2004

gcare - control Riccati equation

Calling Sequence

[X,F]=gcare(Sl)

Parameters

  • Sl : linear system ( syslin list)
  • X : symmetric matrix
  • F : real matrix

Description

Generalized Control Algebraic Riccati Equation (GCARE). X = solution , F = gain.

The GCARE for Sl=[A,B,C,D] is:

(A-B*Si*D'*C)'*X+X*(A-B*Si*D'*C)-X*B*Si*B'*X+C'*Ri*C=0

where S=(eye()+D'*D) , Si=inv(S) , R=(eye()+D*D') , Ri=inv(R) and F=-Si*(D'*C+B'*X) is such that A+B*F is stable.

See Also

gfare ,


gfare

Scilab Function
Last update : 12/01/2004

gfare - filter Riccati equation

Calling Sequence

[Z,H]=gfare(Sl)

Parameters

  • Sl : linear system ( syslin list)
  • Z : symmetric matrix
  • H : real matrix

Description

Generalized Filter Algebraic Riccati Equation (GFARE). Z = solution, H = gain.

The GFARE for Sl=[A,B,C,D] is:

(A-B*D'*Ri*C)*Z+Z*(A-B*D'*Ri*C)'-Z*C'*Ri*C*Z+B*Si*B'=0

where S=(eye()+D'*D) , Si=inv(S) , R=(eye()+D*D') , Ri=inv(R) and H=-(B*D'+Z*C')*Ri is such that A+H*C is stable.

See Also

gcare ,


gtild

Scilab Function
Last update : 12/01/2004

gtild - tilde operation

Calling Sequence

Gt=gtild(G)
Gt=gtild(G,flag)

Parameters

  • G : either a polynomial or a linear system ( syslin list) or a rational matrix
  • Gt : same as G
  • flag : character string: either 'c' or 'd' (optional parameter).

Description

If G is a polynomial matrix (or a polynomial), Gt=gtild(G,'c') returns the polynomial matrix Gt(s)=G(-s)' .

If G is a polynomial matrix (or a polynomial), Gt=gtild(G,'d') returns the polynomial matrix Gt=G(1/z)*z^n where n is the maximum degree of G .

For continuous-time systems represented in state-space by a syslin list, Gt = gtild(G,'c') returns a state-space representation of G(-s)' i.e the ABCD matrices of Gt are A',-C', B', D' . If G is improper ( D= D(s) ) the D matrix of Gt is D(-s)' .

For discrete-time systems represented in state-space by a syslin list, Gt = gtild(G,'d') returns a state-space representation of G(-1/z)' i.e the (possibly improper) state-space representation of -z*C*inv(z*A-B)*C + D(1/z) .

For rational matrices, Gt = gtild(G,'c') returns the rational matrix Gt(s)=G(-s) and Gt = gtild(G,'d') returns the rational matrix Gt(z)= G(1/z)' .

The parameter flag is necessary when gtild is called with a polynomial argument.

Examples

//Continuous time
s=poly(0,'s');G=[s,s^3;2+s^3,s^2-5]
Gt=gtild(G,'c')
Gt-horner(G,-s)'   //continuous-time interpretation
Gt=gtild(G,'d');
Gt-horner(G,1/s)'*s^3  //discrete-time interpretation
G=ssrand(2,2,3);Gt=gtild(G);   //State-space (G is cont. time by default)
clean((horner(ss2tf(G),-s))'-ss2tf(Gt))   //Check
// Discrete-time
z=poly(0,'z');
Gss=ssrand(2,2,3);Gss('dt')='d'; //discrete-time
Gss(5)=[1,2;0,1];   //With a constant D matrix
G=ss2tf(Gss);Gt1=horner(G,1/z)';
Gt=gtild(Gss);
Gt2=clean(ss2tf(Gt)); clean(Gt1-Gt2)  //Check
//Improper systems
z=poly(0,'z');
Gss=ssrand(2,2,3);Gss(7)='d'; //discrete-time
Gss(5)=[z,z^2;1+z,3];    //D(z) is polynomial
G=ss2tf(Gss);Gt1=horner(G,1/z)';  //Calculation in transfer form
Gt=gtild(Gss);    //..in state-space
Gt2=clean(ss2tf(Gt));clean(Gt1-Gt2)  //Check

See Also

syslin , horner , factors ,


h2norm

Scilab Function
Last update : 12/01/2004

h2norm - H2 norm

Calling Sequence

[n]=h2norm(Sl [,tol])

Parameters

  • Sl : linear system ( syslin list)
  • n : real scalar

Description

produces the H2 norm of a linear continuous time system Sl .

(For Sl in state-space form h2norm uses the observability gramian and for Sl in transfer form h2norm uses a residue method)


hankelsv

Scilab Function
Last update : 12/01/2004

hankelsv - Hankel singular values

Calling Sequence

[nk2,W]=hankelsv(sl [,tol])
[nk2]=hankelsv(sl [,tol])

Parameters

  • sl : syslin list representing the linear system (state-space).
  • tol : tolerance parameter for detecting imaginary axis modes (default value is 1000*%eps ).

Description

returns nk2 , the squared Hankel singular values of sl and W = P*Q = controllability gramian times observability gramian.

nk2 is the vector of eigenvalues of W .

Examples

A=diag([-1,-2,-3]);
sl=syslin('c',A,rand(3,2),rand(2,3));[nk2,W]=hankelsv(sl)
[Q,M]=pbig(W,nk2(2)-%eps,'c');
slr=projsl(sl,Q,M);hankelsv(slr)

See Also

balreal , equil , equil1 ,


hinf

Scilab Function
Last update : 12/01/2004

hinf - H_infinity design of continuous-time systems

Calling Sequence

[AK,BK,CK,DK,(RCOND)] = hinf(A,B,C,D,ncon,nmeas,gamma)

Parameters

  • A : the n-by-n system state matrix A.
  • B : the n-by-m system input matrix B.
  • C : the p-by-n system output matrix C.
  • D : the p-by-m system matrix D.
  • ncon : the number of control inputs. m >= ncon >= 0, p-nmeas >= ncon.
  • nmeas : the number of measurements. p >= nmeas >= 0, m-ncon >= nmeas.
  • gamma : the parameter gamma used in H_infinity design. It is assumed that gamma is sufficiently large so that the controller is admissible. gamma >= 0.
  • AK : the n-by-n controller state matrix AK.
  • BK : the n-by-nmeas controller input matrix BK.
  • CK : the ncon-by-n controller output matrix CK.
  • DK : the ncon-by-nmeas controller matrix DK.
  • RCOND : a vector containing estimates of the reciprocal condition numbers of the matrices which are to be inverted and estimates of the reciprocal condition numbers of the Riccati equations which have to be solved during the computation of the controller. (See the description of the algorithm in [1].)
    • RCOND (1) contains the reciprocal condition number of the control transformation matrix TU,
    • RCOND (2) contains the reciprocal condition number of the measurement transformation matrix TY,
    • RCOND (3) contains an estimate of the reciprocal condition number of the X-Riccati equation,
    • RCOND (4) contains an estimate of the reciprocal condition number of the Y-Riccati equation.

Description

[AK,BK,CK,DK,(RCOND)] = hinf(A,B,C,D,ncon,nmeas,gamma) To compute the matrices of an H-infinity (sub)optimal n-state controller

              | AK | BK |
          K = |----|----|,
              | CK | DK |

for the continuous-time system

              | A  | B1  B2  |   | A | B |
          P = |----|---------| = |---|---|,
              | C1 | D11 D12 |   | C | D |
              | C2 | D21 D22 |

and for a given value of gamma, where B2 has column size of the number of control inputs (ncon) and C2 has row size of the number of measurements (nmeas) being provided to the controller.

References

[1] P.Hr. Petkov, D.W. Gu and M.M. Konstantinov. Fortran 77 routines for Hinf and H2 design of continuous-time linear control systems. Report98-14, Department of Engineering, Leicester University, August 1998.

Examples

//example from Niconet report SLWN1999-12
//Hinf
A=[-1  0  4  5 -3 -2
   -2  4 -7 -2  0  3
   -6  9 -5  0  2 -1
   -8  4  7 -1 -3  0
    2  5  8 -9  1 -4
    3 -5  8  0  2 -6];

B=[-3 -4 -2  1  0
    2  0  1 -5  2
   -5 -7  0  7 -2
    4 -6  1  1 -2
   -3  9 -8  0  5
    1 -2  3 -6 -2];

C=[ 1 -1  2 -4  0 -3
   -3  0  5 -1  1  1
   -7  5  0 -8  2 -2
    9 -3  4  0  3  7
    0  1 -2  1 -6 -2];

D=[ 1 -2 -3  0  0
    0  4  0  1  0
    5 -3 -4  0  1
    0  1  0  1 -3
    0  0  1  7  1];
Gamma=10.18425636157899;
[AK,BK,CK,DK] = hinf(A,B,C,D,2,2,Gamma)

See Also

dhinf ,


h_cl

Scilab Function
Last update : 12/01/2004

h_cl - closed loop matrix

Calling Sequence

[Acl]=h_cl(P,r,K)
[Acl]=h_cl(P22,K)

Parameters

  • P, P22 : linear system ( syslin list), augmented plant or nominal plant respectively
  • r : 1x2 row vector, dimensions of 2,2 part of P ( r=[rows,cols]=size(P22) )
  • K : linear system ( syslin list), controller
  • Acl : real square matrix

Description

Given the standard plant P (with r=size(P22) ) and the controller K , this function returns the closed loop matrix Acl .

The poles of Acl must be stable for the internal stability of the closed loop system.

Acl is the A -matrix of the linear system [I -P22;-K I]^-1 i.e. the A -matrix of lft(P,r,K)

See Also

lft ,

Author

F. D.


h_inf_st

Scilab Function
Last update : 12/01/2004

h_inf_st - static H_infinity problem

Calling Sequence

[Kopt,gamaopt]=h_inf_stat(D,r)

Parameters

  • D : real matrix
  • r : 1x2 vector
  • Kopt : matrix

Description

computes a matrix Kopt such that largest singular value of:

lft(D,r,K)=D11+D12* K*inv(I-D22*K)* D21 is minimal (Static H-infinity four blocks problem).

D is partionned as D=[D11 D12; D21 D22] where size(D22)=r=[r1 r2]

Author

F.D. ;


h_inf

Scilab Function
Last update : 12/01/2004

h_inf - H-infinity (central) controller

Calling Sequence

[Sk,ro]=h_inf(P,r,romin,romax,nmax)
[Sk,rk,ro]=h_inf(P,r,romin,romax,nmax)

Parameters

  • P : syslin list : continuous-time linear system (``augmented'' plant given in state-space form or in transfer form)
  • r : size of the P22 plant i.e. 2-vector [#outputs,#inputs]
  • romin,romax : a priori bounds on ro with ro=1/gama^2 ; ( romin=0 usually)
  • nmax : integer, maximum number of iterations in the gama-iteration.

Description

h_inf computes H-infinity optimal controller for the continuous-time plant P .

The partition of P into four sub-plants is given through the 2-vector r which is the size of the 22 part of P .

P is given in state-space e.g. P=syslin('c',A,B,C,D) with A,B,C,D = constant matrices or P=syslin('c',H) with H a transfer matrix.

[Sk,ro]=H_inf(P,r,romin,romax,nmax) returns ro in [romin,romax] and the central controller Sk in the same representation as P .

(All calculations are made in state-space, i.e conversion to state-space is done by the function, if necessary).

Invoked with three LHS parameters,

[Sk,rk,ro]=H_inf(P,r,romin,romax,nmax) returns ro and the Parameterization of all stabilizing controllers:

a stabilizing controller K is obtained by K=lft(Sk,r,PHI) where PHI is a linear system with dimensions r' and satisfy:

H_norm(PHI) < gamma . rk (=r) is the size of the Sk22 block and ro = 1/gama^2 after nmax iterations.

Algorithm is adapted from Safonov-Limebeer. Note that P is assumed to be a continuous-time plant.

See Also

gamitg , ccontrg , leqr ,

Author

F.Delebecque INRIA (1990)


h_norm

Scilab Function
Last update : 12/01/2004

h_norm - H-infinity norm

Calling Sequence

[hinfnorm [,frequency]]=h_norm(sl [,rerr])

Parameters

  • sl : the state space system ( syslin list)
  • rerr : max. relative error, default value 1e-8
  • hinfnorm : the infinity norm of Sl
  • frequency : frequency at which maximum is achieved

Description

produces the infinity norm of a state-space system (the maximum over all frequencies of the maximum singular value).

See Also

linfn , linf , svplot ,


lcf

Scilab Function
Last update : 12/01/2004

lcf - normalized coprime factorization

Calling Sequence

[N,M]=lcf(sl)

Parameters

  • sl : linear system given in state space or transfer function ( syslin list)
  • N,M : two linear systems ( syslin list)

Description

Computes normalized coprime factorization of the linear dynamic system sl .

sl = M^-1 N

Author

F. D.; ;


leqr

Scilab Function
Last update : 12/01/2004

leqr - H-infinity LQ gain (full state)

Calling Sequence

[K,X,err]=leqr(P12,Vx)

Parameters

  • P12 : syslin list
  • Vx : symmetric nonnegative matrix (should be small enough)
  • K,X : two real matrices
  • err : a real number (l1 norm of LHS of Riccati equation)

Description

leqr computes the linear suboptimal H-infinity LQ full-state gain for the plant P12=[A,B2,C1,D12] in continuous or discrete time.

P12 is a syslin list (e.g. P12=syslin('c',A,B2,C1,D12) ).

      [C1' ]               [Q  S]
      [    ]  * [C1 D12] = [    ]
      [D12']               [S' R]

Vx is related to the variance matrix of the noise w perturbing x ; (usually Vx=gama^-2*B1*B1' ).

The gain K is such that A + B2*K is stable.

X is the stabilizing solution of the Riccati equation.

For a continuous plant:

(A-B2*inv(R)*S')'*X+X*(A-B2*inv(R)*S')-X*(B2*inv(R)*B2'-Vx)*X+Q-S*inv(R)*S'=0

K=-inv(R)*(B2'*X+S)

For a discrete time plant:

X-(Abar'*inv((inv(X)+B2*inv(R)*B2'-Vx))*Abar+Qbar=0

K=-inv(R)*(B2'*inv(inv(X)+B2*inv(R)*B2'-Vx)*Abar+S')

with Abar=A-B2*inv(R)*S' and Qbar=Q-S*inv(R)*S'

The 3-blocks matrix pencils associated with these Riccati equations are:

               discrete                        continuous
   |I  -Vx  0|   | A    0    B2|       |I   0   0|   | A    Vx    B2|
  z|0   A'  0| - |-Q    I    -S|      s|0   I   0| - |-Q   -A'   -S |
   |0   B2' 0|   | S'   0     R|       |0   0   0|   | S'   -B2'   R|

See Also

lqr ,

Author

F.D.;


lft

Scilab Function
Last update : 12/01/2004

lft - linear fractional transformation

Calling Sequence

[P1]=LFT(P,K)
[P1]=LFT(P,r,K)
[P1,r1]=LFT(P,r,P#,r#)

Parameters

  • P : linear system ( syslin list), the ``augmented'' plant, implicitly partitioned into four blocks (two input ports and two output ports).
  • K : linear system ( syslin list), the controller (possibly an ordinary gain).
  • r : 1x2 row vector, dimension of P22
  • P# : linear system ( syslin list), implicitly partitioned into four blocks (two input ports and two output ports).
  • r# : 1x2 row vector, dimension of P#22

Description

Linear fractional transform between two standard plants P and P# in state space form or in transfer form ( syslin lists).

r= size(P22) r#=size(P22#)

LFT(P,r, K) is the linear fractional transform between P and a controller K ( K may be a gain or a controller in state space form or in transfer form);

LFT(P,K) is LFT(P,r,K) with r =size of K transpose;

P1= P11+P12*K* (I-P22*K)^-1 *P21

[P1,r1]=LFT(P,r,P#,r#) returns the generalized (2 ports) lft of P and P# .

P1 is the pair two-port interconnected plant and the partition of P1 into 4 blocks in given by r1 which is the dimension of the 22 block of P1 .

P and R can be PSSDs i.e. may admit a polynomial D matrix.

Examples

s=poly(0,'s');
P=[1/s, 1/(s+1); 1/(s+2),2/s]; K= 1/(s-1);
lft(P,K)
lft(P,[1,1],K)
P(1,1)+P(1,2)*K*inv(1-P(2,2)*K)*P(2,1)   //Numerically dangerous!
ss2tf(lft(tf2ss(P),tf2ss(K)))
lft(P,-1)
f=[0,0;0,1];w=P/.f; w(1,1)
//Improper plant (PID control)
W=[1,1;1,1/(s^2+0.1*s)];K=1+1/s+s
lft(W,[1,1],K); ss2tf(lft(tf2ss(W),[1,1],tf2ss(K)))

See Also

sensi , augment , feedback , sysdiag ,


linfn

Scilab Function
Last update : 12/01/2004

linfn - infinity norm

Calling Sequence

[x,freq]=linfn(G,PREC,RELTOL,options);

Parameters

  • G : is a syslin list
  • PREC : desired relative accuracy on the norm
  • RELTOL : relative threshold to decide when an eigenvalue can be considered on the imaginary axis.
  • options : available options are 'trace' or 'cond'
  • x is the computed norm.
  • freq : vector

Description

Computes the Linf (or Hinf) norm of G This norm is well-defined as soon as the realization G=(A,B,C,D) has no imaginary eigenvalue which is both controllable and observable.

freq is a list of the frequencies for which ||G|| is attained,i.e., such that ||G (j om)|| = ||G|| .

If -1 is in the list, the norm is attained at infinity.

If -2 is in the list, G is all-pass in some direction so that ||G (j omega)|| = ||G|| for all frequencies omega.

The algorithm follows the paper by G. Robel (AC-34 pp. 882-884, 1989). The case D=0 is not treated separately due to superior accuracy of the general method when (A,B,C) is nearly non minimal.

The 'trace' option traces each bisection step, i.e., displays the lower and upper bounds and the current test point.

The 'cond' option estimates a confidence index on the computed value and issues a warning if computations are ill-conditioned

In the general case ( A neither stable nor anti-stable), no upper bound is prespecified.

If by contrast A is stable or anti stable, lower and upper bounds are computed using the associated Lyapunov solutions.

See Also

h_norm ,

Author

P. Gahinet


linf

Scilab Function
Last update : 12/01/2004

linf - infinity norm

Calling Sequence

linf(g [,eps],[tol])

Parameters

  • g : is a syslin linear system.
  • eps : is error tolerance on n.
  • tol : threshold for imaginary axis poles.

Description

returns the L_infinity norm of g .

    n=sup [sigmax(g(jw)]
       w

(sigmax largest singular value).

See Also

h_norm , linfn ,


lqg_ltr

Scilab Function
Last update : 12/01/2004

lqg_ltr - LQG with loop transform recovery

Calling Sequence

[kf,kc]=lqg_ltr(sl,mu,ro)

Parameters

  • sl : linear system in state-space form ( syslin list)
  • mu,ro : real positive numbers chosen ``small enough''
  • kf,kc : controller and observer Kalman gains.

Description

returns the Kalman gains for:

           x = a*x + b*u + l*w1
  (sl)
           y = c*x + mu*I*w2

           z = h*x

Cost function:

/+oo | J = E(| [z(t)'*z(t) + ro^2*u(t)'*u(t)]dt) lqg | / 0

The lqg/ltr approach looks for L,mu,H,ro such that: J(lqg) = J(freq) where

/+oo * * * J = | tr[S W W S ] + tr[T T]dw freq | /0

and

 S = (I + G*K)^(-1)
 T = G*K*(I+G*K)^(-1)

See Also

syslin ,


macglov

Scilab Function
Last update : 12/01/2004

macglov - Mac Farlane Glover problem

Calling Sequence

[P,r]=macglov(Sl)

Parameters

  • Sl : linear system ( syslin list)
  • P : linear system ( syslin list), ``augmented'' plant
  • r : 1x2 vector, dimension of P22

Description

[P,r]=macglov(Sl) returns the standard plant P for the Glover-McFarlane problem.

For this problem ro_optimal = 1-hankel_norm( [N,M] ) with [N,M]=lcf(sl) (Normalized coprime factorization) i.e.

gama_optimal = 1/sqrt(ro_optimal)

Author

F. Delebecque INRIA


mucomp

Scilab Function
Last update : 12/01/2004

mucomp - mu (structured singular value) calculation

Calling Sequence

[BOUND, D, G] = mucomp(Z, K, T)

Parameters

  • Z : the complex n-by-n matrix for which the structured singular value is to be computed
  • K : the vector of length m containing the block structure of the uncertainty.
  • T : the vector of length m indicating the type of each block. T(I) = 1 if the corresponding block is real T(I) = 2 if the corresponding block is complex.
  • BOUND : the upper bound on the structured singular value.
  • D, G : vectors of length n containing the diagonal entries of the diagonal matrices D and G, respectively, such that the matrix Z'*D^2*Z + sqrt(-1)*(G*Z-Z'*G) - bound^2*D^2 is negative semidefinite.

Description

To compute an upper bound on the structured singular value for a given square complex matrix and given block structure of the uncertainty.

Reference

Slicot routine AB13MD.


nehari

Scilab Function
Last update : 12/01/2004

nehari - Nehari approximant

Calling Sequence

[x]=nehari(R [,tol])

Parameters

  • R : linear system ( syslin list)
  • x : linear system ( syslin list)
  • tol : optional threshold

Description

[x]=nehari(R [,tol])returns the Nehari approximant of R .

R = linear system in state-space representation ( syslin list).

R is strictly proper and - R~ is stable (i.e. R is anti stable).

    || R - X ||oo = min || R - Y ||oo
                  Y in Hoo


parrot

Scilab Function
Last update : 12/01/2004

parrot - Parrot's problem

Calling Sequence

K=parrot(D,r)

Parameters

  • D,K : matrices
  • r : 1X2 vector (dimension of the 2,2 part of D )

Description

Given a matrix D partionned as [D11 D12; D21 D22] where size(D22)=r=[r1,r2] compute a matrix K such that largest singular value of [D11 D12; D21 D22+K] is minimal (Parrot's problem)

See Also

h_inf_st ,


riccati

Scilab Function
Last update : 12/01/2004

riccati - Riccati equation

Calling Sequence

X=riccati(A,B,C,dom,[typ])
[X1,X2]=riccati(A,B,C,dom,[typ])

Parameters

  • A,B,C : real matrices nxn, B and C symetric.
  • dom : 'c' or 'd' for the time domain (continuous or discrete)
  • typ : string : 'eigen' for block diagonalization or schur' for Schur method.
  • X1,X2,X : square real matrices (X2 invertible), X symmetric

Description

X=riccati(A,B,C,dom,[typ]) solves the Riccati equation:

A'*X+X*A-X*B*X+C=0

in continuous time case, or:

 A'*X*A-(A'*X*B1/(B2+B1'*X*B1))*(B1'*X*A)+C-X

with B=B1/B2*B1' in the discrete time case. If called with two output arguments, riccati returns X1,X2 such that X=X1/X2 .

See Also

ricc , ric_desc ,


ric_desc

Scilab Function
Last update : 12/01/2004

ric_desc - Riccati equation

Calling Sequence

X=ric_desc(H [,E))
[X1,X2,zero]=ric_desc(H [,E])

Parameters

  • H,E : real square matrices
  • X1,X2 : real square matrices
  • zero : real number

Description

Riccati solver with hamiltonian matrices as inputs.

In the continuous time case calling sequence is ric_descr(H) (one input):

Riccati equation is:

  (Ec)   A'*X + X*A + X*R*X -Q = 0.

Defining the hamiltonian matrix H by:

 H = [A  R;
      Q -A']

with the calling sequence [X1,X2,zero]=ric_descr(H) , the solution X is given by X=X1/X2 .

zero = L1 norm of rhs of ( Ec )

The solution X is also given by X=riccati(A,Q,R,'c'))

In the discrete-time case calling sequence is ric_descr(H,E) (two inputs):

The Riccati equation is:

   (Ed)  A'*X*A-(A'*X*B*(R+B'*X*B)^-1)*(B'*X*A)+C-X = 0.

Defining G=B/R*B' and the hamiltonian pencil (E,H) by:

      E=[eye(n,n),G;               H=[A, 0*ones(n,n);
         0*ones(n,n),A']             -C, eye(n,n)];

with the calling sequence [X1,X2,err]=ric_descr(H,E) , the solution X is given by X=X1/X2 .

zero = L1 norm of rhs of ( Ed )

The solution X is also given by X=riccati(A,G,C,'d') with G=B/R*B'

See Also

riccati ,


rowinout

Scilab Function
Last update : 12/01/2004

rowinout - inner-outer factorization

Calling Sequence

[Inn,X,Gbar]=rowinout(G)

Parameters

  • G : linear system ( syslin list) [A,B,C,D]
  • Inn : inner factor ( syslin list)
  • Gbar : outer factor ( syslin list)
  • X : row-compressor of G ( syslin list)

Description

Inner-outer factorization (and row compression) of ( l x p ) G =[A,B,C,D] with l>=p .

G is assumed to be tall ( l>=p ) without zero on the imaginary axis and with a D matrix which is full column rank.

G must also be stable for having Gbar stable.

G admits the following inner-outer factorization:

         G = [ Inn ] | Gbar |
                     |  0   |

where Inn is square and inner (all pass and stable) and Gbar square and outer i.e: Gbar is square bi-proper and bi-stable (Gbar inverse is also proper and stable);

Note that:

         [ Gbar ]
   X*G = [  -   ]
         [  0   ]

is a row compression of G where X = Inn inverse is all-pass i.e:

 T
X (-s) X(s) = Identity

(for the continous time case).

See Also

syslin , colinout ,


sensi

Scilab Function
Last update : 12/01/2004

sensi - sensitivity functions

Calling Sequence

[Se,Re,Te]=sensi(G,K)
[Si,Ri,Ti]=sensi(G,K,flag)

Parameters

  • G : standard plant ( syslin list)
  • K : compensator ( syslin list)
  • flag : character string 'o' (default value) or 'i'
  • Se : output sensitivity function (I+G*K)^-1
  • Re : K*Se
  • Te : G*K*Se (output complementary sensitivity function)

Description

sensi computes sensitivity functions. If G and K are given in state-space form, the systems returned are generically minimal. Calculation is made by lft , e.g., Se can be given by the commands P = augment(G,'S') , Se=lft(P,K) . If flag = 'i' , [Si,Ri,Ti]=sensi(G,K,'i') returns the input sensitivity functions.

[Se;Re;Te]= [inv(eye()+G*K);K*inv(eye()+G*K);G*K*inv(eye()+G*K)];
[Si;Ri;Ti]= [inv(eye()+K*G);G*inv(eye()+K*G);K*G*inv(eye()+K*G)];

Examples

G=ssrand(1,1,3);K=ssrand(1,1,3);
[Se,Re,Te]=sensi(G,K);
Se1=inv(eye()+G*K);  //Other way to compute
ss2tf(Se)    //Se seen in transfer form
ss2tf(Se1)
ss2tf(Te)
ss2tf(G*K*Se1)
[Si,Ri,Ti]=sensi(G,K,'i');
w1=[ss2tf(Si);ss2tf(Ri);ss2tf(Ti)]
w2=[ss2tf(inv(eye()+K*G));ss2tf(G*inv(eye()+K*G));ss2tf(K*G*inv(eye()+K*G))];
clean(w1-w2)

See Also

augment , lft , h_cl ,


tf2des

Scilab Function
Last update : 12/01/2004

tf2des - transfer function to descriptor

Calling Sequence

S=tf2des(G)
S=tf2des(G,flag)

Parameters

  • G : linear system ( syslin list) with possibly polynomial D matrix
  • flag : character string "withD"
  • S : list

Description

Transfer function to descriptor form: S=list('d',A,B,C,D,E)

  E*xdot = A*x+B*u
  y = C*x + D*u

Note that D=0 if the optional parameter flag= "withD" is not given. Otherwise a maximal rank D matrix is returned in the fifth entry of the list S

Examples

s=poly(0,'s');
G=[1/(s-1),s;1,2/s^3];
S1=tf2des(G);des2tf(S1)
S2=tf2des(G,"withD");des2tf(S2)

See Also

pol2des , tf2ss , ss2des , des2tf ,


Optimisation et simulation
NDcost - generic external for optim computing gradient using finite differences
bvode - boundary value problems for ODE
bvodeS - simplified call of bvode
dasrt - DAE solver with zero crossing
dassl - differential algebraic equation
datafit - Parameter identification based on measured data
derivative - approximate derivatives of a function
fit_dat - Parameter identification based on measured data
fsolve - résout un système d'équations non-linéaires
impl - differential algebraic equation
int2d - definite 2D integral by quadrature and cubature method
int3d - definite 3D integral by quadrature and cubature method
intc - Cauchy integral
intg - intégration numérique adaptative
intl - Cauchy integral
karmarkar - karmarkar algorithm
leastsq - Solves non-linear least squares problems
linpro - linear programming solver
lmisolver - linear matrix inequation solver
lmitool - tool for solving linear matrix inequations
lsqrsolve - minimize the sum of the squares ofnonlinear functions, levenberg-marquardt algorithm
numdiff - numerical gradient estimation
ode - solveur d'équations différentielles ordinaires
ode_discrete - ordinary differential equation solver, discrete time simulation
ode_optional_output - ode solvers optional outputs description
ode_root - ordinary differential equation solver with root finding
odedc - discrete/continuous ode solver
odeoptions - set options for ode solvers
optim - non-linear optimization routine
qld - linear quadratic programming solver
quapro - linear quadratic programming solver
semidef - semidefinite programming


bvode

Scilab Function
Last update : 28/06/2005

bvode - boundary value problems for ODE

Calling Sequence

[z]=bvode(points,ncomp,m,aleft,aright,zeta,ipar,ltol,tol,fixpnt,...
fsub1,dfsub1,gsub1,dgsub1,guess1)

Parameters

  • z The solution of the ode evaluated on the mesh given by points
  • points an array which gives the points for which we want the solution
  • ncomp number of differential equations (ncomp <= 20)
  • m a vector of size ncomp . m(j) gives the order of the j-th differential equation
  • aleft left end of interval
  • aright right end of interval
  • zeta zeta(j) gives j-th side condition point (boundary point). must have

    zeta(j) <= zeta(j+1)

    all side condition points must be mesh points in all meshes used, see description of ipar(11) and fixpnt below.

  • ipar an integer array dimensioned at least 11. a list of the parameters in ipar and their meaning follows some parameters are renamed in bvode; these new names are given in parentheses.
    • ipar(1) 0 if the problem is linear, 1 if the problem is nonlinear
    • ipar(2) = number of collocation points per subinterval (= k ) where

      max m(i) <= k <= 7 .

      if ipar(2)=0 then bvode sets

      k = max ( max m(i)+1, 5-max m(i) )

    • ipar(3) = number of subintervals in the initial mesh ( = n ). if ipar(3) = 0 then bvode arbitrarily sets n = 5 .
    • ipar(4) = number of solution and derivative tolerances. ( = ntol ) we require

      0 < ntol <= mstar.

    • ipar(5) = dimension of fspace ( = ndimf ) a real work array. its size provides a constraint on nmax. choose ipar(5) according to the formula:

      ipar(5)>=nmax*nsizef

      where

      nsizef=4+3*mstar+(5+kd)*kdm+(2*mstar-nrec)*2*mstar .

    • ipar(6) = dimension of ispace ( = ndimi )an integer work array. its size provides a constraint on nmax, the maximum number of subintervals. choose ipar(6) according to the formula:

      ipar(6)>=nmax*nsizei

      where

      nsizei=3 + kdm with kdm=kd+mstar ; kd=k*ncomp ; nrec =number of right end boundary conditions.

    • ipar(7) output control ( = iprint )
      • = -1 for full diagnostic printout
      • = 0 for selected printout
      • = 1 for no printout
    • ipar(8) ( = iread )
      • = 0 causes bvode to generate a uniform initial mesh.
      • = xx Other values are not implemented yet in Scilab
        • = 1 if the initial mesh is provided by the user. it is defined in fspace as follows: the mesh

          will occupy fspace(1), ..., fspace(n+1) . the user needs to supply only the interior mesh points fspace(j) = x(j), j = 2, ..., n.

        • = 2 if the initial mesh is supplied by the user as with ipar(8)=1 , and in addition no adaptive mesh selection is to be done.
    • ipar(9) ( = iguess )
      • = 0 if no initial guess for the solution is provided.
      • = 1 if an initial guess is provided by the user in subroutine guess .
      • = 2 if an initial mesh and approximate solution coefficients are provided by the user in fspace. (the former and new mesh are the same).
      • = 3 if a former mesh and approximate solution coefficients are provided by the user in fspace, and the new mesh is to be taken twice as coarse; i.e.,every second point from the former mesh.
      • = 4 if in addition to a former initial mesh and approximate solution coefficients, a new mesh is provided in fspace as well. (see description of output for further details on iguess = 2, 3, and 4.)
    • ipar(10)
      • = 0 if the problem is regular
      • = 1 if the first relax factor is =rstart, and the nonlinear iteration does not rely on past covergence (use for an extra sensitive nonlinear problem only).
      • = 2 if we are to return immediately upon (a) two successive nonconvergences, or (b) after obtaining error estimate for the first time.
    • ipar(11) = number of fixed points in the mesh other than aleft and aright . ( = nfxpnt , the dimension of fixpnt ) the code requires that all side condition points other than aleft and aright (see description of zeta ) be included as fixed points in fixpnt .
  • ltol an array of dimension ipar(4) . ltol(j) = l specifies that the j-th tolerance in tol controls the error in the l-th component of z(u) . also require that:

    1 <= ltol(1) < ltol(2) < ... < ltol(ntol) <= mstar

  • tol an array of dimension ipar(4) . tol(j) is the error tolerance on the ltol(j) -th component of z(u) . thus, the code attempts to satisfy for j=1:ntol on each subinterval
            abs(z(v)-z(u))       <=     tol(j)*abs(z(u))     +tol(j)
                     ltol(j)                       ltol(j)

    if v(x) is the approximate solution vector.

  • fixpnt an array of dimension ipar(11) . it contains the points, other than aleft and aright , which are to be included in every mesh.
  • externals The function fsub,dfsub,gsub,dgsub,guess are Scilab externals i.e. functions (see syntax below) or the name of a Fortran subroutine (character string) with specified calling sequence or a list. An external as a character string refers to the name of a Fortran subroutine. The Fortran coded function interface to bvode are specified in the file fcol.f .
    • fsub name of subroutine for evaluating
                                                      t
                f(x,z(u(x))) =    (f ,...,f     )
                                    1      ncomp

      at a point x in (aleft,aright) . it should have the heading [f]=fsub(x,z) where f is the vector containing the value of fi(x,z(u)) in the i-th component and

                                                          t
                         z(u(x))=(z(1),...,z(mstar))

      is defined as above under purpose .

    • dfsub name of subroutine for evaluating the Jacobian of f(x,z(u)) at a point x. it should have the heading [df]=dfsub (x , z ) where z(u(x)) is defined as for fsub and the ( ncomp ) by ( mstar ) array df should be filled by the partial derivatives of f, viz, for a particular call one calculates
                          df(i,j) = dfi / dzj, i=1,...,ncomp
                                         j=1,...,mstar.
    • gsub name of subroutine for evaluating the i-th component of g(x,z(u(x))) = g (zeta(i),z(u(zeta(i)))) at a point x = zeta(i) where 1<=i<=mstar.

      it should have the heading [g]=gsub (i , z) where z(u) is as for fsub , and i and g=gi are as above. Note that in contrast to f in fsub , here only one value per call is returned in g .

    • dgsub name of subroutine for evaluating the i-th row of the Jacobian of g(x,u(x)) . it should have the heading [dg]=dgsub (i , z ) where z(u) is as for fsub, i as for gsub and the mstar-vector dg should be filled with the partial derivatives of g, viz, for a particular call one calculates
    • guess name of subroutine to evaluate the initial approximation for z(u(x)) and for dmval(u(x)) = vector of the mj-th derivatives of u(x) . it should have the heading [z,dmval]= guess (x ) note that this subroutine is used only if ipar(9) = 1 , and then all mstar components of z and ncomp components of dmval should be specified for any x,

      aleft <= x <= aright .

Description

this package solves a multi-point boundary value problem for a mixed order system of ode-s given by

       (m(i))
       u       =  f  ( x; z(u(x)) )      i = 1, ... ,ncomp
        i          i                     aleft < x  < aright,

       g  ( zeta(j); z(u(zeta(j))) ) = 0   j = 1, ... ,mstar
        j
      mstar = m(1)+m(2)+...+m(ncomp),

where

                                        t
             u = (u , u , ... ,u     )
                   1   2        ncomp

is the exact solution vector

              (mi)
             u     is the mi=m(i) th  derivative of u
              i                                      i

                                (1)        (m1-1)       (mncomp-1)
             z(u(x)) = ( u (x),u  (x),...,u    (x),...,u      (x) )
                          1     1          1            ncomp

              f (x,z(u))
               i

is a (generally) nonlinear function of z(u)=z(u(x)) .

              g (zeta(j);z(u))
               j

is a (generally) nonlinear function used to represent a boundary condition.

the boundary points satisfy

aleft <= zeta(1) <= .. <= zeta(mstar) <= aright .

the orders mi of the differential equations satisfy

1<=m(i)<=4 .

Examples

deff('df=dfsub(x,z)','df=[0,0,-6/x**2,-6/x]')
deff('f=fsub(x,z)','f=(1 -6*x**2*z(4)-6*x*z(3))/x**3')
deff('g=gsub(i,z)','g=[z(1),z(3),z(1),z(3)];g=g(i)')
deff('dg=dgsub(i,z)',['dg=[1,0,0,0;0,0,1,0;1,0,0,0;0,0,1,0]';
                      'dg=dg(i,:)'])
deff('[z,mpar]=guess(x)','z=0;mpar=0')// unused here

 //define trusol for testing purposes
deff('u=trusol(x)',[
   'u=0*ones(4,1)';
   'u(1) =  0.25*(10*log(2)-3)*(1-x) + 0.5 *( 1/x   + (3+x)*log(x) - x)'
   'u(2) = -0.25*(10*log(2)-3)       + 0.5 *(-1/x^2 + (3+x)/x      + log(x) - 1)'
   'u(3) = 0.5*( 2/x^3 + 1/x   - 3/x^2)'
   'u(4) = 0.5*(-6/x^4 - 1/x/x + 6/x^3)'])

fixpnt=0;m=4;
ncomp=1;aleft=1;aright=2;
zeta=[1,1,2,2];
ipar=zeros(1,11);
ipar(3)=1;ipar(4)=2;ipar(5)=2000;ipar(6)=200;ipar(7)=1;
ltol=[1,3];tol=[1.e-11,1.e-11];
res=aleft:0.1:aright;
z=bvode(res,ncomp,m,aleft,aright,zeta,ipar,ltol,tol,fixpnt,...
 fsub,dfsub,gsub,dgsub,guess)
z1=[];for x=res,z1=[z1,trusol(x)]; end;
z-z1

See Also

fort , link , external , ode , dassl ,

Author

u. ascher, department of computer science, university of british; columbia, vancouver, b. c., canada v6t 1w5; g. bader, institut f. angewandte mathematik university of heidelberg; im neuenheimer feld 294d-6900 heidelberg 1 ; ; Fortran subroutine colnew.f


bvodeS

Scilab Function
Last update : 08/02/2006

bvodeS - simplified call of bvode

Calling Sequence

z=bvodeS(x,m,n,a,b,fsub,gsub,zeta, [ystart,dfsub,dgsub,fixpnt,ndimf,ndimi,ltol,tol,ntol,nonlin, collpnt,subint,iprint,ireg,ifail])

Parameters

  • x : array of points at which approximations of the solution will be computed. The points x(i) must be given in increasing order.
  • m : array of orders for the differential equations given in fsub .
  • n : number of differential equations, length of m .
  • a : left end of solution interval, where a<=x(1).
  • b : right end of solution interval, where x($)<=b.
  • fsub : name of a Scilab function for evaluating the rhs of the differential equation system to be solved; fsub also may be a list for parameter transfer.
  • gsub : name of a Scilab function for evaluating the boundary conditions for the given differential equation system; gsub may also be a list as for fsub.
  • zeta : array of points at which the boundary or side conditions are given in increasing order. Each point must occur as often as boundary or side conditions are given there. Each side condition point other than a or b must be included in the array fixpnt. The length of zeta should be sum(m).
  • z : array of all derivatives of the solution functions up to the order m(i)-1 for the i-th function. (See the examples below.) The length of z should be sum(m).
  • ystart,dfsub,dgsub,fixpnt,ndimf,ndimi,ltol,tol,ntol,nonlin, collpnt,subint,iprint,ireg,ifail : These optional arguments may be called by name in any order in the form argument=name. The meaning of ystart to ireg is given in the bvode help page. The Scilab functions dfsub and dgsub for evaluating the Jacobians may also be lists for parameter transfer. The function ystart is called guess in bvode.
  • ifail : if ifail=1, all parameters needed for the call of bvode are displayed.

Description

This interface program simplifies the call of bvode , a program for the numerical solution of multi-point boundary value problems for mixed order systems of ordinary differential equations. The Scilab program bvode is adapted from the fortran program colnew. See the paper by U. Asher, J. Christiansen, and R.D. Russel: Collocation software for boundary-value ODE's, ACM Trans. Math. Soft. 7:209-222, 1981. The following examples should demonstrate not only how such systems can be solved with the help of bvodeS, but also should emphazise some important problems which occur with boundary value problems for ordinary ode's.

Examples

// 1. Modified example from help bvode.

// DE:  y1''''(x)=(1-6*x*x*y1'''(x)-6*x*y1''(x))/(y2(x)^3)
//         y2'(x)=1
// z=[y1 ; y1' ; y1'' ; y1''' ; y2]
// BV: y1(1)=0 y1''(1)=0
// BV: y1(2)=1 y1''(2)=0 y2(2)=2

function RhS=fsub(x,z)
  RhS=[(1-6*x*x*z(4)-6*x*z(3))/(z(5)^3);1]
endfunction

function g=gsub(i,z)
  g=[z(1) z(3) z(1)-1 z(3) z(5)-2]
  g=g(i)
endfunction

function [z,lhS]=ystart(x)
  z=zeros(5,1);z(5)=1;
  lhS=[0;1];
endfunction

n=2;
m=[4 1];
N=100;
a=1; b=2;
zeta=[a a b b b];
x=linspace(a,b,N);

ltol=4; // We want to change the default error for y1'''.
tol=1e-12;
tic()
z=bvodeS(x,m,n,a,b,fsub,gsub,zeta,ltol=ltol,tol=tol,ystart=ystart);
// Try tol=1e-14 etc.
toc()

function z=yex(x) // True solution
  z=zeros(5,1);
  z(1)=0.25*(10*log(2)-3)*(1-x)+0.5*(1/x+(3+x)*log(x)-x)+(x-1)
  z(2)=-0.25*(10*log(2)-3)+0.5*(-1/x^2+(3+x)/x+log(x)-1)+1
  z(3)=0.5*(2/x^3+1/x-3/x^2)
  z(4)=0.5*(-6/x^4-1/x/x+6/x^3)
  z(5)=x
endfunction

zex=[];for xx=x, zex=[zex yex(xx)]; end
scf(0); clf();
plot2d(x,abs(z-zex)',style=[1 2 3 5 6])
xtitle('Absolute error','x',' ')
legend(['z1(x)';'z2(x)';'z3(x)';'z4(x)';'z5(x)'])

// example #2. An eigenvalue problem

// y''(x)=-la*y(x)
// BV: y(0)=y'(0); y(1)=0
// Eigenfunctions and eigenvalues are y(x,n)=sin(s(n)*(1-x)), la(n)=s(n)^2,
// where s(n) are the zeros of f(s,n)=s+atan(s)-(n+1)*pi, n=0,1,2,...
// To get a third boundary condition, we choose y(0)=1
// (With y(x) also c*y(x) is a solution for each constant c.)
// We solve the following ode system:
// y''=-la*y
// la'=0
// BV: y(0)=y'(0), y(0)=1; y(1)=0
// z=[y(x) ; y'(x) ; la]

function rhs=fsub(x,z)
  rhs=[-z(3)*z(1);0]
endfunction

function g=gsub(i,z)
  g=[z(1)-z(2) z(1)-1 z(1)]
  g=g(i)
endfunction

// The following start function is good for the first 8 eigenfunctions.
function [z,lhs]=ystart(x,z,la0)
  z=[1;0;la0]
  lhs=[0;0]
endfunction

a=0;b=1;
m=[2;1];
n=2;
zeta=[a a b];
N=101;
x=linspace(a,b,N)';

// We have s(n)-(n+1/2)*pi -> 0 for n to infinity.
la0=input('n-th eigenvalue: n= ?');la0=(%pi/2+la0*%pi)^2;

z=bvodeS(x,m,n,a,b,fsub,gsub,zeta,ystart=list(ystart,la0));

clf()
plot2d(x,[z(1,:)' z(2,:)'],style=[5 1],axesflag=5)
xtitle(['Startvalue =  '+string(la0);'Eigenvalue = '+string(z(3,1))],'x',' ')
legend(['y(x)';'y''(x)'])

// example #3. A boundary value problem with more than one solution.

// DE: y''(x)=-exp(y(x))
// BV: y(0)=0; y(1)=0
// This boundary value problem has more than one solution.
// It is demonstrated how to find two of them with the help of
// some preinformation of the solutions y(x) to build the function ystart.
// z=[y(x);y'(x)]

a=0;b=1;m=2;n=1;
zeta=[a b];
N=101;
tol=1e-8*[1 1];
x=linspace(a,b,N);

function rhs=fsub(x,z),rhs=-exp(z(1));endfunction

function g=gsub(i,z)
  g=[z(1) z(1)]
  g=g(i)
endfunction

function [z,lhs]=ystart(x,z,M)
  //z=[4*x*(1-x)*M ; 4*(1-2*x)*M]
  z=[M;0]
  //lhs=[-exp(4*x*(1-x)*M)]
  lhs=0
endfunction

for M=[1 4]
   if M==1
      z=bvodeS(x,m,n,a,b,fsub,gsub,zeta,ystart=list(ystart,M),tol=tol);
   else
      z1=bvodeS(x,m,n,a,b,fsub,gsub,zeta,ystart=list(ystart,M),tol=tol);
   end
end

// Integrating the ode yield e.g. the two solutions yex and yex1.

function y=f(c),y=c.*(1-tanh(sqrt(c)/4).^2)-2;endfunction
c=fsolve(2,f);

function y=yex(x,c)
  y=log(c/2*(1-tanh(sqrt(c)*(1/4-x/2)).^2))
endfunction

function y=f1(c1), y=2*c1^2+tanh(1/4/c1)^2-1;endfunction
c1=fsolve(0.1,f1);

function y=yex1(x,c1)
  y=log((1-tanh((2*x-1)/4/c1).^2)/2/c1/c1)
endfunction

disp(norm(z(1,:)-yex(x)),'norm(yex(x)-z(1,:))= ')
disp(norm(z1(1,:)-yex1(x)),'norm(yex1(x)-z1(1,:))= ')

clf();
subplot(2,1,1)
plot2d(x,z(1,:),style=[5])
xtitle('Two different solutions','x',' ')
subplot(2,1,2)
plot2d(x,z1(1,:),style=[5])
xtitle(' ','x',' ')

// example #4. A multi-point boundary value problem.

// DE y'''(x)=1
// z=[y(x);y'(x);y''(x)]
// BV: y(-1)=2 y(1)=2
// Side condition: y(0)=1

a=-1;b=1;c=0;
// The side condition point c must be included in the array fixpnt.
n=1;
m=[3];

function rhs=fsub(x,z)
  rhs=1
endfunction

function g=gsub(i,z)
  g=[z(1)-2 z(1)-1 z(1)-2]
  g=g(i)
endfunction

N=10;
zeta=[a c b];
x=linspace(a,b,N);

z=bvodeS(x,m,n,a,b,fsub,gsub,zeta,fixpnt=c);

function y=yex(x)
y=x.^3/6+x.^2-x./6+1
endfunction

disp(norm(yex(x)-z(1,:)),'norm(yex(x)-z(1,:))= ')

See Also

bvode , ode , dassl ,

Author

Rainer von Seggern


dasrt

Scilab Function
Last update : 12/01/2004

dasrt - DAE solver with zero crossing

Calling Sequence

[r,nn,[,hd]]=dasrt(x0,t0,t [,atol,[rtol]],res [,jac],ng, surf [,info] [,hd])

Parameters

  • x0 : is either y0 ( ydot0 is estimated by dassl with zero as first estimate) or the matrix [y0 ydot0] . g(t,y0,ydot0) must be equal to zero. If you only know an estimate of ydot0 set info(7)=1
    • y0 : real column vector of initial conditions.
    • ydot0 : real column vector of the time derivative of y at t0 (may be an estimate).
  • t0 : real number is the initial instant.
  • t : real scalar or vector. Gives instants for which you want the solution. Note that you can get solution at each dassl's step point by setting info(2)=1 .
  • nn : a vector with two entries [times num] times is the value of the time at which the surface is crossed, num is the number of the crossed surface
  • atol,rtol : real scalars or column vectors of same size as y . atol,rtol give respectively absolute and relative error tolerances of solution. If vectors the tolerances are specified for each component of y .
  • res : external (function or list or string). Computes the value of g(t,y,ydot) .
    • function

      : Its calling sequence must be [r,ires]=res(t,y,ydot) and res must return the residue r=g(t,y,ydot) and error flag ires . ires = 0 if res succeeds to compute r , =-1 if residue is locally not defined for (t,y,ydot) , =-2 if parameters are out of admissible range.

    • list : it must be as follows:

list(res,x1,x2,...)

      where the calling sequence of the function res is now

r=res(t,y,ydot,x1,x2,...)

      res still returns r=g(t,y,ydot) as a function of (t,y,ydot,x1,x2,...) .

    • string : it must refer to the name of a fortran subroutine (see source code of fresd.f ).
  • jac : external (function or list or string). Computes the value of dg/dy+cj*dg/dydot for a given value of parameter cj
    • function : Its calling sequence must be r=jac(t,y,ydot,cj) and the jac function must return r=dg(t,y,ydot)/dy+cj*dg(t,y,ydot)/dydot where cj is a real scalar
    • list : it must be as follows

list(jac,x1,x2,...)

      where the calling sequence of the function jac is now

r=jac(t,y,ydot,x1,x2,...)

      jac still returns dg/dy+cj*dg/dydot as a function of (t,y,ydot,cj,x1,x2,...) .

    • character string : it must refer to the name of a fortran subroutine (see source code of jacdd.f ).
  • surf : external (function or list or string). Computes the value of the column vector surf(t,y) with ng components. Each component defines a surface.
    • function : Its calling sequence must be surf(t,y)
    • list : it must be as follows

list(surf,x1,x2,...)

      where the calling sequence of the function surf is now

r=surf(t,y,x1,x2,...)
    • character string : it must refer to the name of a fortran subroutine (see source code of fsurfd.f ) in directory SCDIR/default
  • info : list which contains 7 elements, default value is list([],0,[],[],[],0,0)
    • info(1) : real scalar which gives the maximum time for which g is allowed to be evaluated or an empty matrix [] if no limits imposed for time.
    • info(2) : flag which indicates if dassl returns its intermediate computed values ( flag=1 ) or only the user specified time point values ( flag=0 ).
    • info(3) : 2 components vector which give the definition [ml,mu] of band matrix computed by jac ; r(i - j + ml + mu + 1,j) = "dg(i)/dy(j)+cj*dg(i)/dydot(j)" . If jac returns a full matrix set info(3)=[] .
    • info(4) : real scalar which gives the maximum step size. Set info(4)=[] if no limitation.
    • info(5) : real scalar which gives the initial step size. Set info(4)=[] if not specified.
    • info(6) : set info(6)=1 if the solution is known to be non negative, else set info(6)=0 .
    • info(7) : set info(7)=1 if ydot0 is just an estimation, info(7)=0 if g(t0,y0,ydot0)=0 .
  • hd : real vector which allows to store the dassl context and to resume integration
  • r : real matrix . Each column is the vector [t;x(t);xdot(t)] where t is time index for which the solution had been computed

Description

Solution of the implicit differential equation

    g(t,y,ydot)=0
    y(t0)=y0  and   ydot(t0)=ydot0

Returns the surface crossing instants and the number of the surface reached in nn .

Detailed examples can be found in SCIDIR/tests/dassldasrt.tst

Examples

//dy/dt = ((2*log(y)+8)/t -5)*y,  y(1) = 1,  1<=t<=6
//g1 = ((2*log(y)+8)/t - 5)*y
//g2 = log(y) - 2.2491
y0=1;t=2:6;t0=1;y0d=3;
atol=1.d-6;rtol=0;ng=2;

deff('[delta,ires]=res1(t,y,ydot)','ires=0;delta=ydot-((2*log(y)+8)/t-5)*y')
deff('[rts]=gr1(t,y)','rts=[((2*log(y)+8)/t-5)*y;log(y)-2.2491]')

[yy,nn]=dasrt([y0,y0d],t0,t,atol,rtol,res1,ng,gr1);
//(Should return nn=[2.4698972 2])

See Also

ode , dassl , impl , fort , link , external ,


dassl

Scilab Function
Last update : 12/01/2004

dassl - differential algebraic equation

Calling Sequence

[r [,hd]]=dassl(x0,t0,t [,atol,[rtol]],res [,jac] [,info] [,hd])

Parameters

  • x0 : is either y0 ( ydot0 is estimated by dassl with zero as first estimate) or the matrix [y0 ydot0] . g(t,y0,ydot0) must be equal to zero. If you only know an estimate of ydot0 set info(7)=1
    • y0 : real column vector of initial conditions.
    • ydot0 : real column vector of the time derivative of y at t0 (may be an estimate).
  • t0 : real number is the initial instant.
  • t : real scalar or vector. Gives instants for which you want the solution. Note that you can get solution at each dassl's step point by setting info(2)=1 .
  • atol,rtol : real scalars or column vectors of same size as y . atol,rtol give respectively absolute and relative error tolerances of solution. If vectors the tolerances are specified for each component of y .
  • res : external (function or list or string). Computes the value of g(t,y,ydot) .
    • function

      : Its calling sequence must be [r,ires]=res(t,y,ydot) and res must return the residue r=g(t,y,ydot) and error flag ires . ires = 0 if res succeeds to compute r , =-1 if residue is locally not defined for (t,y,ydot) , =-2 if parameters are out of admissible range.

    • list : it must be as follows:

list(res,x1,x2,...)

      where the calling sequence of the function res is now

r=res(t,y,ydot,x1,x2,...)

      res still returns r=g(t,y,ydot) as a function of (t,y,ydot,x1,x2,...) .

    • string : it must refer to the name of a fortran subroutine (see source code of of Ex-dassl.f in routines/defaut/).
  • jac : external (function or list or string). Computes the value of dg/dy+cj*dg/dydot for a given value of parameter cj
    • function : Its calling sequence must be r=jac(t,y,ydot,cj) and the jac function must return r=dg(t,y,ydot)/dy+cj*dg(t,y,ydot)/dydot where cj is a real scalar
    • list : it must be as follows

list(jac,x1,x2,...)

      where the calling sequence of the function jac is now

r=jac(t,y,ydot,x1,x2,...)

      jac still returns dg/dy+cj*dg/dydot as a function of (t,y,ydot,cj,x1,x2,...) .

    • character string : it must refer to the name of a fortran subroutine (see source code of Ex-dassl.f in routines/defaut/).
  • info : list which contains 7 elements, default value is list([],0,[],[],[],0,0);
    • info(1) : real scalar which gives the maximum time for which g is allowed to be evaluated or an empty matrix [] if no limits imposed for time.
    • info(2) : flag which indicates if dassl returns its intermediate computed values ( flag=1 ) or only the user specified time point values ( flag=0 ).
    • info(3) : 2 components vector which give the definition [ml,mu] of band matrix computed by jac ; r(i - j + ml + mu + 1,j) = "dg(i)/dy(j)+cj*dg(i)/dydot(j)" . If jac returns a full matrix set info(3)=[] .
    • info(4) : real scalar which gives the maximum step size. Set info(4)=[] if no limitation.
    • info(5) : real scalar which gives the initial step size. Set info(4)=[] if not specified.
    • info(6) : set info(6)=1 if the solution is known to be non negative, else set info(6)=0 .
    • info(7) : set info(7)=1 if ydot0 is just an estimation, info(7)=0 if g(t0,y0,ydot0)=0 .
  • hd : real vector which allows to store the dassl context and to resume integration
  • r : real matrix . Each column is the vector [t;x(t);xdot(t)] where t is time index for which the solution had been computed

Description

Solution of the implicit differential equation

    g(t,y,ydot)=0
    y(t0)=y0  and   ydot(t0)=ydot0

Detailed examples are given in SCIDIR/tests/dassldasrt.tst

Examples

 deff('[r,ires]=chemres(t,y,yd)',[
         'r(1)=-0.04*y(1)+1d4*y(2)*y(3)-yd(1);';
         'r(2)=0.04*y(1)-1d4*y(2)*y(3)-3d7*y(2)*y(2)-yd(2);'
         'r(3)=y(1)+y(2)+y(3)-1;'
         'ires=0']);
 deff('[pd]=chemjac(x,y,yd,cj)',[
         'pd=[-0.04-cj , 1d4*y(3)               , 1d4*y(2);';
         '0.04    ,-1d4*y(3)-2*3d7*y(2)-cj ,-1d4*y(2);';
         '1       , 1                      , 1       ]'])

y0=[1;0;0];
yd0=[-0.04;0.04;0];
t=[1.d-5:0.02:.4,0.41:.1:4,40,400,4000,40000,4d5,4d6,4d7,4d8,4d9,4d10];

y=dassl([y0,yd0],0,t,chemres);

info=list([],0,[],[],[],0,0);
info(2)=1;
y=dassl([y0,yd0],0,4d10,chemres,info);
y=dassl([y0,yd0],0,4d10,chemres,chemjac,info);

See Also

ode , dasrt , impl , fort , link , external ,


datafit

Scilab Function
Last update : 13/12/2005

datafit - Parameter identification based on measured data

Calling Sequence

[p,err]=datafit([imp,] G [,DG],Z [,W],[contr],p0,[algo],[df0,[mem]],
[work],[stop],['in'])

Parameters

  • imp : scalar argument used to set the trace mode. imp=0 nothing (execpt errors) is reported, imp=1 initial and final reports, imp=2 adds a report per iteration, imp>2 add reports on linear search. Warning, most of these reports are written on the Scilab standard output.
  • G : function descriptor (e=G(p,z), e: ne x 1, p: np x 1, z: nz x 1)
  • DG : partial of G wrt p function descriptor (optional; S=DG(p,z), S: ne x np)
  • Z : matrix [z_1,z_2,...z_n] where z_i (nz x 1) is the ith measurement
  • W : weighting matrix of size ne x ne (optional; defaut no ponderation)
  • contr : 'b',binf,bsup with binf and bsup real vectors with same dimension as p0 . binf and bsup are lower and upper bounds on p .
  • p0 : initial guess (size np x 1)
  • algo : 'qn' or 'gc' or 'nd' . This string stands for quasi-Newton (default), conjugate gradient or non-differentiable respectively. Note that 'nd' does not accept bounds on x ).
  • df0 : real scalar. Guessed decreasing of f at first iteration. ( df0=1 is the default value).
  • mem : integer, number of variables used to approximate the Hessian, ( algo='gc' or 'nd' ). Default value is around 6.
  • stop : sequence of optional parameters controlling the convergence of the algorithm. stop= 'ar',nap, [iter [,epsg [,epsf [,epsx]]]]
    • "ar" : reserved keyword for stopping rule selection defined as follows:
    • nap : maximum number of calls to fun allowed.
    • iter : maximum number of iterations allowed.
    • epsg : threshold on gradient norm.
    • epsf : threshold controlling decreasing of f
    • epsx : threshold controlling variation of x . This vector (possibly matrix) of same size as x0 can be used to scale x .
  • "in" : reserved keyword for initialization of parameters used when fun in given as a Fortran routine (see below).
  • p : Column vector, optimal solution found
  • err : scalar, least square error.

Description

datafit is used for fitting data to a model. For a given function G(p,z) , this function finds the best vector of parameters p for approximating G(p,z_i)=0 for a set of measurement vectors z_i . Vector p is found by minimizing G(p,z_1)'WG(p,z_1)+G(p,z_2)'WG(p,z_2)+...+G(p,z_n)'WG(p,z_n)

datafit is an improved version of fit_dat .

Examples

//generate the data
function y=FF(x,p),y=p(1)*(x-p(2))+p(3)*x.*x,endfunction
X=[];Y=[];
pg=[34;12;14] //parameter used to generate data
for x=0:.1:3, Y=[Y,FF(x,pg)+100*(rand()-.5)];X=[X,x];end
Z=[Y;X];

//The criterion function
function e=G(p,z),
   y=z(1),x=z(2);
   e=y-FF(x,p),
endfunction

//Solve the problem
p0=[3;5;10]
[p,err]=datafit(G,Z,p0);

scf(0);clf()
plot2d(X,FF(X,pg),5) //the curve without noise
plot2d(X,Y,-1)  // the noisy data
plot2d(X,FF(X,p),12) //the solution

//the gradient of the criterion function
function s=DG(p,z),
   a=p(1),b=p(2),c=p(3),y=z(1),x=z(2),
   s=-[x-b,-a,x*x]
endfunction

[p,err]=datafit(G,DG,Z,p0);
scf(1);clf()
plot2d(X,FF(X,pg),5) //the curve without noise
plot2d(X,Y,-1)  // the noisy data
plot2d(X,FF(X,p),12) //the solution

See Also

lsqrsolve , optim , leastsq ,


derivative

Last update : 07/02/2006

derivative - approximate derivatives of a function

Calling Sequence

derivative(F,x)
[J [,H]] = derivative(F,x [,h ,order ,H_form ,Q])

Parameters

  • F : a Scilab function F: R^n --> R^m or a list(F,p1,...,pk) , where F is a scilab function in the form y=F(x,p1,...,pk) , p1, ..., pk being any scilab objects (matrices, lists,...).
  • x : real column vector of dimension n.
  • h : (optional) real, the stepsize used in the finite difference approximations.
  • order : (optional) integer, the order of the finite difference formula used to approximate the derivatives (order = 1,2 or 4, default is order=2 ).
  • H_form : (optional) string, the form in which the Hessean will be returned. Possible forms are:
    • H_form='default' : H is a m x ( n^2 ) matrix ; in this form, the k-th row of H corresponds to the Hessean of the k-th component of F, given as the following row vector :

  [ d(grad(F_k))/dx_1 | ..... | d(grad(F_k))/dx_n ]

      ((grad(F_k) being a row vector).

    • H_form='blockmat' : H is a (mxn) x n block matrix : the classic Hessean matrices (of each component of F) are stacked by row (H = [H1 ; H2 ; ... ; Hm] in scilab syntax).
    • H_form='hypermat' : H is a n x n matrix for m=1, and a n x n x m hypermatrix otherwise. H(:,:,k) is the classic Hessean matrix of the k-th component of F.
  • Q : (optional) real matrix, orthogonal (default is eye(n,n)).

Description

Numerical approximation of the first and second derivatives of a function F: R^n --> R^m at the point x. The Jacobian is computed by approximating the directional derivatives of the components of F in the direction of the columns of Q. (For m=1, v=Q(:,k) : grad(F(x))*v = Dv(F(x)).) The second derivatives are computed by composition of first order derivatives. If H is given in its default form the Taylor series of F(x) up to terms of second order is given by :

  F(x+dx) = F(x) + J(x)*dx + 1/2*H(x)*(dx .*. dx) + ...

(([J,H]=derivative(F,x,H_form='default'), J=J(x), H=H(x).)

Remarks

Numerical approximation of derivatives is generally an unstable process. The step size h must be small to get a low error but if it is too small floating point errors will dominate by cancellation. As a rule of thumb don't change the default step size. To work around numerical difficulties one may also change the order and/or choose different orthogonal matrices Q (the default is eye(n,n)), especially if the approximate derivatives are used in optimization routines. All the optional arguments may also be passed as named arguments, so that one can use calls in the form :

derivative(F, x, H_form = "hypermat")
derivative(F, x, order = 4) etc.

Examples

  function y=F(x)
   y=[sin(x(1)*x(2))+exp(x(2)*x(3)+x(1)) ; sum(x.^3)];
 endfunction
 function y=G(x,p)
   y=[sin(x(1)*x(2)*p)+exp(x(2)*x(3)+x(1)) ; sum(x.^3)];
 endfunction

 x=[1;2;3];[J,H]=derivative(F,x,H_form='blockmat')

 n=3;
 // form an orthogonal matrix :
 nu=0; while nu<n, [Q,nu]=colcomp(rand(n,n)); end
 for i=[1,2,4]
    [J,H]=derivative(F,x,order=i,H_form='blockmat',Q=Q);
    mprintf("order= %d \n",i);
    H,
 end

 p=1;h=1e-3;
 [J,H]=derivative(list(G,p),x,h,2,H_form='hypermat');H
 [J,H]=derivative(list(G,p),x,h,4,Q=Q);H

 // Taylor series example:
 dx=1e-3*[1;1;-1];
 [J,H]=derivative(F,x);
 F(x+dx)
 F(x+dx)-F(x)
 F(x+dx)-F(x)-J*dx
 F(x+dx)-F(x)-J*dx-1/2*H*(dx .*. dx)

 // A trivial example
 function y=f(x,A,p,w), y=x'*A*x+p'*x+w; endfunction
 // with Jacobian and Hessean given by J(x)=x'*(A+A')+p', and H(x)=A+A'.
 A = rand(3,3); p = rand(3,1); w = 1;
 x = rand(3,1);
 [J,H]=derivative(list(f,A,p,w),x,h=1,H_form='blockmat')
 // Since f(x) is quadratic in x, approximate derivatives of order=2 or 4 by finite
 // differences should be exact for all h~=0. The apparent errors are caused by
 // cancellation in the floating point operations, so a "big" h is choosen.
 // Comparison with the exact matrices:
 Je = x'*(A+A')+p'
 He = A+A'
 clean(Je - J)
 clean(He - H)

See Also

numdiff , derivat ,

Author

Rainer von Seggern, Bruno Pincon


fit_dat

Scilab Function
Last update : 12/01/2004

fit_dat - Parameter identification based on measured data

Calling Sequence

[p,err]=fit_dat(G,p0,Z [,W] [,pmin,pmax] [,DG])

Parameters

  • G : Scilab function (e=G(p,z), e: nex1, p: npx1, z: nzx1)
  • p0 : initial guess (size npx1)
  • Z : matrix [z_1,z_2,...z_n] where z_i (nzx1) is the ith measurement
  • W : weighting matrix of size nexne (optional; default 1)
  • pmin : lower bound on p (optional; size npx1)
  • pmax : upper bound on p (optional; size npx1)
  • DG : partial of G wrt p (optional; S=DG(p,z), S: nexnp)

Description

fit_dat is used for fitting data to a model. For a given function G(p,z), this function finds the best vector of parameters p for approximating G(p,z_i)=0 for a set of measurement vectors z_i. Vector p is found by minimizing G(p,z_1)'WG(p,z_1)+G(p,z_2)'WG(p,z_2)+...+G(p,z_n)'WG(p,z_n)

Examples

deff('y=FF(x)','y=a*(x-b)+c*x.*x')
X=[];Y=[];
a=34;b=12;c=14;for x=0:.1:3, Y=[Y,FF(x)+100*(rand()-.5)];X=[X,x];end
Z=[Y;X];
deff('e=G(p,z)','a=p(1),b=p(2),c=p(3),y=z(1),x=z(2),e=y-FF(x)')
[p,err]=fit_dat(G,[3;5;10],Z)
xset('window',0)
xbasc();
plot2d(X',Y',-1)
plot2d(X',FF(X)',5,'002')
a=p(1),b=p(2),c=p(3);plot2d(X',FF(X)',12,'002')

a=34;b=12;c=14;
deff('s=DG(p,z)','y=z(1),x=z(2),s=-[x-p(2),-p(1),x*x]')
[p,err]=fit_dat(G,[3;5;10],Z,DG)
xset('window',1)
xbasc();
plot2d(X',Y',-1)
plot2d(X',FF(X)',5,'002')
a=p(1),b=p(2),c=p(3);plot2d(X',FF(X)',12,'002')

See Also

optim , datafit ,


fsolve

Scilab Function
Last update : 17/06/2004

fsolve - résout un système d'équations non-linéaires

Calling Sequence

[x [,v [,info]]]=fsolve(x0,fct [,fjac] [,tol])

Parameters

  • x0 : vecteur réel (vecteur initial).
  • fct : fonction externe (fonction Scilab ou chaîne de caractères ou liste).
  • fjac : fonction externe (fonction Scilab ou chaîne de caractères ou liste).
  • tol : scalaire. Tolérance : l'algorithme s'arrête lorsque l'erreur relative estimée entre x et la solution est inférieure à tol ( tol=1.d-10 par défaut).
  • x : vecteur réel (solution estimée).
  • v : vecteur réel (valeur de la fonction en x).
  • info : indicateur d'arrêt de l'algorithme
    • 0 : paramètres d'entrée incorrects
    • 1 : l'erreur relative estimée entre x et la solution est inférieure à tol
    • 2 : nombre d'appels à fct
    • 3 : tol est trop petit. L'algorithme stationne.
    • 4 : les itérations n'améliorent pas assez la solution.

Description

Résout un système de n équations non linéaires à n inconnues avec un algorithme du type méthode hybride de Powell. La Jacobienne peut être fournie (c'est fortement conseillé).

      0 = fct(x)

fct est une fonction "externe" Cette fonction renvoie v=fct(x) pour x donné.

La séquence d'appel de fct est :

      [v]=fct(x).

Si fct est une chaîne de caractères, elle désigne le nom d'une subroutine Fortran ou C liée dynamiquement à Scilab, avec comme liste d'appel Fortran :

      fct(n,x,v,iflag)
      integer n,iflag
      double precision x(n),v(n)

ou alors pour une routine C :

      fct(int *n, double x[],double v[],int *iflag)

(voir link ).

jac est une fonction "externe" aussi. Cette fonction renvoie v=d(fct)/dx (x) pour x donné.

La séquence d'appel de jac est :

      [v]=jac(x).

Si jac est une chaîne de caractères, elle désigne le nom d'une subroutine Fortran ou C liée dynamiquement à Scilab. Les séquences d'appel sont les mêmes que pour fct (attention v doit être un tableau n x n).

Examples

    // un exemple simple
    a=[1,7;2,8];b=[10;11];
    deff('[y]=fsol1(x)','y=a*x+b');
    deff('[y]=fsolj1(x)','y=a');
    [xres]=fsolve([100;100],fsol1);
    a*xres+b
    [xres]=fsolve([100;100],fsol1,fsolj1);
    a*xres+b
    // voir routines/default/Ex-fsolve.f
    [xres]=fsolve([100;100],'fsol1','fsolj1',1.e-7);
    a*xres+b

See Also

external , quapro , linpro , optim ,


impl

Scilab Function
Last update : 17/11/2004

impl - differential algebraic equation

Calling Sequence

y=impl([type],y0,ydot0,t0,t [,atol, [rtol]],res,adda [,jac])

Parameters

  • y0,ydot0 : real vectors or matrix (initial conditions).
  • t0 : real scalar (initial time).
  • t : real vector (times at which the solution is computed).
  • res,adda : externals (function or character string or list).
  • type : string 'adams' or 'stiff'
  • atol,rtol : real scalar or real vector of the same size as as y .
  • jac : external (function or character string or list).

Description

Solution of the linear implicit differential equation

A(t,y) dy/dt=g(t,y), y(t0)=y0

t0 is the initial instant, y0 is the vector of initial conditions Vector ydot0 of the time derivative of y at t0 must also be given. r The input res is an external i.e. a function with specified syntax, or the name a Fortran subroutine or a C function (character string) with specified calling sequence or a list.

If res is a function, its syntax must be as follows:

r = res(t,y,ydot)

where t is a real scalar (time) and y and ydot are real vector (state and derivative of the state). This function must return r=g(t,y)-A(t,y)*ydot .

If res is a character string, it refers to the name of a Fortran subroutine or a C function. See SCIDIR/routines/default/Ex-impl.f for an example to do that.

res can also be a list: see the help of ode .

The input adda is also an external.

If adda is a function, its syntax must be as follows:

r = adda(t,y,p)

and it must return r=A(t,y)+p where p is a matrix to be added to A(t,y) .

If adda is a character string, it refers to the name of a Fortran subroutine or a C function. See SCIDIR/routines/default/Ex-impl.f for an example to do that.

adda can also be a list: see the help of ode .

The input jac is also an external.

If jac is a function, its syntax must be as follows:

j = jac(t,y,ydot)

and it must return the Jacobian of r=g(t,y)-A(t,y)*ydot with respect to y .

If jac is a character string, it refers to the name of a Fortran subroutine or a C function. See SCIDIR/routines/default/Ex-impl.f for an example to do that.

jac can also be a list: see the help of ode .

Examples

y=impl([1;0;0],[-0.04;0.04;0],0,0.4,'resid','aplusp');
// Using hot restart
//[x1,w,iw]=impl([1;0;0],[-0.04;0.04;0],0,0.2,'resid','aplusp');
// hot start from previous call
//[x1]=impl([1;0;0],[-0.04;0.04;0],0.2,0.4,'resid','aplusp',w,iw);
//maxi(abs(x1-x))

See Also

dassl , ode , external ,


int2d

Scilab Function
Last update : 12/01/2004

int2d - definite 2D integral by quadrature and cubature method

Calling Sequence

[I,err]=int2d(X,Y,f [,params])

Parameters

  • X : a 3 by N array containing the abscissae of the vertices of the N triangles.
  • Y : a 3 by N array containing the ordinates of the vertices of the N triangles.
  • f : external (function or list or string) defining the integrand f(u,v) ;
  • params : real vector [tol, iclose, maxtri, mevals, iflag] . default value is [1.d-10, 1, 50, 4000, 1] .
    • tol :the desired bound on the error. If iflag=0 , tol is interpreted as a bound on the relative error; if iflag= 1, the bound is on the absolute error.
    • iclose :an integer parameter that determines the selection of LQM0 or LQM1 methods. If iclose=1 then LQM1 is used. Any other value of iclose causes LQM0 to be used. LQM0 uses function values only at interior points of the triangle. LQM1 is usually more accurate than LQM0 but involves evaluating the integrand at more points including some on the boundary of the triangle. It will usually be better to use LQM1 unless the integrand has singularities on the boundary of the triangle.
    • maxtri :the maximum number of triangles in the final triangulation of the region
    • mevals : the maximum number of function evaluations to be allowed. This number will be effective in limiting the computation only if it is less than 94* maxtri when LQM1 is specified or 56* maxtri when LQM0 is specified.
    • iflag :
  • I : the integral value
  • err : the estimated error

Description

int2d computes the two-dimensional integral of a function f over a region consisting of n triangles. A total error estimate is obtained and compared with a tolerance - tol - that is provided as input to the subroutine. The error tolerance is treated as either relative or absolute depending on the input value of iflag . A 'Local Quadrature Module' is applied to each input triangle and estimates of the total integral and the total error are computed. The local quadrature module is either subroutine LQM0 or subroutine LQM1 and the choice between them is determined by the value of the input variable iclose .

If the total error estimate exceeds the tolerance, the triangle with the largest absolute error is divided into two triangles by a median to its longest side. The local quadrature module is then applied to each of the subtriangles to obtain new estimates of the integral and the error. This process is repeated until either (1) the error tolerance is satisfied, (2) the number of triangles generated exceeds the input parameter maxtri , (3) the number of integrand evaluations exceeds the input parameter mevals , or (4) the function senses that roundoff error is beginning to contaminate the result.

Examples

X=[0,0;1,1;1,0];
Y=[0,0;0,1;1,1];
deff('z=f(x,y)','z=cos(x+y)')
[I,e]=int2d(X,Y,f)
// computes the integrand over the square [0 1]x[0 1]

See Also

intc , intl , int3d , intg , mesh2d ,

Author

Fortran routine twodq Authors: Kahaner,D.K.,N.B.S., Rechard,O.W.,N.B.S.,; Barnhill,Robert,Univ. of UTAH


int3d

Scilab Function
Last update : 12/01/2004

int3d - definite 3D integral by quadrature and cubature method

Calling Sequence

[result,err]=int3d(X,Y,Z,f [,nf[,params]])

Parameters

  • X : a 4 by NUMTET array containing the abscissae of the vertices of the NUMTET tetrahedrons.
  • Y : a 4 by NUMTET array containing the ordinates of the vertices of the NUMTET tetrahedrons.
  • Z : a 4 by NUMTET array containing the third coordinates of the vertices of the NUMTET tetrahedrons.
  • f : external (function or list or string) defining the integrand f(xyz,nf) , where xyz is the vector of a point coordinates and nf the number functions
  • nf : the number of function to integate (default is 1)
  • params : real vector [minpts, maxpts, epsabs, epsrel] . default value is [0, 1000, 0.0, 1.d-5] .
    • epsabs : Desired bound on the absolute error.
    • epsrel : Desired bound on the relative error.
    • minpts : Minimum number of function evaluations.
    • maxpts : Maximum number of function evaluations. The number of function evaluations over each subregion is 43
  • result : the integral value,or vector of the integral values.
  • err : Estimates of absolute errors.

Description

The function calculates an approximation to a given vector of definite integrals

I  I  I (F ,F ,...,F )      dx(3)dx(2)dx(1),
          1  2      numfun

where the region of integration is a collection of NUMTET tetrahedrons and where

F = F (X(1),X(2),X(3)), J = 1,2,...,NUMFUN.
 J   J

A globally adaptive strategy is applied in order to compute approximations result(k) hopefully satisfying, for each component of I, the following claim for accuracy: ABS(I(K)-RESULT(K))<=MAX(EPSABS,EPSREL*ABS(I(K)))

int3d repeatedly subdivides the tetrahedrons with greatest estimated errors and estimates the integrals and the errors over the new subtetrahedrons until the error request is met or MAXPTS function evaluations have been used.

A 43 point integration rule with all evaluation points inside the tetrahedron is applied. The rule has polynomial degree 8.

If the values of the input parameters EPSABS or EPSREL are selected great enough, an integration rule is applied over each tetrahedron and the results are added up to give the approximations RESULT(K) . No further subdivision of the tetrahedrons will then be applied.

When int3d computes estimates to a vector of integrals, all components of the vector are given the same treatment. That is, I(Fj) and I(Fk) for

j not equal to k , are estimated with the same subdivision of the region of integration. For integrals with enough similarity, we may save time by applying int3d to all integrands in one call. For integrals that varies continuously as functions of some parameter, the estimates produced by int3d will also vary continuously when the same subdivision is applied to all components. This will generally not be the case when the different components are given separate treatment.

On the other hand this feature should be used with caution when the different components of the integrals require clearly different subdivisions.

References

Fortran routine dcutet.f

Examples

X=[0;1;0;0];
Y=[0;0;1;0];
Z=[0;0;0;1];
[RESULT,ERROR]=int3d(X,Y,Z,'int3dex')
// computes the integrand exp(x*x+y*y+z*z) over the
//tetrahedron (0.,0.,0.),(1.,0.,0.),(0.,1.,0.),(0.,0.,1.)

//integration over a cube  -1<=x<=1;-1<=y<=1;-1<=z<=1

//  bottom  -top-     right    -left-   front   -rear-
X=[ 0, 0,    0, 0,    0, 0,    0, 0,    0, 0,    0, 0;
   -1,-1,   -1,-1,    1, 1,   -1,-1,   -1,-1,   -1,-1;
    1,-1,    1,-1,    1, 1,   -1,-1,    1,-1,    1,-1;
    1, 1,    1, 1,    1, 1,   -1,-1,    1, 1,    1, 1];
Y=[ 0, 0,    0, 0,    0, 0,    0, 0,    0, 0,    0, 0;
   -1,-1,   -1,-1,   -1, 1,   -1, 1,   -1,-1,    1, 1;
   -1, 1,   -1, 1,    1, 1,    1, 1,   -1,-1,    1, 1;
    1, 1,    1, 1,   -1,-1,   -1,-1,   -1,-1,    1, 1];
Z=[ 0, 0,    0, 0,    0, 0,    0, 0,    0, 0,    0, 0;
   -1,-1,    1, 1,   -1, 1,   -1, 1,   -1,-1,   -1,-1;
   -1,-1,    1, 1,   -1,-1,   -1,-1,   -1, 1,   -1, 1;
   -1,-1,    1, 1,    1,-1,    1,-1,    1, 1,    1, 1];

function v=f(xyz,numfun),v=exp(xyz'*xyz),endfunction
[result,err]=int3d(X,Y,Z,f,1,[0,100000,1.d-5,1.d-7])

function v=f(xyz,numfun),v=1,endfunction
[result,err]=int3d(X,Y,Z,f,1,[0,100000,1.d-5,1.d-7])

See Also

intc , intl , int2d ,

Authors

Jarle Berntsen The Computing Centre, University of Bergen, Thormohlens gt. 55, N-5008 Bergen, Norway Phone.. 47-5-544055 Email.. jarle@eik.ii.uib.no,
Ronald Cools Dept. of Computer Science, Katholieke Universiteit Leuven, Celestijnenlaan 200A, B-3030 Heverlee, Belgium Phone.. 32-16-201015 (3562) Email.. ronald@cs.kuleuven.ac.be,
Terje O. Espelid Department of Informatics, University of Bergen, Thormohlens gt. 55, N-5008 Bergen, Norway Phone.. 47-5-544180 Email.. terje@eik.ii.uib.no


intc

Scilab Function
Last update : 12/01/2004

intc - Cauchy integral

Calling Sequence

[y]=intc(a,b,f)

Parameters

  • a,b : two complex numbers
  • f : "external" function

Description

If f is a complex-valued function, intc(a,b,f) computes the integral from a to b of f(z)dz along the straight line a b of the complex plane.

See Also

intg , intl ,

Author

F. D.


intg

Scilab Function
Last update : 14/12/2005

intg - intégration numérique adaptative

Calling Sequence

[v,err]=intg(a,b,f [,ea [,er])

Parameters

  • a,b : nombres réels
  • f : fonction externe (fonction Scilab ou chaîne de caractères ou liste).
  • ea, er : nombres réels
  • ea : erreur absolue désirée (1.d-14 par défaut)
  • er : erreur relative (1.d-8 par défaut)
  • err : estimation de l'erreur absolue sur le résultat

Description

intg(a,b,f) approche l'intégrale de a à b de f(t)dt . La fonction f doit être continue.

L'évaluation satisfait si possible abs(I-v)<= max(ea,er*abs(I)) où I représente la valeur exacte de l'intégrale.

f est une fonction externe :

Si f est une fonction Scilab elle doit avoir la liste d'appel : y = f(t)

Si f est une liste, cette liste doit avoir la structure suivante : list(f,x1,x2,...) où f est une fonction Scilab avec la liste d'appel : f(t,x1,x2,...) .

Si f est une chaîne de caractères, ce paramètre désigne le nom d'un fonction Fortran ou d'une procédure C ayant une liste d'appel fixée:

Dans le cas Fortran la liste d'appel doit être: double precision function f(x) où x est aussi un nombre double precision.

Dans la cas C la liste d'appel doit être: double f(double *x) .

Examples

    //External écrit en Scilab
    function y=f(x),y=x*sin(30*x)/sqrt(1-((x/(2*%pi))^2)),endfunction
    exact=-2.5432596188;
    I=intg(0,2*%pi,f)
    abs(exact-I)

    //External écrit en Scilab avec un argument
    function y=f1(x,w),y=x*sin(w*x)/sqrt(1-((x/(2*%pi))^2)),endfunction
    I=intg(0,2*%pi,list(f1,30))
    abs(exact-I)

    // External écrit en Fortran (un compilateur Fortran est nécessaire)
    // Ecriture du code fortran
    F=['      double precision function ffun(x)'
    '      double precision x,pi'
    '      pi=3.14159265358979312d+0'
    '      ffun=x*sin(30.0d+0*x)/sqrt(1.0d+0-(x/(2.0d+0*pi))**2)'
    '      return'
    '      end'];
    mputl(F,TMPDIR+'/ffun.f')
    // compilation du code Fortran
    l=ilib_for_link('ffun','ffun.o',[],'f',TMPDIR+'/Makefile');
    // link incrémental
    link(l,'ffun','f')
    // integration de la fonction
    I=intg(0,2*%pi,'ffun')
    abs(exact-I)

    // External écrit en C (un compilateur C est nécessaire)
    // Ecriture du code C
    C=['#include <math.h>'
    'double cfun(double *x)'
    '{'
    '  double y,pi=3.14159265358979312;'
    '  y=*x/(2.0e0*pi);'
    '  return *x*sin(30.0e0**x)/sqrt(1.0e0-y*y);'
    '}'];
    mputl(C,TMPDIR+'/cfun.c')
    // compilation du code C
    l=ilib_for_link('cfun','cfun.o',[],'c',TMPDIR+'/Makefile');
    // incremental linking
    link(l,'cfun','c')
    // integration de la fonction
    I=intg(0,2*%pi,'cfun')
    abs(exact-I)

See Also

intc , intl , inttrap , intsplin , ode ,

Used Function

Les programmes correspondants (dqag0.f et dqags.f de quadpack) se trouvent dabs le repertoire routines/integ :


intl

Scilab Function
Last update : 12/01/2004

intl - Cauchy integral

Calling Sequence

[y]=intl(a,b,z0,r,f)

Parameters

  • z0 : complex number
  • a,b : two real numbers
  • r : positive real number
  • f : "external" function

Description

If f is a complex-valued function, intl(a,b,z0,r,f) computes the integral of f(z)dz along the curve in the complex plane defined by z0 + r.exp(%i*t) for a<=t<=b .(part of the circle with center z0 and radius r with phase between a and b )

See Also

intc ,

Author

F. D.


karmarkar

Scilab Function
Last update : 12/01/2004

karmarkar - karmarkar algorithm

Calling Sequence

[x1]=karmarkar(a,b,c,x0)

Parameters

  • a : matrix (n,p)
  • b : n - vector
  • c : p - vector
  • x0 : initial vector
  • eps : threshold (default value : 1.d-5)
  • gamma : descent step 0<gamma<1 , default value : 1/4
  • x1 : solution
  • crit : value of c'*x1

Description

Computes x which minimizes

                        c'*x

under constraints:

                        a*x = b
                        x>=0

Examples

// n=10;p=20;
// a=rand(n,p);c=rand(p,1);x0=abs(rand(p,1));b=a*x0;x1=karmarkar(a,b,c,x0);


leastsq

Scilab Function
Last update : 11/03/2005

leastsq - Solves non-linear least squares problems

Calling Sequence

[fopt,[xopt,[grdopt]]]=leastsq(fun, x0)
[fopt,[xopt,[grdopt]]]=leastsq(fun, dfun, x0)
[fopt,[xopt,[grdopt]]]=leastsq(fun, cstr, x0)
[fopt,[xopt,[grdopt]]]=leastsq(fun, dfun, cstr, x0)
[fopt,[xopt,[grdopt]]]=leastsq(fun, dfun, cstr, x0, algo)
[fopt,[xopt,[grdopt]]]=leastsq([imp], fun [,dfun] [,cstr],x0 [,algo],[df0,[mem]],[stop])

Parameters

  • fopt : value of the function f(x)=||fun(x)||^2 at xopt
  • xopt : best value of x found to minimize ||fun(x)||^2
  • grdopt : gradient of f at xopt
  • fun : a scilab function or a list defining a function from R^n to R^m (see more details in DESCRIPTION).
  • x0 : real vector (initial guess of the variable to be minimized).
  • dfun : a scilab function or a string defining the Jacobian matrix of fun (see more details in DESCRIPTION).
  • cstr : bound constraints on x . They must be introduced by the string keyword 'b' followed by the lower bound binf then by the upper bound bsup (so cstr appears as 'b',binf,bsup in the calling sequence). Those bounds are real vectors with same dimension than x0 (-%inf and +%inf may be used for dimension which are unrestricted).
  • algo : a string with possible values: 'qn' or 'gc' or 'nd'. These strings stand for quasi-Newton (default), conjugate gradient or non-differentiable respectively. Note that 'nd' does not accept bounds on x .
  • imp : scalar argument used to set the trace mode. imp=0 nothing (except errors) is reported, imp=1 initial and final reports, imp=2 adds a report per iteration, imp>2 add reports on linear search. Warning, most of these reports are written on the Scilab standard output.
  • df0 : real scalar. Guessed decreasing of ||fun||^2 at first iteration. (df0=1 is the default value).
  • mem : integer, number of variables used to approximate the Hessean (second derivatives) of f when algo ='qn'. Default value is around 6.
  • stop : sequence of optional parameters controlling the convergence of the algorithm. They are introduced by the keyword 'ar', the sequence being of the form 'ar',nap, [iter [,epsg [,epsf [,epsx]]]]
    • nap : maximum number of calls to fun allowed.
    • iter : maximum number of iterations allowed.
    • epsg : threshold on gradient norm.
    • epsf : threshold controlling decreasing of f
    • epsx : threshold controlling variation of x . This vector (possibly matrix) of same size as x0 can be used to scale x .

Description

fun being a function from R^n to R^m this routine tries to minimize w.r.t. x, the function:

                           _m_
                      2    \      2
     f(x) = ||fun(x)||  =  /   fun (x)
                           ---    i
                           i=1
which is the sum of the squares of the components of fun. Bound constraints may be imposed on x .

How to provide fun and dfun

fun can be either a usual scilab function (case 1) or a fortran or a C routine linked to scilab (case 2). For most problems the definition of fun will need supplementary parameters and this can be done in both cases.

  • case 1: when fun is a Scilab function, its calling sequence must be: y=fun(x [,opt_par1,opt_par2,...]). When fun needs optional parameters it must appear as list(fun,opt_par1,opt_par2,...) in the calling sequence of leastsq .
  • case 2: when fun is defined by a Fortran or C routine it must appear as list(fun_name,m [,opt_par1,opt_par2,...]) in the calling sequence of leastsq , fun_name (a string) being the name of the routine which must be linked to Scilab (see link ). The generic calling sequences for this routine are:
    In Fortran:    subroutine fun(m, n, x, params, y)
               integer m,n
               double precision x(n), params(*), y(m)

In C:          void fun(int *m, int *n, double *x, double *params, double *y)
    where n is the dimension of vector x , m the dimension of vector y (which must store the evaluation of fun at x) and params is a vector which contains the optional parameters opt_par1, opt_par2, ... (each parameter may be a vector, for instance if opt_par1 has 3 components, the description of opt_par2 begin from params(4) (fortran case), and from params[3] (C case), etc... Note that even if fun doesn't need supplementary parameters you must anyway write the fortran code with a params argument (which is then unused in the subroutine core).

    • In many cases it is adviced to provide the Jacobian matrix dfun (dfun(i,j)=dfi/dxj) to the optimizer (which uses a finite difference approximation otherwise) and as for fun it may be given as a usual scilab function or as a fortran or a C routine linked to scilab.

  • case 1: when dfun is a scilab function, its calling sequence must be: y=dfun(x [, optional parameters]) (notes that even if dfun needs optional parameters it must appear simply as dfun in the calling sequence of leastsq ).
  • case 2: when dfun is defined by a Fortran or C routine it must appear as dfun_name (a string) in the calling sequence of leastsq (dfun_name being the name of the routine which must be linked to Scilab). The calling sequences for this routine are nearly the same than for fun :
    In Fortran:    subroutine dfun(m, n, x, params, y)
               integer m,n
               double precision x(n), params(*), y(m,n)

In C:          void fun(int *m, int *n, double *x, double *params, double *y)
    in the C case dfun(i,j)=dfi/dxj must be stored in y[m*(j-1)+i-1].

    • Remarks

    Like datafit , leastsq is a front end onto the optim function. If you want to try the Levenberg-Marquard method instead, use lsqrsolve .

    A least squares problem may be solved directly with the optim function ; in this case the function NDcost may be useful to compute the derivatives (see the NDcost help page which provides a simple example for parameters identification of a differential equation).

    Examples

    // We will show different calling possibilities of leastsq on one (trivial) example
// which is non linear but doesn't really need to be solved with leastsq (applying
// log linearizes the model and the problem may be solved with linear algebra).
// In this example we look for the 2 parameters x(1) and x(2) of a simple
// exponential decay model (x(1) being the unknow initial value and x(2) the
// decay constant):
function y = yth(t, x)
   y  = x(1)*exp(-x(2)*t)
endfunction

// we have the m measures (ti, yi):
m = 10;
tm = [0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5]';
ym = [0.79, 0.59, 0.47, 0.36, 0.29, 0.23, 0.17, 0.15, 0.12, 0.08]';
wm = ones(m,1); // measure weights (here all equal to 1...)

// and we want to find the parameters x such that the model fits the given
// datas in the least square sense:
//
//  minimize  f(x) = sum_i  wm(i)^2 ( yth(tm(i),x) - ym(i) )^2

// initial parameters guess
x0 = [1.5 ; 0.8];

// in the first examples, we define the function fun and dfun
// in scilab language
function e = myfun(x, tm, ym, wm)
   e = wm.*( yth(tm, x) - ym )
endfunction

function g = mydfun(x, tm, ym, wm)
   v = wm.*exp(-x(2)*tm)
   g = [v , -x(1)*tm.*v]
endfunction

// now we could call leastsq:

// 1- the simplest call
[f,xopt, gropt] = leastsq(list(myfun,tm,ym,wm),x0)

// 2- we provide the Jacobian
[f,xopt, gropt] = leastsq(list(myfun,tm,ym,wm),mydfun,x0)

// a small graphic (before showing other calling features)
tt = linspace(0,1.1*max(tm),100)';
yy = yth(tt, xopt);
xbasc()
plot2d(tm, ym, style=-2)
plot2d(tt, yy, style = 2)
legend(["measure points", "fitted curve"]);
xtitle("a simple fit with leastsq")

// 3- how to get some informations (we use imp=1)
[f,xopt, gropt] = leastsq(1,list(myfun,tm,ym,wm),mydfun,x0)

// 4- using the conjugate gradient (instead of quasi Newton)
[f,xopt, gropt] = leastsq(1,list(myfun,tm,ym,wm),mydfun,x0,"gc")

// 5- how to provide bound constraints (not useful here !)
xinf = [-%inf,-%inf]; xsup = [%inf, %inf];
[f,xopt, gropt] = leastsq(list(myfun,tm,ym,wm),"b",xinf,xsup,x0) // without Jacobian
[f,xopt, gropt] = leastsq(list(myfun,tm,ym,wm),mydfun,"b",xinf,xsup,x0) // with Jacobian

// 6- playing with some stopping parameters of the algorithm
//    (allows only 40 function calls, 8 iterations and set epsg=0.01, epsf=0.1)
[f,xopt, gropt] = leastsq(1,list(myfun,tm,ym,wm),mydfun,x0,"ar",40,8,0.01,0.1)

// 7 and 8: now we want to define fun and dfun in fortran then in C
//          Note that the "compile and link to scilab" method used here
//          is believed to be OS independant (but there are some requirements,
//          in particular you need a C and a fortran compiler, and they must
//          be compatible with the ones used to build your scilab binary).

// 7- fun and dfun in fortran

// 7-1/ Let 's Scilab write the fortran code (in the TMPDIR directory):
f_code = [ ...
"      subroutine myfun(m,n,x,param,f)"
"*     param(i) = tm(i), param(m+i) = ym(i), param(2m+i) = wm(i)"
"      implicit none"
"      integer n,m"
"      double precision x(n), param(*), f(m)"
"      integer i"
"      do i = 1,m"
"         f(i) = param(2*m+i)*( x(1)*exp(-x(2)*param(i)) - param(m+i) )"
"      enddo"
"      end ! subroutine fun"
""
"      subroutine mydfun(m,n,x,param,df)"
"*     param(i) = tm(i), param(m+i) = ym(i), param(2m+i) = wm(i)"
"      implicit none"
"      integer n,m"
"      double precision x(n), param(*), df(m,n)"
"      integer i"
"      do i = 1,m"
"         df(i,1) =  param(2*m+i)*exp(-x(2)*param(i))"
"         df(i,2) = -x(1)*param(i)*df(i,1)"
"      enddo"
"      end ! subroutine dfun"];
mputl(f_code,TMPDIR+'/myfun.f')

// 7-2/ compiles it. You need a fortran compiler !
names = ["myfun" "mydfun"]
flibname = ilib_for_link(names,"myfun.o",[],"f",TMPDIR+"/Makefile");

// 7-3/ link it to scilab (see link help page)
link(flibname,names,"f")

// 7-4/ ready for the leastsq call: be carreful don't forget to
//      give the dimension m after the routine name !
[f,xopt, gropt] = leastsq(list("myfun",m,tm,ym,wm),x0)  // without Jacobian
[f,xopt, gropt] = leastsq(list("myfun",m,tm,ym,wm),"mydfun",x0) // with Jacobian

// 8- last example: fun and dfun in C

// 8-1/ Let 's Scilab write the C code (in the TMPDIR directory):
c_code = [...
"#include <math.h>"
"void myfunc(int *m,int *n, double *x, double *param, double *f)"
"{"
"  /*  param[i] = tm[i], param[m+i] = ym[i], param[2m+i] = wm[i] */"
"  int i;"
"  for ( i = 0 ; i < *m ; i++ )"
"    f[i] = param[2*(*m)+i]*( x[0]*exp(-x[1]*param[i]) - param[(*m)+i] );"
"  return;"
"}"
""
"void mydfunc(int *m,int *n, double *x, double *param, double *df)"
"{"
"  /*  param[i] = tm[i], param[m+i] = ym[i], param[2m+i] = wm[i] */"
"  int i;"
"  for ( i = 0 ; i < *m ; i++ )"
"    {"
"      df[i] = param[2*(*m)+i]*exp(-x[1]*param[i]);"
"      df[i+(*m)] = -x[0]*param[i]*df[i];"
"    }"
"  return;"
"}"];
mputl(c_code,TMPDIR+'/myfunc.c')

// 8-2/ compiles it. You need a C compiler !
names = ["myfunc" "mydfunc"]
clibname = ilib_for_link(names,"myfunc.o",[],"c",TMPDIR+"/Makefile");

// 8-3/ link it to scilab (see link help page)
link(clibname,names,"c")

// 8-4/ ready for the leastsq call
[f,xopt, gropt] = leastsq(list("myfunc",m,tm,ym,wm),"mydfunc",x0)

    See Also

    lsqrsolve , optim , NDcost , datafit , external , quapro , linpro ,


linpro

Scilab Function
Last update : 12/01/2004

linpro - linear programming solver

Calling Sequence

[x,lagr,f]=linpro(p,C,b [,x0])
[x,lagr,f]=linpro(p,C,b,ci,cs [,x0])
[x,lagr,f]=linpro(p,C,b,ci,cs,me [,x0])
[x,lagr,f]=linpro(p,C,b,ci,cs,me,x0 [,imp])

Parameters

  • p : real column vector (dimension n )
  • C : real matrix (dimension (me + md) x n ) (If no constraints are given, you can set C = [] )
  • b : RHS column vector (dimension (me + md) ) (If no constraints are given, you can set b = [] )
  • ci : column vector of lower-bounds (dimension n ). If there are no lower bound constraints, put ci = [] . If some components of x are bounded from below, set the other (unconstrained) values of ci to a very large negative number (e.g. ci(j) = -number_properties('huge') .
  • cs : column vector of upper-bounds. (Same remarks as above).
  • me : number of equality constraints (i.e. C(1:me,:)*x = b(1:me) )
  • x0 : either an initial guess for x or one of the character strings 'v' or 'g' . If x0='v' the calculated initial feasible point is a vertex. If x0='g' the calculated initial feasible point is arbitrary.
  • imp : verbose option (optional parameter) (Try imp=7,8,... ) warning the message are output in the window where scilab has been started.
  • x : optimal solution found.
  • f : optimal value of the cost function (i.e. f=p'*x ).
  • lagr : vector of Lagrange multipliers. If lower and upper-bounds ci,cs are provided, lagr has n + me + md components and lagr(1:n) is the Lagrange vector associated with the bound constraints and lagr (n+1 : n + me + md) is the Lagrange vector associated with the linear constraints. (If an upper-bound (resp. lower-bound) constraint i is active lagr(i) is > 0 (resp. <0). If no bounds are provided, lagr has only me + md components.

Description

[x,lagr,f]=linpro(p,C,b [,x0]) Minimize p'*x under the constraints C*x <= b

[x,lagr,f]=linpro(p,C,b,ci,cs [,x0]) Minimize p'*x under the constraints C*x <= b , ci <= x <= cs

[x,lagr,f]=linpro(p,C,b,ci,cs,me [,x0]) Minimize p'*x under the constraints

 C(j,:) x = b(j),  j=1,...,me
 C(j,:) x <= b(j), j=me+1,...,me+md
 ci <= x <= cs

If no initial point is given the program computes a feasible initial point which is a vertex of the region of feasible points if x0='v' .

If x0='g' , the program computes a feasible initial point which is not necessarily a vertex. This mode is advisable when the quadratic form is positive definite and there are a few constraints in the problem or when there are large bounds on the variables that are security bounds and very likely not active at the optimal solution.

Examples

//Find x in R^6 such that:
//C1*x = b1  (3 equality constraints i.e me=3)
C1= [1,-1,1,0,3,1;
    -1,0,-3,-4,5,6;
     2,5,3,0,1,0];
b1=[1;2;3];
//C2*x <= b2  (2 inequality constraints)
C2=[0,1,0,1,2,-1;
    -1,0,2,1,1,0];
b2=[-1;2.5];
//with  x between ci and cs:
ci=[-1000;-10000;0;-1000;-1000;-1000];cs=[10000;100;1.5;100;100;1000];
//and minimize p'*x with
p=[1;2;3;4;5;6]
//No initial point is given: x0='v';
C=[C1;C2]; b=[b1;b2] ; me=3; x0='v';
[x,lagr,f]=linpro(p,C,b,ci,cs,me,x0)
// Lower bound constraints 3 and 4 are active and upper bound
// constraint 5 is active --> lagr(3:4) < 0 and lagr(5) > 0.
// Linear (equality) constraints 1 to 3 are active --> lagr(7:9) <> 0

See Also

quapro ,

Authors

Eduardo Casas Renteria, Universidad de Cantabria,
Cecilia Pola Mendez , Universidad de Cantabria

Used Function

in routines/optim directory (authors E.Casas, C. Pola Mendez):

anfm01.f anfm03.f anfm05.f anrs01.f auxo01.f dimp03.f dnrm0.f optr03.f pasr03.f zthz.f anfm02.f anfm04.f anfm06.f anrs02.f desr03.f dipvtf.f optr01.f opvf03.f plcbas.f

From BLAS library

daxpy.f dcopy.f ddot.f dnrm2.f dscal.f dswap.f idamax.f

in routines/calelm directory (authors INRIA):

add.f ddif.f dmmul.f

From LAPACK library : dlamch.f


lmisolver

Scilab Function
Last update : 12/01/2004

lmisolver - linear matrix inequation solver

Calling Sequence

[XLISTF[,OPT]] = lmisolver(XLIST0,evalfunc [,options])

Parameters

  • XLIST0 : a list of containing initial guess (e.g. XLIST0=list(X1,X2,..,Xn) )
  • evalfunc : a Scilab function ("external" function with specific syntax)

    The syntax the function evalfunc must be as follows:

    [LME,LMI,OBJ]=evalfunct(X) where X is a list of matrices, LME, LMI are lists and OBJ a real scalar.

  • XLISTF : a list of matrices (e.g. XLIST0=list(X1,X2,..,Xn) )
  • options : optional parameter. If given, options is a real row vector with 5 components [Mbound,abstol,nu,maxiters,reltol]

Description

lmisolver solves the following problem:

minimize f(X1,X2,...,Xn) a linear function of Xi's

under the linear constraints: Gi(X1,X2,...,Xn)=0 for i=1,...,p and LMI (linear matrix inequalities) constraints:

Hj(X1,X2,...,Xn) > 0 for j=1,...,q

The functions f, G, H are coded in the Scilab function evalfunc and the set of matrices Xi's in the list X (i.e. X=list(X1,...,Xn) ).

The function evalfun must return in the list LME the matrices G1(X),...,Gp(X) (i.e. LME(i)=Gi(X1,...,Xn), i=1,...,p). evalfun must return in the list LMI the matrices H1(X0),...,Hq(X) (i.e. LMI(j)=Hj(X1,...,Xn) , j=1,...,q). evalfun must return in OBJ the value of f(X) (i.e. OBJ=f(X1,...,Xn) ).

lmisolver returns in XLISTF , a list of real matrices, i. e. XLIST=list(X1,X2,..,Xn) where the Xi's solve the LMI problem:

Defining Y,Z and cost by:

[Y,Z,cost]=evalfunc(XLIST) , Y is a list of zero matrices, Y=list(Y1,...,Yp) , Y1=0, Y2=0, ..., Yp=0 .

Z is a list of square symmetric matrices, Z=list(Z1,...,Zq) , which are semi positive definite Z1>0, Z2>0, ..., Zq>0 (i.e. spec(Z(j)) > 0),

cost is minimized.

lmisolver can also solve LMI problems in which the Xi's are not matrices but lists of matrices. More details are given in the documentation of LMITOOL.

Examples

//Find diagonal matrix X (i.e. X=diag(diag(X), p=1) such that
//A1'*X+X*A1+Q1 < 0, A2'*X+X*A2+Q2 < 0 (q=2) and trace(X) is maximized
n=2;A1=rand(n,n);A2=rand(n,n);
Xs=diag(1:n);Q1=-(A1'*Xs+Xs*A1+0.1*eye());
Q2=-(A2'*Xs+Xs*A2+0.2*eye());
deff('[LME,LMI,OBJ]=evalf(Xlist)','X=Xlist(1),LME=X-diag(diag(X));...
LMI=list(-(A1''*X+X*A1+Q1),-(A2''*X+X*A2+Q2)),OBJ= -sum(diag(X))  ');
X=lmisolver(list(zeros(A1)),evalf);X=X(1)
[Y,Z,c]=evalf(X)

See Also

lmitool ,


lmitool

Scilab Function
Last update : 12/01/2004

lmitool - tool for solving linear matrix inequations

Calling Sequence

lmitool()
lmitool(filename)
txt=lmitool(probname,varlist,datalist)

Parameters

  • filename : a string referring to a .sci function
  • probname : a string containing the name of the problem
  • varlist : a string containing the names of the unknown matrices (separated by commas if there are more than one)
  • datalist : a string containing the names of data matrices (separated by commas if there are more than one)
  • txt : a string providing information on what the user should do next

Description

lmitool() or lmitool(filename) is used to define interactively a LMI problem. In the non interactive mode, txt=lmitool(probname,varlist,datalist) generates a file in the current directory. The name of this file is obtained by adding .sci to the end of probname . This file is the skeleton of a solver function and the corresponding evaluation function needed by lmisolver .

See Also

lmisolver ,


lsqrsolve

Scilab Function
Last update : 11/01/2005

lsqrsolve - minimize the sum of the squares of nonlinear functions, levenberg-marquardt algorithm

Calling Sequence

[x [,v [,info]]]=lsqrsolve(x0,fct,m [,stop [,diag]])
[x [,v [,info]]]=lsqrsolve(x0,fct,m ,fjac [,stop [,diag]])

Parameters

  • x0 : real vector (initial value of functions argument).
  • fct : external (i.e function or list or string).
  • m : integer, the number of functions.
  • fjac : external (i.e function or list or string).
  • stop : optional vector [ftol,xtol,gtol,maxfev,epsfcn,factor] the default value is [1.d-8,1.d-8,1.d-5,1000,0,100]
    • ftol : A positive real number,termination occurs when both the actual and predicted relative reductions in the sum of squares are at most ftol. therefore, ftol measures the relative error desired in the sum of squares.
    • xtol : A positive real number, termination occurs when the relative error between two consecutive iterates is at most xtol. therefore, xtol measures the relative error desired in the approximate solution.
    • gtol : A nonnegative input variable. termination occurs when the cosine of the angle between fct(x) and any column of the jacobian is at most gtol in absolute value. therefore, gtol measures the orthogonality desired between the function vector and the columns of the jacobian.
    • maxfev : A positive integer, termination occurs when the number of calls to fct is at least maxfev by the end of an iteration.
    • epsfcn : A positive real number, used in determining a suitable step length for the forward-difference approximation. this approximation assumes that the relative errors in the functions are of the order of epsfcn. if epsfcn is less than the machine precision, it is assumed that the relative errors in the functions are of the order of the machine precision.
    • factor : A positive real number, used in determining the initial step bound. this bound is set to the product of factor and the euclidean norm of diag*x if nonzero, or else to factor itself. in most cases factor should lie in the interval (.1,100.). 100. is a generally recommended value.
  • diag : is an array of length n. diag must contain positive entries that serve as multiplicative scale factors for the variables.
  • x : real vector (final value of function argument, estimated zero).
  • v : real vector (value of functions at x).
  • info : termination indicator
    • 0 : improper input parameters.
    • 1 : algorithm estimates that the relative error between x and the solution is at most tol.
    • 2 : number of calls to fcn reached
    • 3 : tol is too small. No further improvement in the approximate solution x is possible.
    • 4 : iteration is not making good progress.

Description

minimize the sum of the squares of m nonlinear functions in n variables by a modification of the levenberg-marquardt algorithm. the user must provide a subroutine which calculates the functions. the jacobian is then calculated by a forward-difference approximation.

minimize sum(fct(x,m).^2) where fct is function from R^n to R^m

fct should be :

a Scilab function whose calling sequence is v=fct(x,m) given x and m .
a character string which refers to a C or Fortran routine which must be linked to Scilab.

Fortran calling sequence should be fct(m,n,x,v,iflag) where m , n , iflag are integers, x a double precision vector of size n and v a double precision vector of size m .

C calling sequence should be fct(int *m, int *n, double x[],double v[],int *iflag)

fjac is an external which returns v=d(fct)/dx (x) . it should be :

a Scilab functionwhose calling sequence is J=fjac(x,m) given x and m .
a character stringit refers to a C or Fortran routine which must be linked to Scilab.

Fortran calling sequence should be fjac(m,n,x,jac,iflag) where m , n , iflag are integers, x a double precision vector of size n and jac a double precision vector of size m*n .

C calling sequence should be fjac(int *m, int *n, double x[],double v[],int *iflag)

return -1 in iflag to stop the algoritm if the function or jacobian could not be evaluated.

Examples

// A simple example with lsqrsolve
a=[1,7;
   2,8
   4 3];
b=[10;11;-1];
function y=f1(x,m),y=a*x+b;endfunction
[xsol,v]=lsqrsolve([100;100],f1,3)
xsol+a\b

function y=fj1(x,m),y=a;endfunction
[xsol,v]=lsqrsolve([100;100],f1,3,fj1)
xsol+a\b

// Data fitting problem
// 1 build the data
a=34;b=12;c=14;
deff('y=FF(x)','y=a*(x-b)+c*x.*x');
X=(0:.1:3)';Y=FF(X)+100*(rand()-.5);

//solve
function e=f1(abc,m)
  a=abc(1);b=abc(2),c=abc(3),
  e=Y-(a*(X-b)+c*X.*X);
endfunction
[abc,v]=lsqrsolve([10;10;10],f1,size(X,1));
abc
norm(v)

See Also

external , quapro , linpro , optim , fsolve ,

Used Function

lmdif, lmder from minpack, Argonne National Laboratory.


numdiff

Scilab Function
Last update : 12/01/2004

numdiff - numerical gradient estimation

Calling Sequence

g=numdiff(fun,x [,dx])

Parameters

  • fun : an external, Scilab function or list. See below for calling sequence, see also external for details about external functions.
  • x : vector, the argument of the function fun
  • dx : vector, the finite difference step. Default value is dx=sqrt(%eps)*(1+1d-3*abs(x))
  • g : vector, the estimated gradient

Description

given a function fun(x) from R^n to R^p computes the matrix g such as

    [   d f    ]
    [      i   ]
g = [   ----   ]
 ij [   d x    ]
    [      j   ]

using finite difference methods.

The function fun calling sequence must be y=fun(x,p1,p2,..pn) .If parameters p1,p2,..pn exist then numdiff can be called as follow g=numdiff(list(fun,p1,p2,..pn),x).

Examples

function  f=myfun(x,y,z,t)
f=(x+y)^t+z
endfunction

y=3;z=4;t=2;
g=numdiff(list(myfun,3,4,2),1)

x=1;
exact=t*(x+y)^(t-1)

See Also

optim ,


odedc

Scilab Function
Last update : 12/01/2004

odedc - discrete/continuous ode solver

Calling Sequence

yt=odedc(y0,nd,stdel,t0,t,f)

Parameters

  • y0 : real column vector (initial conditions), y0=[y0c;y0d] where y0d has nd components.
  • nd : integer, dimension of y0d
  • stdel : real vector with one or two entries, stdel=[h, delta] (with delta=0 as default value).
  • t0 : real scalar (initial time).
  • t : real (row) vector, instants where yt is calculated .
  • f : external i.e. function or character string or list with calling sequence: yp=f(t,yc,yd,flag) .

Description

y=odedc([y0c;y0d],nd,[h,delta],t0,t,f) computes the solution of a mixed discrete/continuous system. The discrete system state yd_k is embedded into a piecewise constant yd(t) time function as follows:

yd(t)=yd_k for t in
[t_k=delay+k*h,t_(k+1)=delay+(k+1)*h[ (with delay=h*delta).

The simulated equations are now:

dyc/dt=f(t,yc(t),yd(t),0),  for t in [t_k,t_(k+1)[
yc(t0)=y0c

and at instants t_k the discrete variable yd is updated by:

yd(t_k+)=f(yc(t_k-),yd(t_k-),1)

Note that, using the definition of yd(t) the last equation gives

yd_k = f (t_k,yc(t_k-),yd(t_(k-1)),1)  (yc is time-continuous: yc(t_k-)=yc(tk))

The calling parameters of f are fixed: ycd=f(t,yc,yd,flag) ; this function must return either the derivative of the vector yc if flag=0 or the update of yd if flag=1 .

ycd=dot(yc) must be a vector with same dimension as yc if flag=0 and ycd=update(yd) must be a vector with same dimension as yd if flag=1 .

t is a vector of instants where the solution y is computed.

y is the vector y=[y(t(1)),y(t(2)),...] . This function can be called with the same optional parameters as the ode function (provided nd and stdel are given in the calling sequence as second and third parameters). In particular integration flags, tolerances can be set. Optional parameters can be set by the odeoptions function.

An example for calling an external routine is given in directory SCIDIR/default/fydot2.f

External routines can be dynamically linked (see link ).

Examples

//Linear system with switching input
deff('xdu=phis(t,x,u,flag)','if flag==0 then xdu=A*x+B*u; else xdu=1-u;end');
x0=[1;1];A=[-1,2;-2,-1];B=[1;2];u=0;nu=1;stdel=[1,0];u0=0;t=0:0.05:10;
xu=odedc([x0;u0],nu,stdel,0,t,phis);x=xu(1:2,:);u=xu(3,:);
nx=2;
plot2d1('onn',t',x',[1:nx],'161');
plot2d2('onn',t',u',[nx+1:nx+nu],'000');
//Fortran external( see fydot2.f):
norm(xu-odedc([x0;u0],nu,stdel,0,t,'phis'),1)

//Sampled feedback
//
//        |     xcdot=fc(t,xc,u)
//  (system)   |
//        |     y=hc(t,xc)
//
//
//        |     xd+=fd(xd,y)
//  (feedback) |
//        |     u=hd(t,xd)
//
deff('xcd=f(t,xc,xd,iflag)',...
  ['if iflag==0 then '
   '  xcd=fc(t,xc,e(t)-hd(t,xd));'
   'else '
   '  xcd=fd(xd,hc(t,xc));'
   'end']);
A=[-10,2,3;4,-10,6;7,8,-10];B=[1;1;1];C=[1,1,1];
Ad=[1/2,1;0,1/20];Bd=[1;1];Cd=[1,1];
deff('st=e(t)','st=sin(3*t)')
deff('xdot=fc(t,x,u)','xdot=A*x+B*u')
deff('y=hc(t,x)','y=C*x')
deff('xp=fd(x,y)','xp=Ad*x + Bd*y')
deff('u=hd(t,x)','u=Cd*x')
h=0.1;t0=0;t=0:0.1:2;
x0c=[0;0;0];x0d=[0;0];nd=2;
xcd=odedc([x0c;x0d],nd,h,t0,t,f);
norm(xcd-odedc([x0c;x0d],nd,h,t0,t,'fcd1')) // Fast calculation (see fydot2.f)
plot2d([t',t',t'],xcd(1:3,:)');
xset("window",2);plot2d2("gnn",[t',t'],xcd(4:5,:)');
xset("window",0);

See Also

ode , odeoptions , csim , external ,


odeoptions

Scilab Function
Last update : 12/01/2004

odeoptions - set options for ode solvers

Calling Sequence

odeoptions()

Description

This function interactively displays a command which should be executed to set various options of ode solvers. The global variable %ODEOPTIONS sets the options.

CAUTION: the ode function checks if this variable exists and in this case it uses it. For using default values you should clear this variable. Note that odeoptions does not create this variable. To create it you must execute the command line displayed by odeoptions .

The variable %ODEOPTIONS is a vector with the following elements:

[itask,tcrit,h0,hmax,hmin,jactyp,mxstep,maxordn,maxords,ixpr,ml,mu]

The default value is:

[1,0,0,%inf,0,2,500,12,5,0,-1,-1]

The meaning of the elements is described below.

itask 1 : normal computation at specified times 2 : computation at mesh points (given in first row of output of ode ) 3 : one step at one internal mesh point and return 4 : normal computation without overshooting tcrit 5 : one step, without passing tcrit , and return

tcrit assumes itask equals 4 or 5, described above

h0 first step tried

hmax max step size

hmin min step size

jactype 0 : functional iterations, no jacobian used ( "adams" or "stiff" only) 1 : user-supplied full jacobian 2 : internally generated full jacobian 3 : internally generated diagonal jacobian ( "adams" or "stiff" only) 4 : user-supplied banded jacobian (see ml and mu below) 5 : internally generated banded jacobian ( see ml and mu below)

maxordn maximum non-stiff order allowed, at most 12

maxords maximum stiff order allowed, at most 5

ixpr print level, 0 or 1

ml , mu If jactype equals 4 or 5, ml and mu are the lower and upper half-bandwidths of the banded jacobian: the band is the i,j's with i-ml <= j <= ny-1. If jactype equals 4 the jacobian function must return a matrix J which is ml+mu+1 x ny (where ny=dim of y in ydot=f(t,y)) such that column 1 of J is made of mu zeros followed by df1/dy1, df2/dy1, df3/dy1, ... (1+ml possibly non-zero entries) column 2 is made of mu-1 zeros followed by df1/dx2, df2/dx2, etc

See Also

ode ,


ode_discrete

Scilab Function
Last update : 12/01/2004

ode_discrete - ordinary differential equation solver, discrete time simulation

Calling Sequence

y=ode("discrete",y0,k0,kvect,f)

Parameters

  • y0 : real vector or matrix (initial conditions).
  • t0 : real scalar (initial time).
  • f : external i.e. function or character string or list.
  • k0 : integer (initial time).
  • kvect : integer vector.

Description

With this syntax (first argument equal to "discrete" ) ode computes recursively y(k+1)=f(k,y(k)) from an initial state y(k0) and returns y(k) for k in kvect . kvect(1) must be greater than or equal to k0 .

Other arguments and other options are the same as for ode , see the ode help.

Examples

y1=[1;2;3]; deff("yp=a_function(k,y)","yp=A*y+B*u(k)")
A=diag([0.2,0.5,0.9]); B=[1;1;1];u=1:10;n=5;
y=ode("discrete",y1,1,1:n,a_function);
y(:,2)-(A*y1+B*u(1))
// Now y evaluates  at [y3,y5,y7,y9]
y=ode("discrete",y1,1,3:2:9,a_function)

See Also

ode ,


ode_optional_output

Scilab Function
Last update : 15/10/2004

ode_optional_output - ode solvers optional outputs description

Description

This page describes the the most important values returned in the optional lhs ode function arguments w and iw . These are valid only for the lsode lsoda and lsodar ode solver. For more details, one can look at the solvers fortran code comments in routines/integ/lsod*.f .
w(11) the step size in t last used (successfully).
w(12) the step size to be attempted on the next step.
w(13) the current value of the independent variable which the solver has actually reached, i.e. the current internal mesh point in t. on output, tcur will always be at least as far as the argument t, but may be farther (if interpolation was done).
w(14) a tolerance scale factor, greater than 1.0, computed when a request for too much accuracy was detected (istate = -3 if detected at the start of the problem, istate = -2 otherwise). if itol is left unaltered but rtol and atol are uniformly scaled up by a factor of tolsf=w(14) for the next call, then the solver is deemed likely to succeed. (the user may also ignore tolsf and alter the tolerance parameters in any other way appropriate.)
w(15) the value of t at the time of the last method switch, if any. This value is not significant with lsode solver.
iw(10) the number of g evaluations for the problem so far. This value is only significant for lsodar solver.
iw(11) the number of steps taken for the problem so far.
iw(12) the number of f evaluations for the problem so far.
iw(13) the number of jacobian evaluations (and of matrix lu decompositions) for the problem so far.
iw(14) the method order last used (successfully).
iw(15) the order to be attempted on the next step.
iw(16) the index of the component of largest magnitude in the weighted local error vector ( e(i)/ewt(i) ), on an error return with istate = -4 or -5.
iw(17) the length of w actually required, assuming that the length of rwork is to be fixed for the rest of the problem, and that switching may occur. this is defined on normal returns and on an illegal input return for insufficient storage.
iw(18) the length of iw actually required, assuming that the length of iw is to be fixed for the rest of the problem, and that switching may occur. this is defined on normal returns and on an illegal input return for insufficient storage.
iw(19) the method indicator for the last successful step.. 1 means adams (nonstiff), 2 means bdf (stiff). This value is not significant with lsode solver.
iw(20) the current method indicator.. 1 means adams (nonstiff), 2 means bdf (stiff). this is the method to be attempted on the next step. thus it differs from iw(19) only if a method switch has just been made. This value is not significant with lsode solver.


ode_root

Scilab Function
Last update : 12/01/2004

ode_root - ordinary differential equation solver with root finding

Calling Sequence

y,rd[,w,iw]=ode("root",y0,t0,t [,rtol [,atol]],f [,jac],ng,g [,w,iw])

Parameters

  • y0 : real vector or matrix (initial conditions).
  • t0 : real scalar (initial time).
  • t : real vector (times at which the solution is computed).
  • f : external i.e. function or character string or list.
  • rtol,atol : real constants or real vectors of the same size as y .
  • jac : external i.e. function or character string or list.
  • w,iw : real vectors.
  • ng : integer.
  • g : external i.e. function or character string or list.

Description

With this syntax (first argument equal to "root" ) ode computes the solution of the differential equation dy/dt=f(t,y) until the state y(t) crosses the surface g(t,y)=0 .

g should give the equation of the surface. It is an external i.e. a function with specified syntax, or the name of a Fortran subroutine or a C function (character string) with specified calling sequence or a list.

If g is a function the syntax should be as follows:

z=g(t,y)

where t is a real scalar (time) and y a real vector (state). It returns a vector of size ng which corresponds to the ng constraints. If g is a character string it refers to the name of a Fortran subroutine or a C function, with the following calling sequence: g(n,t,y,ng,gout) where ng is the number of constraints and gout is the value of g (output of the program). If g is a list the same conventions as for f apply (see ode help).

Ouput rd is a 1 x k vector. The first entry contains the stopping time. Other entries indicate which components of g have changed sign. k larger than 2 indicates that more than one surface ( (k-1) surfaces) have been simultaneously traversed.

Other arguments and other options are the same as for ode , see the ode help.

Examples

// Integration of the differential equation
// dy/dt=y , y(0)=1, and finds the minimum time t such that y(t)=2
deff("[ydot]=f(t,y)","ydot=y")
deff("[z]=g(t,y)","z=y-2")
y0=1;ng=1;
[y,rd]=ode("roots",y0,0,2,f,ng,g)

deff("[z]=g(t,y)","z=y-[2;2;33]")
[y,rd]=ode("roots",1,0,2,f,3,g)

See Also

dasrt , ode ,


ode

Scilab Function
Last update : 14/12/2005

ode - solveur d'équations différentielles ordinaires

Calling Sequence

y=ode(y0,t0,t,f)
[y,w,iw]=ode([type],y0,t0,t [,rtol [,atol]],f [,jac] [,w,iw])
[y,rd,w,iw]=ode("root",y0,t0,t [,rtol [,atol]],f [,jac],ng,g [,w,iw])
y=ode("discrete",y0,k0,kvect,f)

Parameters

  • y0 : vecteur ou matrice réelle (conditions initiales).
  • t0 : réel (instant initial).
  • t : vecteur réel (instants où la solution est renvoyée).
  • f : fonction externe (fonction Scilab ou chaîne de caractères ou liste).
  • type : une des chaînes de caractères : "adams" "stiff" "rk" "rkf" "fix" "discrete" "roots"
  • rtol,atol : constantes ou vecteurs réels de même taille que y .
  • jac : fonction externe (fonction Scilab, chaîne de caractères ou liste).
  • w,iw : vecteurs réels
  • ng : entier
  • g : fonction externe (fonction Scilab, chaîne de caractères ou liste).
  • k0 : entier (instant initial). kvect : vecteur d'entiers

Description

ode est la fonction utilisée pour approcher la solution d'une équation différentielle ordinaire (EDO) explicite du premier ordre en temps, définie par : dy/dt=f(t,y) , y(t0)=y0. Il s'agit d'une interface vers diverses librairies, en particulier ODEPACK. Le type du problème et la méthode utilisée dépendent de la valeur du premier argument optionnel type qui peut être égal à :
<aucun> : le solveur lsoda du package ODEPACK est utilisé par défaut. Il choisit automatiquement entre un schéma prédicteur-correcteur d'Adams et un schéma adapté au systèmes raides (stiff) de type "Backward Differentiation Formula" (BDF). Initialement le schéma adapté aux système non raides est choisi puis la méthode adaptée est ensuite choisie dynamiquement.
"adams" : Problèmes non raides. Le solveur lsode du package ODEPACK est utilisé (schéma d'Adams).
"stiff" : Pour les systèmes raides. Le solveur lsode du package ODEPACK est utilisé avec le schéma BDF.
"rk" : Schéma de Runge-Kutta adaptatif d'ordre 4 (RK4).
"rkf" : Formules de Shampine et Watts basées sur les paires de Runge-Kutta Fehlberg d'ordre 4 et 5 (RKF45). Bien pour les problèmes non raides ou moyennement raides, lorsque le calcul du second membre n'est pas trop coûteux. Cette méthode est à éviter si l'on recherche une très grande précision.
"fix": Identique à "rkf", mais l'interface est simplifiée, i.e. uniquement rtol et atol sont communiqués au solveur.
"root": Solveur d'EDO avec recherche de racines. Le solveur lsodar du package ODEPACK est utilisé. C'est une variante de lsoda permettant la recherche d'une racine d'une fonction vectorielle donnée. Voir ode_root pour plus de détails.
"discrete": Simulation en temps discret. Voir ode_discrete pour plus de détails.

Ici on ne décrit l'usage de ode que pour des EDO explicites.

L'appel le plus simple de ode est du type : y=ode(y0,t0,t,f) où y0 est le vecteur des conditions initiales, t0 est le temps initial, et t est le vecteur des instants où l'on veut une approximation de la solution. y est calculée et y est la matrice y=[y(t(1)),y(t(2)),...] .

Le paramètre d'entrée f de ode défini le membre de droite de léquation différentielle du premier ordre dy/dt=f(t,y). C'est un external qui peut être :

Soit une fonction Scilab, sa syntaxe doit être ydot = f(t,y) où t est un scalaire (le temps), y un vecteur (l'état). Cette fonction renvoie le second membre de l'équation différentielle dy/dt=f(t,y).

Soit une chaîne de caractères, elle désigne le nom d'une subroutine Fortran ou une procédure C, i.e. si ode(y0,t0,t,"fex") est la commande, alors la procedure fex est appelée.

Si c'est une subroutine Fortran, sa liste d'appel doit être

          subroutine fex(n,t,y,ydot)
          integer n
          double precision t,y(*),ydot(*)
Si c'est une fonction C son prototype doit être:
          void fex(int *n,double *t,double *y,double *ydot)

Cet external peut être compilé par l'utilitaire ilib_for_link et chargé dynamiquement par la fonction link .

Soit une liste avec la structure suivante list(vrai_f,u1,u2,...un) où vrai_f est une fonction avec la syntaxe ydot = vrai_f(t,y,u1,u2,...,un)

Cette syntaxe permet de passer des paramètres sous forme d'arguments supplémentaires de vrai_f .

La fonction f peut renvoyer une matrice p x q au lieu d'un vecteur. Dans ce cas, on résout le système d'EDO n=p+q dY/dt=F(t,Y) où Y est une matrice p x q . La condition initiale Y0 doit aussi être une matrice p x q matrix et le résultat renvoyé par ode est la matrice: p x q(T+1) égale à [Y(t_0),Y(t_1),...,Y(t_T)] .

Des paramètres optionnels contrôlent la tolérance du schéma : rtol et atol sont des valeurs seuil sur les erreurs estimées (relative et absolue) L'erreur estimée sur y(i) est rtol(i)*abs(y(i))+atol(i)

Si rtol et/ou atol sont des constantes rtol(i) et/ou atol(i) prennent ces valeurs. Les valeurs par défaut de rtol et atol sont respectivement rtol=1.d-5 et atol=1.d-7 pour la plupart des solveurs et rtol=1.d-3 et atol=1.d-4 pour "rfk" et "fix" .

Pour les problèmes raides, il est recommandé de fournir la jacobienne du second membre sous forme de l'argument optionnel jac . Le paramètre jac de ode est par exemple une fonction Scilab, dont la syntaxe est imposée, ou le nom d'une subroutine Fortran ou C (chaîne de caractères) ou une liste.

Si jac est une fonction Scilab sa syntaxe doit être J=jac(t,y)

où t est un scalaire (le temps) et y un vecteur (l'état). La matrice J doit renvoyer df/dx i.e. J(k,i) = dfk /dxi avec fk = k-ième composante de f.

Si f est une chaîne de caractères, elle désigne le nom d'une subroutine Fortran ou C.

En Fortran, Cette routine doit avoir la liste d'appel suivante :
          subroutine fex(n,t,y,ml,mu,J,nrpd)
          integer n,ml,mu,nrpd
          double precision t,y(*),J(*)
Si c'est une fonction C son prototype doit être:
          void fex(int *n,double *t,double *y,int *ml,int *mu,double *J,int *nrpd,)
Dans la plupart des cas il n'est pas nécessaire d'utiliser ml , mu et nrpd , qui sont relatif aà la possibilité de stockage "bande" du Jacobien

Si jac est une liste, les mêmes conventions que pour f s'appliquent.

Les arguments optionnels w et iw sont des vecteurs ou le solveur stocke des informations sur son état(voir ode_optional_output pour plus de détails) . Lorsque ces paramêtres sont utilisés comme argument d'entrée, ils permettent de redémarrer l'intégration au point où elle s'était arrêtée à la sortie d'un apple précédent à ode .

Plus d'options peuvent être passées aux solveurs d'ODEPACK en utilisant la variable %ODEOPTIONS . Voir odeoptions .

Examples

    // ---------- EDO Simple  (external : fonction Scilab)
    // dy/dt=y^2-y sin(t)+cos(t), y(0)=0
    function ydot=f(t,y),ydot=y^2-y*sin(t)+cos(t),endfunction
    y0=0;t0=0;t=0:0.1:%pi;
    y=ode(y0,t0,t,f)
    plot(t,y)

    // ---------- EDO Simple  (external : code C)
    ccode=['#include <math.h>'
       'void myode(int *n,double *t,double *y,double *ydot)'
       '{'
       '  ydot[0]=y[0]*y[0]-y[0]*sin(*t)+cos(*t);'
       '}']
    mputl(ccode,TMPDIR+'/myode.c') //create the C file
    ilib_for_link('myode','myode.o',[],'c',TMPDIR+'/Makefile',TMPDIR+'/loader.sce');//compile
    exec(TMPDIR+'/loader.sce') //incremental linking
    y0=0;t0=0;t=0:0.1:%pi;
    y=ode(y0,t0,t,'myode');

    // ---------- Simulation de dx/dt = A x(t) + B u(t) avec u(t)=sin(omega*t),
    // x0=[1;0]
    // solution x(t) desired at t=0.1, 0.2, 0.5 ,1.
    // A and u function are passed to RHS function in a list.
    // B and omega are passed as global variables
    function xdot=linear(t,x,A,u),xdot=A*x+B*u(t),endfunction
    function ut=u(t),ut=sin(omega*t),endfunction
    A=[1 1;0 2];B=[1;1];omega=5;
    ode([1;0],0,[0.1,0.2,0.5,1],list(linear,A,u))

    // ----------Integration de l'équation différentielle de Riccati (état matriciel)
    // Xdot=A'*X + X*A - X'*B*X + C , X(0)=Identity
    // Solution at t=[1,2]
    function Xdot=ric(t,X),Xdot=A'*X+X*A-X'*B*X+C,endfunction
    A=[1,1;0,2]; B=[1,0;0,1]; C=[1,0;0,1];
    t0=0;t=0:0.1:%pi;
    X=ode(eye(A),0,t,ric)
    //
    // ---------- Calcul de exp(A)  (état matriciel)
    A=[1,1;0,2];
    function xdot=f(t,x),xdot=A*x;,endfunction
    ode(eye(A),0,1,f)
    ode("adams",eye(A),0,1,f)

    // ----------  Calcul de exp(A)  (état matriciel, cas raide, jacobien fourni)
    A=[10,0;0,-1];
    function xdot=f(t,x),xdot=A*x,endfunction
    function J=Jacobian(t,y),J=A,endfunction
    ode("stiff",[0;1],0,1,f,Jacobian)

See Also

ode_discrete , ode_root , dassl , impl , odedc , odeoptions , csim , ltitr , rtitr ,

Authors

Alan C. Hindmarsh, mathematics and statistics division, l-316 livermore, ca 94550.19

Bibliography

Alan C. Hindmarsh, lsode and lsodi, two new initial value ordinary differential equation solvers, acm-signum newsletter, vol. 15, no. 4 (1980), pp. 10-11.

Used Function

Les sous programmes associés se trouvent dans le repertoire routines/integ: lsode.f lsoda.f lsodar.f


optim

Scilab Function
Last update : 09/03/2005

optim - non-linear optimization routine

Calling Sequence

[f,xopt]=optim(costf,x0)
[f [,xopt [,gradopt [,work]]]]=optim(costf [,<contr>],x0 [,algo] [,df0 [,mem]] [,work] [,<stop>] [,<params>] [,imp=iflag])

Parameters

  • costf : external, i.e Scilab function list or string ( costf is the cost function: see below its calling sequence (Scilab or Fortran)). See also external for details about external functions.
  • x0 : real vector (initial value of variable to be minimized).
  • f : value of optimal cost ( f=costf(xopt) )
  • xopt : best value of x found.
  • <contr> : keyword representing the following sequence of arguments: 'b',binf,bsup with binf and bsup are real vectors with same dimension as x0 . binf and bsup are lower and upper bounds on x .
  • algo : Character string used to sprecify the algorithm to use. The possible values are 'qn' for quasi-Newton (default) or 'gc' for conjugate gradient or 'nd' for non-differentiable. Note that 'nd' does not accept bounds on x .
  • df0 : real scalar. Guessed decreasing of f at first iteration. ( df0=1 is the default value).
  • mem : integer, number of variables used to approximate the Hessian, ( algo='gc' or 'nd' ). Default value is around 6.
  • <stop> : keyword representing the sequence of optional parameters controlling the convergence of the algorithm. 'ar',nap [,iter [,epsg [,epsf [,epsx]]]]
    • "ar" : reserved keyword for stopping rule selection defined as follows:
    • nap : maximum number of calls to costf allowed (default is 100).
    • iter : maximum number of iterations allowed (default is 100).
    • epsg : threshold on gradient norm.
    • epsf : threshold controlling decreasing of f
    • epsx : threshold controlling variation of x . This vector (possibly matrix) of same size as x0 can be used to scale x .
  • <params> : keyword representing the sequence of arguments: 'ti', valti ,'td', valtd which can be used to pass argument to an external written in C or Fortran (see below).
  • "imp=iflag" : named argument used to set the trace mode. iflag=0 nothing (execpt errors) is reported, iflag=1 initial and final reports, iflag=2 adds a report per iteration, iflag>2 add reports on linear search. Warning, most of these reports are written on the Scilab standard output.
  • gradopt : gradient of costf at xopt
  • work : working array for hot restart for quasi-Newton method. This array is automatically initialized by optim when optim is invoked. It can be used as input parameter to speed-up the calculations.

Description

Non-linear optimization routine for programs without constraints or with bound constraints:

      min costf(x) w.r.t x.

costf is an "external" i.e a Scilab function, a list or a string giving the name of a C or Fortran routine (see "external"). This external must return the value f of the cost function at the point x and the gradient g of the cost function at the point x .

- Scilab function case

If costf is a Scilab function, the calling sequence for costf must be: [f,g,ind]=costf(x,ind)

Here, costf is a function which returns f , value (real number) of cost function at x , and g , gradient vector of cost function at x . The variable ind is described below.
- List case

If costf is a list, it should be of the form: list(real_costf, arg1,...,argn) with real_costf a Scilab function with calling sequence : [f,g,ind]=costf(x,ind,arg1,... argn) . The x , f , g , ind arguments have the same meaning that above. argi arguments can be used to pass function parameters.

- String case

If costf is a character string, it refers to the name of a C or Fortran routine which must be linked to Scilab

* Fortran case

The generic calling sequence for the Fortran subroutine is: subroutine costf(ind,n,x,f,g,ti,tr,td) with the following declarations:

          integer ind,n ti(*)
          double precision x(n),f,g(n),td(*)
          real tr(*)
The argument ind is described below.

The Fortran subroutine costf must return f and the vector g , given x, ind, n, ti, tr,td .

ti,tr,td can be used to initialize parameters. In the calling sequence of optim , the keyword <params>' can be replaced by 'ti', valti ,'td', valtd . Then, the routine costf is evaluated with ti=valti and td=valtd whatever the value of ind . Thus, the Scilab variables valti and valtd (integer vector and real vector) are sent to the routine costf .

* C case

The generic calling sequence for the C procedure is: void costf(int *ind, int *n, double *x, double *f, double *g, int *ti, float *tr, double *td) with the following declarations:

The argument ind is described below.

The C procedure costf must return f and the vector g , given x, ind, n, ti, tr, td .

ti,tr,td can be used to initialize parameters. In the calling sequence of optim , the string 'in' can be replaced by 'ti', valti ,'td', valtd . Then, the procedure costf is evaluated with ti=valti and td=valtd whatever the value of ind . Thus, the Scilab variables valti and valtd (integer vector and real vector) are sent to the procedure costf .

If ind=2 (resp. 3, 4 ), costf must provide f (resp. g, f and g ).

If ind=1 nothing is computed (used for display purposes only).

On output, ind<0 means that f cannot be evaluated at x and ind=0 interrupts the optimization.

Examples

    // External function written in Scilab
    xref=[1;2;3];x0=[1;-1;1]
    deff('[f,g,ind]=cost(x,ind)','f=0.5*norm(x-xref)^2,g=x-xref');
    [f,xopt]=optim(cost,x0)      //Simplest call
    [f,xopt,gopt]=optim(cost,x0,'gc')  // By conjugate gradient
    [f,xopt,gopt]=optim(cost,x0,'nd')  //Seen as non differentiable
    [f,xopt,gopt]=optim(cost,'b',[-1;0;2],[0.5;1;4],x0) //  Bounds on x
    [f,xopt,gopt]=optim(cost,'b',[-1;0;2],[0.5;1;4],x0,'gc') //  Bounds on x
    [f,xopt,gopt]=optim(cost,'b',[-1;0;2],[0.5;1;4],x0,'gc','ar',3)

    // External function written in C (C compiler required)
    // write down the C code (Rosenbrock problem)
    C=['#include <math.h>'
    'double sq(double x)'
    '{ return x*x;}'
    'void rosenc(int *ind, int *n, double *x, double *f, double *g, '
    '                                int *ti, float *tr, double *td)'
    '{'
    '  double p;'
    '  int i;'
    '  p=td[0];'
    '  if (*ind==2||*ind==4) {'
    '    *f=1.0;'
    '    for (i=1;i<*n;i++)'
    '      *f+=p*sq(x[i]-sq(x[i-1]))+sq(1.0-x[i]);'
    '  }'
    '  if (*ind==3||*ind==4) {'
    '    g[0]=-4.0*p*(x[1]-sq(x[0]))*x[0];'
    '    for (i=1;i<*n-1;i++)'
    '      g[i]=2.0*p*(x[i]-sq(x[i-1]))-4.0*p*(x[i+1]-sq(x[i]))*x[i]-2.0*(1.0-x[i]);'
    '    g[*n-1]=2.0*p*(x[*n-1]-sq(x[*n-2]))-2.0*(1.0-x[*n-1]);'
    '  }'
    '}'];
    mputl(C,TMPDIR+'/rosenc.c')
    // compile the C code
    l=ilib_for_link('rosenc','rosenc.o',[],'c',TMPDIR+'/Makefile');
    // incremental linking
    link(l,'rosenc','c')
    //solve the problem
    x0=[40;10;50];
    p=100;
    [f,xo,go]=optim('rosenc',x0,'td',p)

    // External function written in Fortran (Fortran compiler required)
    // write down the Fortran  code (Rosenbrock problem)
 F=[ '      subroutine rosenf(ind, n, x, f, g, ti, tr, td)'
     '      integer ind,n,ti(*)'
     '      double precision x(n),f,g(n),td(*)'
     '      real tr(*)'
     'c'
     '      double precision y,p'
     '      p=td(1)'
     '      if (ind.eq.2.or.ind.eq.4) then'
     '        f=1.0d0'
     '        do i=2,n'
     '          f=f+p*(x(i)-x(i-1)**2)**2+(1.0d0-x(i))**2'
     '        enddo'
     '      endif'
     '      if (ind.eq.3.or.ind.eq.4) then'
     '        g(1)=-4.0d0*p*(x(2)-x(1)**2)*x(1)'
     '        if(n.gt.2) then'
     '          do i=2,n-1'
     '            g(i)=2.0d0*p*(x(i)-x(i-1)**2)-4.0d0*p*(x(i+1)-x(i)**2)*x(i)'
     '     &           -2.0d0*(1.0d0-x(i))'
     '          enddo'
     '        endif'
     '        g(n)=2.0d0*p*(x(n)-x(n-1)**2)-2.0d0*(1.0d0-x(n))'
     '      endif'
     '      return'
     '      end'];

    mputl(F,TMPDIR+'/rosenf.f')
    // compile the Fortran code
    l=ilib_for_link('rosenf','rosenf.o',[],'f',TMPDIR+'/Makefile');
    // incremental linking
    link(l,'rosenf','f')
    //solve the problem
    x0=[40;10;50];
    p=100;
    [f,xo,go]=optim('rosenf',x0,'td',p)

See Also

external , quapro , linpro , datafit , leastsq , numdiff , derivative , NDcost ,


qld

Scilab Function
Last update : 24/06/2005

qld - linear quadratic programming solver

Calling Sequence

[x,lagr]=qld(Q,p,C,b,ci,cs,me [,tol])
[x,lagr,info]=qld(Q,p,C,b,ci,cs,me [,tol])

Parameters

  • Q : real positive definite symmetric matrix (dimension n x n ).
  • p : real (column) vector (dimension n )
  • C : real matrix (dimension (me + md) x n )
  • b : RHS column vector (dimension (me + md) )
  • ci : column vector of lower-bounds (dimension n ). If there are no lower bound constraints, put ci = [] . If some components of x are bounded from below, set the other (unconstrained) values of ci to a very large negative number (e.g. ci(j) = -number_properties('huge') .
  • cs : column vector of upper-bounds. (Same remarks as above).
  • me : number of equality constraints (i.e. C(1:me,:)*x = b(1:me) )
  • tol :Floatting point number, required précision.
  • x : optimal solution found.
  • lagr : vector of Lagrange multipliers. If lower and upper-bounds ci,cs are provided, lagr has n + me + md components and lagr(1:n) is the Lagrange vector associated with the bound constraints and lagr (n+1 : n + me + md) is the Lagrange vector associated with the linear constraints. (If an upper-bound (resp. lower-bound) constraint i is active lagr(i) is > 0 (resp. <0). If no bounds are provided, lagr has only me + md components.
  • info : integer, return the execution status instead of sending errors.

    info==1 : Too many iterations needed

    info==2 : Accuracy insufficient to statisfy convergence criterion

    info==5 : Length of working array is too short

    info==10: The constraints are inconsistent

Description

Minimize 0.5*x'*Q*x + p'*x

under the constraints

 C(j,:) x = b(j),  j=1,...,me
 C(j,:) x <= b(j), j=me+1,...,me+md
 ci <= x <= cs

This function requires Q to be positive definite, if it is not the case, one may use the quapro function.

Examples

//Find x in R^6 such that:
//C1*x = b1 (3 equality constraints i.e me=3)
C1= [1,-1,1,0,3,1;
    -1,0,-3,-4,5,6;
     2,5,3,0,1,0];
b1=[1;2;3];
//C2*x <= b2 (2 inequality constraints)
C2=[0,1,0,1,2,-1;
    -1,0,2,1,1,0];
b2=[-1;2.5];
//with  x between ci and cs:
ci=[-1000;-10000;0;-1000;-1000;-1000];cs=[10000;100;1.5;100;100;1000];
//and minimize 0.5*x'*Q*x + p'*x with
p=[1;2;3;4;5;6]; Q=eye(6,6);
//No initial point is given;
C=[C1;C2] ; //
b=[b1;b2] ;  //
me=3;
[x,lagr]=qld(Q,p,C,b,ci,cs,me)
//Only linear constraints (1 to 4) are active (lagr(1:6)=0):

See Also

quapro , optim ,

Authors

K.Schittkowski, University of Bayreuth, Germany
A.L. Tits and J.L. Zhou , University of Maryland

Used Function

ql0001.f in routines/optim directory


quapro

Scilab Function
Last update : 29/06/2005

quapro - linear quadratic programming solver

Calling Sequence

[x,lagr,f]=quapro(Q,p,C,b [,x0])
[x,lagr,f]=quapro(Q,p,C,b,ci,cs [,x0])
[x,lagr,f]=quapro(Q,p,C,b,ci,cs,me [,x0])
[x,lagr,f]=quapro(Q,p,C,b,ci,cs,me,x0 [,imp])

Parameters

  • Q : real symmetric matrix (dimension n x n ).
  • p : real (column) vector (dimension n )
  • C : real matrix (dimension (me + md) x n ) (If no constraints are given, you can set C = [] )
  • b : RHS column vector (dimension (me + md) ) (If no constraints are given, you can set b = [] )
  • ci : column vector of lower-bounds (dimension n ). If there are no lower bound constraints, put ci = [] . If some components of x are bounded from below, set the other (unconstrained) values of ci to a very large negative number (e.g. ci(j) = -number_properties('huge') .
  • cs : column vector of upper-bounds. (Same remarks as above).
  • me : number of equality constraints (i.e. C(1:me,:)*x = b(1:me) )
  • x0 : either an initial guess for x or one of the character strings 'v' or 'g' . If x0='v' the calculated initial feasible point is a vertex. If x0='g' the calculated initial feasible point is arbitrary.
  • imp : verbose option (optional parameter) (Try imp=7,8,... ). warning the message are output in the window where scilab has been started.
  • x : optimal solution found.
  • f : optimal value of the cost function (i.e. f=0.5*x'*Q*x+p' ).
  • lagr : vector of Lagrange multipliers. If lower and upper-bounds ci,cs are provided, lagr has n + me + md components and lagr(1:n) is the Lagrange vector associated with the bound constraints and lagr (n+1 : n + me + md) is the Lagrange vector associated with the linear constraints. (If an upper-bound (resp. lower-bound) constraint i is active lagr(i) is > 0 (resp. <0). If no bounds are provided, lagr has only me + md components.

Description

Minimize 0.5*x'*Q*x + p'*x

under the constraint

C*x <= b

Minimize 0.5*x'*Q*x + p'*x

under the constraints

C*x <= b          ci <= x <= cs

Minimize 0.5*x'*Q*x + p'*x

under the constraints

 C(j,:) x = b(j),  j=1,...,me
 C(j,:) x <= b(j), j=me+1,...,me+md
 ci <= x <= cs

If no initial point is given the program computes a feasible initial point which is a vertex of the region of feasible points if x0='v' .

If x0='g' , the program computes a feasible initial point which is not necessarily a vertex. This mode is advisable when the quadratic form is positive definite and there are few constraints in the problem or when there are large bounds on the variables that are just security bounds and very likely not active at the optimal solution.

Note that Q is not necessarily non-negative, i.e. Q may have negative eigenvalues.

Examples

//Find x in R^6 such that:
//C1*x = b1 (3 equality constraints i.e me=3)
C1= [1,-1,1,0,3,1;
    -1,0,-3,-4,5,6;
     2,5,3,0,1,0];
b1=[1;2;3];
//C2*x <= b2 (2 inequality constraints)
C2=[0,1,0,1,2,-1;
    -1,0,2,1,1,0];
b2=[-1;2.5];
//with  x between ci and cs:
ci=[-1000;-10000;0;-1000;-1000;-1000];cs=[10000;100;1.5;100;100;1000];
//and minimize 0.5*x'*Q*x + p'*x with
p=[1;2;3;4;5;6]; Q=eye(6,6);
//No initial point is given;
C=[C1;C2] ; //
b=[b1;b2] ;  //
me=3;
[x,lagr,f]=quapro(Q,p,C,b,ci,cs,me)
//Only linear constraints (1 to 4) are active (lagr(1:6)=0):
[x,lagr,f]=quapro(Q,p,C,b,[],[],me)   //Same result as above

See Also

qld , linpro , optim ,

Authors

Eduardo Casas Renteria, Universidad de Cantabria,
Cecilia Pola Mendez , Universidad de Cantabria

Used Function

in routines/optim directory (authors E.Casas, C. Pola Mendez):

anfm01.f anfm03.f anfm05.f anrs01.f auxo01.f dimp03.f dnrm0.f optr03.f pasr03.f zthz.f anfm02.f anfm04.f anfm06.f anrs02.f desr03.f dipvtf.f optr01.f opvf03.f plcbas.f

From BLAS library

daxpy.f dcopy.f ddot.f dnrm2.f dscal.f dswap.f idamax.f

in routines/calelm directory (authors INRIA):

add.f ddif.f dmmul.f

From LAPACK library : dlamch.f


semidef

Scilab Function
Last update : 12/01/2004

semidef - semidefinite programming

Calling Sequence

[x,Z,ul,info]=semidef(x0,Z0,F,blck_szs,c,options)

Parameters

  • x0 : m x 1 real column vector (must be strictly primal feasible, see below)
  • Z0 : L x 1 real vector (compressed form of a strictly feasible dual matrix, see below)
  • F : L x (m+1) real matrix
  • blck_szs : p x 2 integer matrix (sizes of the blocks) defining the dimensions of the (square) diagonal blocks size(Fi(j)=blck_szs(j) j=1,...,m+1 .
  • c : m x 1 real vector
  • options : row vector with five entries [nu,abstol,reltol,0,maxiters]
  • ul : row vector with two entries

Description

[x,Z,ul,info]=semidef(x0,Z0,F,blck_szs,c,options) solves semidefinite program:

    minimize    c'*x
    subject to  F_0 + x_1*F_1 + ... + x_m*F_m  >= 0

 and its dual

    maximize    -Tr F_0 Z
    subject to  Tr F_i Z = c_i, i=1,...,m
                Z >= 0

exploiting block structure in the matrices F_i.

It interfaces L. Vandenberghe and S. Boyd sp.c program.

The Fi's matrices are stored columnwise in F in compressed format: if F_i^j, i=0,..,m, j=1,...,L denote the jth (symmetric) diagonal block of F_i, then

    [ pack(F_0^1)  pack(F_1^1) ...  pack(F_m^1) ]
    [ pack(F_0^2)  pack(F_1^2) ...  pack(F_m^2) ]
F=  [   ...       ...          ...              ]
    [ pack(F_0^L)  pack(F_1^L) ...  pack(F_m^L) ]

where pack(M) , for symmetric M , is the vector [M(1,1);M(1,2);...;M(1,n);M(2,2);M(2,3);...;M(2,n);...;M(n,n)] (obtained by scanning columnwise the lower triangular part of M ).

blck_szs gives the size of block j , ie, size(F_i^j)=blck_szs(j) .

Z is a block diagonal matrix with L blocks Z^0, ..., Z^{L-1} . Z^j has size blck_szs[j] times blck_szs[j] . Every block is stored using packed storage of the lower triangular part.

The 2 vector ul contains the primal objective value c'*x and the dual objective value -Tr F_0*Z .

The entries of options are respectively: nu = a real parameter which ntrols the rate of convergence. abstol = absolute tolerance. reltol = relative tolerance (has a special meaning when negative). tv target value, only referenced if reltol < 0 . iters = on entry: maximum number of iterations >= 0, on exit: the number of iterations taken.

info returns 1 if maxiters exceeded, 2 if absolute accuracy is reached, 3 if relative accuracy is reached, 4 if target value is reached, 5 if target value is not achievable; negative values indicate errors.

Convergence criterion:

 (1) maxiters is exceeded
 (2) duality gap is less than abstol
 (3) primal and dual objective are both positive and
     duality gap is less than (reltol * dual objective)
     or primal and dual objective are both negative and
     duality gap is less than (reltol * minus the primal objective)
 (4) reltol is negative and
     primal objective is less than tv or dual objective is greater
     than tv

Examples

F0=[2,1,0,0;
    1,2,0,0;
    0,0,3,1
    0,0,1,3];
F1=[1,2,0,0;
    2,1,0,0;
    0,0,1,3;
    0,0,3,1]
F2=[2,2,0,0;
    2,2,0,0;
    0,0,3,4;
    0,0,4,4];
blck_szs=[2,2];
F01=F0(1:2,1:2);F02=F0(3:4,3:4);
F11=F1(1:2,1:2);F12=F1(3:4,3:4);
F21=F2(1:2,1:2);F22=F2(3:4,3:4);
x0=[0;0]
Z0=2*F0;
Z01=Z0(1:2,1:2);Z02=Z0(3:4,3:4);
FF=[[F01(:);F02(:)],[F11(:);F12(:)],[F21(:);F22(:)]]
ZZ0=[[Z01(:);Z02(:)]];
c=[trace(F1*Z0);trace(F2*Z0)];
options=[10,1.d-10,1.d-10,0,50];
[x,Z,ul,info]=semidef(x0,pack(ZZ0),pack(FF),blck_szs,c,options)
w=vec2list(unpack(Z,blck_szs),[blck_szs;blck_szs]);Z=sysdiag(w(1),w(2))
c'*x+trace(F0*Z)
spec(F0+F1*x(1)+F2*x(2))
trace(F1*Z)-c(1)
trace(F2*Z)-c(2)


NDcost

Scilab Function
Last update : 11/03/2005

NDcost - generic external for optim computing gradient using finite differences

Calling Sequence

[f,g,ind]=NDcost(x,ind,fun,varargin)

Parameters

  • x : real vector or matrix
  • ind : integer parameter (see optim)
  • fun : Scilab function with calling sequence F=fun(x,varargin) varargin may be use to pass parameters p1,...pn
  • f : criterion value at point x (see optim)
  • g : gradient value at point x (see optim)

Description

This function can be used as an external for optim to minimize problem where gradient is too complicated to be programmed. only the function fun which computes the criterion is required.

This function should be used as follow: [f,xopt,gopt]=optim(list(NDcost,fun,p1,...pn),x0,...)

Examples

// example #1 (a simple one)
//function to minimize
function f=rosenbrock(x,varargin)
   p=varargin(1)
   f=1+sum( p*(x(2:$)-x(1:$-1)^2)^2 + (1-x(2:$))^2)
endfunction

x0=[1;2;3;4];
[f,xopt,gopt]=optim(list(NDcost,rosenbrock,200),x0)

// example #2: this example (from Rainer von Seggern) shows a quick (*) scilab way
//             to identify the parameters of a linear differential equation.
//             The model is a simple damped (linear) oscillator:
//
//               x''(t) + c x'(t) + k x(t) = 0
//
// and we write it as a system of (2) differential equations of first
// order with y(1) = x, and y(2) = x':
//
//     dy1/dt = y(2)
//     dy2/dt = -c*y(2) -k*y(1)
//
// We suppose to have m measures of x (that is y(1)) at different times
// t_obs(1), ..., t_obs(m) called x_obs(1), ..., x_obs(m)  (in this example
// these measures will be simulated) and we want to find the parameters
// c and k by minimizing the sum of square errors between x_obs and y1(t_obs,p)
//
// (*) This method is not the most efficient but is easy to implement.

function dy = DEQ(t,y,p)
   // the rhs of our first order differential equation system
   c =p(1);k=p(2)
   dy=[y(2);-c*y(2)-k*y(1)]
endfunction

function y=uN(p, t, t0, y0)
   // Numerical solution get with ode (in this case an exact analytic
   // solution is found easily but ode could work for any equations...)
   // Note: the ode output must be an approximation of the solution at
   //       times given in the vector t=[t(1),...,t($)]
   y = ode(y0,t0,t,list(DEQ,p))
endfunction

function r = cost_func(p, t_obs, x_obs, t0, y0)
   // the function to be minimized : this is the sum of the squared
   // errors between what gives the model and the measuments
   sol = uN(p, t_obs, t0, y0)
   e = sol(1,:) - x_obs
   r = sum(e.*e)
endfunction

// Datas
t0 = 0; y0 = [10;0]; // initial time and initial conditions
T = 30;  // final time for measurements

// Here we simulate experimental datas (from which the parameters
// should be found)
pe = [0.2;3];  // exact parameters
m = 60;  t_obs = linspace(t0+2,T,m); // observation times
sigma = 2;   // noise level
y_obs = uN(pe, t_obs, t0, y0);
x_obs = y_obs(1,:) + grand(1,m,"nor",0, sigma);

// initial guess parameters
p0 = [0.5 ; 5];

// for information the cost function before optimization:
cost0 = cost_func(p0, t_obs, x_obs, t0, y0);
mprintf("\n\r cost function before optimization = %g",cost0)

// Solution with optim
[costopt,popt]=optim(list(NDcost,cost_func, t_obs, x_obs, t0, y0),p0); //,'ar',40,40,1e-3);

mprintf("\n\r cost function after optimization = %g",costopt)
mprintf("\n\r values of the parameters found: c = %g, k = %g",popt(1),popt(2))

// a small plot
t = linspace(0,T,400);
y = uN(popt, t, t0, y0);
clf();
plot2d(t',y(1,:)',style=2)
plot2d(t_obs',y_obs(1,:)',style=-2)
legend(["model","measures"]);
xtitle("least square fit to identify ode parameters")

See Also

optim , external , derivative ,


Traitement du signal
Signal - Signal manual description
analpf - create analog low-pass filter
buttmag - response of Butterworth filter
casc - cascade realization of filter from coefficients
cepstrum - cepstrum calculation
cheb1mag - response of Chebyshev type 1 filter
cheb2mag - response of type 2 Chebyshev filter
chepol - Chebychev polynomial
convol - convolution
corr - correlation, covariance
cspect - spectral estimation (correlation method)
czt - chirp z-transform algorithm
detrend - remove constant, linear or piecewise linear trend from a vector
dft - discrete Fourier transform
ell1mag - magnitude of elliptic filter
eqfir - minimax approximation of FIR filter
eqiir - Design of iir filters
faurre - filter computation by simple Faurre algorithm
ffilt - coefficients of FIR low-pass
fft - fast Fourier transform.
ifft - fast Fourier transform.
fft2 - two-dimension fast Fourier transform
fftshift - rearranges the fft output, moving the zero frequency to the center of the spectrum
filter - modelling filter
find_freq - parameter compatibility for elliptic filter design
findm - for elliptic filter design
frfit - frequency response fit
frmag - magnitude of FIR and IIR filters
fsfirlin - design of FIR, linear phase filters, frequency sampling technique
group - group delay for digital filter
hank - covariance to hankel matrix
hilb - Hilbert transform
iir - iir digital filter
iirgroup - group delay Lp IIR filter optimization
iirlp - Lp IIR filter optimization
intdec - Changes sampling rate of a signal
jmat - row or column block permutation
kalm - Kalman update
lattn - recursive solution of normal equations
lattp - lattp
lev - Yule-Walker equations (Levinson's algorithm)
levin - Toeplitz system solver by Levinson algorithm (multidimensional)
lgfft - utility for fft
lindquist - Lindquist's algorithm
mese - maximum entropy spectral estimation
mfft - multi-dimensional fft
mrfit - frequency response fit
%asn - elliptic integral
%k - Jacobi's complete elliptic integral
%sn - Jacobi 's elliptic function
phc - Markovian representation
pspect - cross-spectral estimate between 2 series
remez - Remez's algorithm
remezb - Minimax approximation of magnitude response
rpem - RPEM estimation
sinc - samples of sinc function
sincd - digital sinc function or Direchlet kernel
srfaur - square-root algorithm
srkf - square root Kalman filter
sskf - steady-state Kalman filter
system - observation update
trans - low-pass to other filter transform
wfir - linear-phase FIR filters
wiener - Wiener estimate
wigner - 'time-frequency' wigner spectrum
window - compute symmetric window of various type
yulewalk - least-square filter design
zpbutt - Butterworth analog filter
zpch1 - Chebyshev analog filter
zpch2 - Chebyshev analog filter
zpell - lowpass elliptic filter


analpf

Scilab Function
Last update : 12/01/2004

analpf - create analog low-pass filter

Calling Sequence

[hs,pols,zers,gain]=analpf(n,fdesign,rp,omega)

Parameters

  • n : positive integer : filter order
  • fdesign : string : filter design method : 'butt' or 'cheb1' or 'cheb2' or 'ellip'
  • rp : 2-vector of error values for cheb1, cheb2 and ellip filters where only rp(1) is used for cheb1 case, only rp(2) is used for cheb2 case, and rp(1) and rp(2) are both used for ellip case. 0<rp(1),rp(2)<1
    • - for cheb1 filters 1-rp(1)<ripple<1 in passband
    • - for cheb2 filters 0<ripple<rp(2) in stopband
    • - for ellip filters 1-rp(1)<ripple<1 in passband 0<ripple<rp(2) in stopband
  • omega : cut-off frequency of low-pass filter in Hertz
  • hs : rational polynomial transfer function
  • pols : poles of transfer function
  • zers : zeros of transfer function
  • gain : gain of transfer function

Description

Creates analog low-pass filter with cut-off frequency at omega.

hs=gain*poly(zers,'s')/poly(pols,'s')

Examples

//Evaluate magnitude response of continuous-time system
hs=analpf(4,'cheb1',[.1 0],5)
fr=0:.1:15;
hf=freq(hs(2),hs(3),%i*fr);
hm=abs(hf);
plot(fr,hm)

Author

C. B.


buttmag

Scilab Function
Last update : 12/01/2004

buttmag - response of Butterworth filter

Calling Sequence

[h]=buttmag(order,omegac,sample)

Parameters

  • order : integer : filter order
  • omegac : real : cut-off frequency in Hertz
  • sample : vector of frequency where buttmag is evaluated
  • h : Butterworth filter values at sample points

Description

squared magnitude response of a Butterworth filter omegac = cutoff frequency ; sample = sample of frequencies

Examples

//squared magnitude response of Butterworth filter
h=buttmag(13,300,1:1000);
mag=20*log(h)'/log(10);
plot2d((1:1000)',mag,[2],"011"," ",[0,-180,1000,20])

Author

F. D.


casc

Scilab Function
Last update : 12/01/2004

casc - cascade realization of filter from coefficients

Calling Sequence

[cels]=casc(x,z)

Parameters

  • x : (4xN)-matrix where each column is a cascade element, the first two column entries being the numerator coefficients and the second two column entries being the denominator coefficients
  • z : string representing the cascade variable
  • cels : resulting cascade representation

Description

Creates cascade realization of filter from a matrix of coefficients (utility function).

Examples

x=[1,2,3;4,5,6;7,8,9;10,11,12]
cels=casc(x,'z')


cepstrum

Scilab Function
Last update : 12/01/2004

cepstrum - cepstrum calculation

Calling Sequence

fresp = cepstrum(w,mag)

Parameters

  • w : positive real vector of frequencies (rad/sec)
  • mag : real vector of magnitudes (same size as w )
  • fresp : complex vector

Description

fresp = cepstrum(w,mag) returns a frequency response fresp(i) whose magnitude at frequency w(i) equals mag(i) and such that the phase of freq corresponds to a stable and minimum phase system. w needs not to be sorted, but minimal entry should not be close to zero and all the entries of w should be different.

Examples

w=0.1:0.1:5;mag=1+abs(sin(w));
fresp=cepstrum(w,mag);
plot2d([w',w'],[mag(:),abs(fresp)])

See Also

frfit ,


cheb1mag

Scilab Function
Last update : 13/12/2005

cheb1mag - response of Chebyshev type 1 filter

Calling Sequence

[h2]=cheb1mag(n,omegac,epsilon,sample)

Parameters

  • n : integer : filter order
  • omegac : real : cut-off frequency
  • epsilon : real : ripple in pass band
  • sample : vector of frequencies where cheb1mag is evaluated
  • h2 : Chebyshev I filter values at sample points

Description

Square magnitude response of a type 1 Chebyshev filter.

omegac =passband edge.

epsilon : such that 1/(1+epsilon^2) =passband ripple.

sample : vector of frequencies where the square magnitude is desired.

Examples

//Chebyshev; ripple in the passband
n=13;epsilon=0.2;omegac=3;sample=0:0.05:10;
h=cheb1mag(n,omegac,epsilon,sample);
plot2d(sample,h)
xtitle('','frequencies','magnitude')

See Also

buttmag ,


cheb2mag

Scilab Function
Last update : 12/01/2004

cheb2mag - response of type 2 Chebyshev filter

Calling Sequence

[h2]=cheb2mag(n,omegar,A,sample)

Parameters

  • n : integer ; filter order
  • omegar : real scalar : cut-off frequency
  • A : attenuation in stop band
  • sample : vector of frequencies where cheb2mag is evaluated
  • h2 : vector of Chebyshev II filter values at sample points

Description

Square magnitude response of a type 2 Chebyshev filter.

omegar = stopband edge, sample = vector of frequencies where the square magnitude h2 is desired.

Examples

//Chebyshev; ripple in the stopband
n=10;omegar=6;A=1/0.2;sample=0.0001:0.05:10;
h2=cheb2mag(n,omegar,A,sample);
plot(sample,log(h2)/log(10),'frequencies','magnitude in dB')
//Plotting of frequency edges
minval=(-maxi(-log(h2)))/log(10);
plot2d([omegar;omegar],[minval;0],[2],"000");
//Computation of the attenuation in dB at the stopband edge
attenuation=-log(A*A)/log(10);
plot2d(sample',attenuation*ones(sample)',[5],"000")

See Also

cheb1mag ,


chepol

Scilab Function
Last update : 12/01/2004

chepol - Chebychev polynomial

Calling Sequence

[Tn]=chepol(n,var)

Parameters

  • n : integer : polynomial order
  • var : string : polynomial variable
  • Tn : polynomial in the variable var

Description

Recursive implementation of Chebychev polynomial. Tn=2*poly(0,var)*chepol(n-1,var)-chepol(n-2,var) with T0=1 and T1=poly(0,var) .

Examples

chepol(4,'x')

Author

F. D.


convol

Scilab Function
Last update : 12/01/2004

convol - convolution

Calling Sequence

[y]=convol(h,x)
[y,e1]=convol(h,x,e0)

Parameters

  • x,h :input sequences ( h is a "short" sequence, x a "long" one)
  • e0 : old tail to overlap add (not used in first call)
  • y : output of convolution
  • e1 : new tail to overlap add (not used in last call)

Description

calculates the convolution y= h*x of two discrete sequences by using the fft. Overlap add method can be used.

USE OF OVERLAP ADD METHOD:
For x=[x1,x2,...,xNm1,xN]
First call is [y1,e1]=convol(h,x1);
Subsequent calls : [yk,ek]=convol(h,xk,ekm1);
Final call : [yN]=convol(h,xN,eNm1);
Finally y=[y1,y2,...,yNm1,yN]

Examples

x=1:3;
h1=[1,0,0,0,0];h2=[0,1,0,0,0];h3=[0,0,1,0,0];
x1=convol(h1,x),x2=convol(h2,x),x3=convol(h3,x),
convol(h1+h2+h3,x)
p1=poly(x,'x','coeff')
p2=poly(h1+h2+h3,'x','coeff')
p1*p2

See Also

corr , fft , pspect ,

Author

F. D , C. Bunks Date 3 Oct. 1988; ;


corr

Scilab Function
Last update : 12/01/2004

corr - correlation, covariance

Calling Sequence

[cov,Mean]=corr(x,[y],nlags)
[cov,Mean]=corr('fft',xmacro,[ymacro],n,sect)
[w,xu]=corr('updt',x1,[y1],w0)
[w,xu]=corr('updt',x2,[y2],w,xu)
...
[wk]=corr('updt',xk,[yk],w,xu)

Parameters

  • x : a real vector
  • y : a real vector, default value x.
  • nlags : integer, number of correlation coefficients desired.
  • xmacro : a scilab external (see below).
  • ymacro : a scilab external (see below), default value xmacro
  • n : an integer, total size of the sequence (see below).
  • sect : size of sections of the sequence (see below).
  • xi : a real vector
  • yi : a real vector,default value xi.
  • cov : real vector, the correlation coefficients
  • Mean : real number or vector, the mean of x and if given y

Description

Computes

                n - m
                 ====
                 \                                                 1
        cov(m) =  >        (x(k)  - xmean) (y(m+k)      - ymean) * ---
                 /                                                  n
                 ====
                 k = 1

for m=0,.., nlag-1 and two vectors x=[x(1),..,x(n)] y=[y(1),..,y(n)]

Note that if x and y sequences are differents corr(x,y,...) is different with corr(y,x,...)

Short sequences [cov,Mean]=corr(x,[y],nlags) returns the first nlags correlation coefficients and Mean = mean(x) (mean of [x,y] if y is an argument). The sequence x (resp. y ) is assumed real, and x and y are of same dimension n.
Long sequences [cov,Mean]=corr('fft',xmacro,[ymacro],n,sect) Here xmacro is either

a function of type [xx]=xmacro(sect,istart) which returns a vector xx of dimension nsect containing the part of the sequence with indices from istart to istart+sect-1 .

a fortran subroutine or C procedure which performs the same calculation. (See the source code of dgetx for an example). n = total size of the sequence. sect = size of sections of the sequence. sect must be a power of 2. cov has dimension sect . Calculation is performed by FFT.

Updating method

    [w,xu]=corr('updt',x1,[y1],w0)
    [w,xu]=corr('updt',x2,[y2],w,xu)
     ...
    wk=corr('updt',xk,[yk],w,xu)

With this calling sequence the calculation is updated at each call to corr .

    w0 = 0*ones(1,2*nlags);
    nlags = power of 2.

x1,x2,... are parts of x such that x=[x1,x2,...] and sizes of xi a power of 2. To get nlags coefficients a final fft must be performed c=fft(w,1)/n ; cov=c(1nlags) ( n is the size of x (y) ). Caution: this calling sequence assumes that xmean = ymean = 0 .

Examples

x=%pi/10:%pi/10:102.4*%pi;
rand('seed');rand('normal');
y=[.8*sin(x)+.8*sin(2*x)+rand(x);.8*sin(x)+.8*sin(1.99*x)+rand(x)];
c=[];
for j=1:2,for k=1:2,c=[c;corr(y(k,:),y(j,:),64)];end;end;
c=matrix(c,2,128);cov=[];
for j=1:64,cov=[cov;c(:,(j-1)*2+1:2*j)];end;
rand('unif')
//
rand('normal');x=rand(1,256);y=-x;
deff('[z]=xx(inc,is)','z=x(is:is+inc-1)');
deff('[z]=yy(inc,is)','z=y(is:is+inc-1)');
[c,mxy]=corr(x,y,32);
x=x-mxy(1)*ones(x);y=y-mxy(2)*ones(y);  //centring
c1=corr(x,y,32);c2=corr(x,32);
norm(c1+c2,1)
[c3,m3]=corr('fft',xx,yy,256,32);
norm(c1-c3,1)
[c4,m4]=corr('fft',xx,256,32);
norm(m3,1),norm(m4,1)
norm(c3-c1,1),norm(c4-c2,1)
x1=x(1:128);x2=x(129:256);
y1=y(1:128);y2=y(129:256);
w0=0*ones(1:64);   //32 coeffs
[w1,xu]=corr('u',x1,y1,w0);w2=corr('u',x2,y2,w1,xu);
zz=real(fft(w2,1))/256;c5=zz(1:32);
norm(c5-c1,1)
[w1,xu]=corr('u',x1,w0);w2=corr('u',x2,w1,xu);
zz=real(fft(w2,1))/256;c6=zz(1:32);
norm(c6-c2,1)
rand('unif')
// test for Fortran or C external
//
deff('[y]=xmacro(sec,ist)','y=sin(ist:(ist+sec-1))');
x=xmacro(100,1);
[cc1,mm1]=corr(x,2^3);
[cc,mm]=corr('fft',xmacro,100,2^3);
[cc2,mm2]=corr('fft','corexx',100,2^3);
[maxi(abs(cc-cc1)),maxi(abs(mm-mm1)),maxi(abs(cc-cc2)),maxi(abs(mm-mm2))]

deff('[y]=ymacro(sec,ist)','y=cos(ist:(ist+sec-1))');
y=ymacro(100,1);
[cc1,mm1]=corr(x,y,2^3);
[cc,mm]=corr('fft',xmacro,ymacro,100,2^3);
[cc2,mm2]=corr('fft','corexx','corexy',100,2^3);
[maxi(abs(cc-cc1)),maxi(abs(mm-mm1)),maxi(abs(cc-cc2)),maxi(abs(mm-mm2))]

See Also

fft ,


cspect

Scilab Function
Last update : 12/01/2004

cspect - spectral estimation (correlation method)

Calling Sequence

[sm,cwp]=cspect(nlags,ntp,wtype,x,y,wpar)

Parameters

  • x : data if vector, amount of input data if scalar
  • y : data if vector, amount of input data if scalar
  • nlags : number of correlation lags (positive integer)
  • ntp : number of transform points (positive integer)
  • wtype : string : 're','tr','hm','hn','kr','ch' (window type)
  • wpar : optional window parameters for wtype='kr', wpar>0 and for wtype='ch', 0 < wpar(1) < .5, wpar(2) > 0
  • sm : power spectral estimate in the interval [0,1]
  • cwp : calculated value of unspecified Chebyshev window parameter

Description

Spectral estimation using the correlation method. Cross-spectral estimate of x and y is calculated when both x and y are given. Auto-spectral estimate of x is calculated if y is not given.

Examples

rand('normal');rand('seed',0);
x=rand(1:1024-33+1);
//make low-pass filter with eqfir
nf=33;bedge=[0 .1;.125 .5];des=[1 0];wate=[1 1];
h=eqfir(nf,bedge,des,wate);
//filter white data to obtain colored data
h1=[h 0*ones(1:maxi(size(x))-1)];
x1=[x 0*ones(1:maxi(size(h))-1)];
hf=fft(h1,-1);   xf=fft(x1,-1);yf=hf.*xf;y=real(fft(yf,1));
sm=cspect(100,200,'tr',y);
smsize=maxi(size(sm));fr=(1:smsize)/smsize;
plot(fr,log(sm))

See Also

pspect ,

Author

C. Bunks ; Digital Signal Processing by Oppenheim and Schafer


czt

Scilab Function
Last update : 12/01/2004

czt - chirp z-transform algorithm

Calling Sequence

[czx]=czt(x,m,w,phi,a,theta)

Parameters

  • x : input data sequence
  • m : czt is evaluated at m points in z-plane
  • w : magnitude multiplier
  • phi : phase increment
  • a : initial magnitude
  • theta : initial phase
  • czx : chirp z-transform output

Description

chirp z-transform algorithm which calcultes the z-transform on a spiral in the z-plane at the points [a*exp(j*theta)][w^kexp(j*k*phi)] for k=0,1,...,m-1 .

Examples

a=.7*exp(%i*%pi/6);
[ffr,bds]=xgetech(); //preserve current context
rect=[-1.2,-1.2*sqrt(2),1.2,1.2*sqrt(2)];
t=2*%pi*(0:179)/179;xsetech([0,0,0.5,1]);
plot2d(sin(t)',cos(t)',[2],"012",' ',rect)
plot2d([0 real(a)]',[0 imag(a)]',[3],"000")
xsegs([-1.0,0;1.0,0],[0,-1.0;0,1.0])
w0=.93*exp(-%i*%pi/15);w=exp(-(0:9)*log(w0));z=a*w;
zr=real(z);zi=imag(z);
plot2d(zr',zi',[5],"000")
xsetech([0.5,0,0.5,1]);
plot2d(sin(t)',cos(t)',[2],"012",' ',rect)
plot2d([0 real(a)]',[0 imag(a)]',[-1],"000")
xsegs([-1.0,0;1.0,0],[0,-1.0;0,1.0])
w0=w0/(.93*.93);w=exp(-(0:9)*log(w0));z=a*w;
zr=real(z);zi=imag(z);
plot2d(zr',zi',[5],"000")
xsetech(ffr,bds); //restore context

Author

C. Bunks


detrend

Scilab Function
Last update : 16/05/2005

detrend - remove constant, linear or piecewise linear trend from a vector

Calling Sequence

y = detrend(x)
y = detrend(x,flag)
y = detrend(x,flag,bp)

Parameters

  • x : vector or matrix of real or complex numbers (the signal to treat)
  • flag : a string equal to "linear" (or "l") for linear or piecewise linear treatment or "constant" (or "c") for constant treatment.
  • bp : the breakpoints to provide if you want a piecewise linear treatment.
  • y : output, the signal x with the trend removed from it.

Description

This function removes the constant or linear or piecewise linear trend from a vector x . In general this can be useful before a fourier analysis. If x is matrix this function removes the trend of each column of x.

When flag = "constant" or "c" detrend removes the constant trend (simply the mean of the signal) and when flag = "linear" or "l" the function removes the linear trend. By adding a third argument bp it is possible to remove a continuous piecewise linear trend. Note that the "instants" of the signal x goes from 0 to m-1 (m = length(x) if x is a vector and m = size(x,1) in case x is a matrix). So the breakpoints bp(i) must be reals in [0 m-1] (breakpoints outside are simply removed from bp vector).

The trend is got by a least square fit of x on the appropriate function space.

Examples

// example #1
t = linspace(0,16*%pi,1000)';
x = -20 + t + 0.3*sin(0.5*t) + sin(t) + 2*sin(2*t) + 0.5*sin(3*t);
y = detrend(x);
xbasc()
plot2d(t,[x y],style=[2 5])
legend(["before detrend","after detrend"]);
xgrid()

// example #2
t = linspace(0,32*%pi,2000)';
x = abs(t-16*%pi) + 0.3*sin(0.5*t) + sin(t) + 2*sin(2*t) + 0.5*sin(3*t);
y = detrend(x,"linear",1000);
xbasc()
plot2d(t,[x y],style=[2 5])
legend(["before detrend","after detrend"]);
xgrid()

Author

Bruno Pincon


dft

Scilab Function
Last update : 12/01/2004

dft - discrete Fourier transform

Calling Sequence

[xf]=dft(x,flag);

Parameters

  • x : input vector
  • flag : indicates dft (flag=-1) or idft (flag=1)
  • xf : output vector

Description

Function which computes dft of vector x .

Examples

n=8;omega = exp(-2*%pi*%i/n);
j=0:n-1;F=omega.^(j'*j);  //Fourier matrix
x=1:8;x=x(:);
F*x
fft(x,-1)
dft(x,-1)
inv(F)*x
fft(x,1)
dft(x,1)

See Also

fft ,

Author

C. B.


ell1mag

Scilab Function
Last update : 07/11/2006

ell1mag - magnitude of elliptic filter

Calling Sequence

[v]=ell1mag(eps,m1,z)

Parameters

  • eps : passband ripple= 1/(1+eps^2)
  • m1 : stopband ripple= 1/(1+(eps^2)/m1)
  • z : sample vector of values in the complex plane
  • v : elliptic filter values at sample points

Description

Function used for squared magnitude of an elliptic filter. Usually m1=eps*eps/(a*a-1) . Returns v=real(ones(z)./(ones(z)+eps*eps*s.*s)) for s=%sn(z,m1) .

Examples

deff('[alpha,BeTa]=alpha_beta(n,m,m1)',...
'if 2*int(n/2)==n then, BeTa=K1; else, BeTa=0;end;...
alpha=%k(1-m1)/%k(1-m);')
epsilon=0.1;A=10;  //ripple parameters
m1=(epsilon*epsilon)/(A*A-1);n=5;omegac=6;
m=find_freq(epsilon,A,n);omegar = omegac/sqrt(m)
%k(1-m1)*%k(m)/(%k(m1)*%k(1-m))-n   //Check...
[alpha,Beta]=alpha_beta(n,m,m1)
alpha*%asn(1,m)-n*%k(m1)      //Check
sample=0:0.01:20;
//Now we map the positive real axis into the contour...
z=alpha*%asn(sample/omegac,m)+Beta*ones(sample);
plot(sample,ell1mag(epsilon,m1,z))

See Also

buttmag ,


eqfir

Scilab Function
Last update : 12/01/2004

eqfir - minimax approximation of FIR filter

Calling Sequence

[hn]=eqfir(nf,bedge,des,wate)

Parameters

  • nf : number of output filter points desired
  • bedge : Mx2 matrix giving a pair of edges for each band
  • des : M-vector giving desired magnitude for each band
  • wate : M-vector giving relative weight of error in each band
  • hn : output of linear-phase FIR filter coefficients

Description

Minimax approximation of multi-band, linear phase, FIR filter

Examples

hn=eqfir(33,[0 .2;.25 .35;.4 .5],[0 1 0],[1 1 1]);
[hm,fr]=frmag(hn,256);
plot(fr,hm),

Author

C. B.


eqiir

Scilab Function
Last update : 12/01/2004

eqiir - Design of iir filters

Calling Sequence

[cells,fact,zzeros,zpoles]=eqiir(ftype,approx,om,deltap,deltas)

Parameters

  • ftype : filter type ( 'lp','hp','sb','bp' )
  • approx : design approximation ( 'butt','cheb1','cheb2','ellip' )
  • om : 4-vector of cutoff frequencies (in radians) om=[om1,om2,om3,om4] , 0 <= om1 <= om2 <= om3 <= om4 <= pi . When ftype ='lp' or 'hp', om3 and om4 are not used and may be set to 0.
  • deltap : ripple in the passband. 0<= deltap <=1
  • deltas : ripple in the stopband. 0<= deltas <=1
  • cells : realization of the filter as second order cells
  • fact : normalization constant
  • zzeros : zeros in the z-domain
  • zpoles : poles in the z-domain

Description

Design of iir filter interface with eqiir (syredi)

The filter obtained is h(z)=fact *product of the elements of cells .

That is hz=fact*prod(cells(2))./prod(cells(3))

Examples

[cells,fact,zzeros,zpoles]=...
eqiir('lp','ellip',[2*%pi/10,4*%pi/10],0.02,0.001)
transfer=fact*poly(zzeros,'z')/poly(zpoles,'z')

See Also

eqfir , iir ,


faurre

Scilab Function
Last update : 12/01/2004

faurre - filter computation by simple Faurre algorithm

Calling Sequence

[P,R,T]=faurre(n,H,F,G,R0)

Parameters

  • n : number of iterations.
  • H, F, G : estimated triple from the covariance sequence of y .
  • R0 : E(yk*yk')
  • P : solution of the Riccati equation after n iterations.
  • R, T : gain matrix of the filter.

Description

This function computes iteratively the minimal solution of the algebraic Riccati equation and gives the matrices R and T of the filter model. The algorithm tries to compute the solution P as the growing limit of a sequence of matrices Pn such that

                                     -1
Pn+1=F*Pn*F'+(G-F*Pn*h')*(R0-H*Pn*H')  *(G'-H*Pn*F')
       -1
P0=G*R0 *G'

Note that this method may not converge,especially when F has poles near the unit circle. Use preferably the srfaur function.

See Also

srfaur , lindquist , phc ,

Author

G. Le V.


ffilt

Scilab Function
Last update : 12/01/2004

ffilt - coefficients of FIR low-pass

Calling Sequence

[x]=ffilt(ft,n,fl,fh)

Parameters

  • ft : filter type where ft can take the values
    • "lp" : for low-pass filter
    • "hp" : for high-pass filter
    • "bp" : for band-pass filter
    • "sb" : for stop-band filter
  • n : integer (number of filter samples desired)
  • fl : real (low frequency cut-off)
  • fh : real (high frequency cut-off)
  • x : vector of filter coefficients

Description

Get n coefficients of a FIR low-pass, high-pass, band-pass, or stop-band filter. For low and high-pass filters one cut-off frequency must be specified whose value is given in fl . For band-pass and stop-band filters two cut-off frequencies must be specified for which the lower value is in fl and the higher value is in fh

Author

C. B.


fft2

Scilab Function
Last update : 10/02/2006

fft2 - two-dimension fast Fourier transform

Calling Sequence

y=fft2(x)
y=fft2(x,n,m)

Parameters

  • x : a vector/matrix/array (Real or Complex)
  • y : a vector/matrix/array (Real or Complex)
  • m : integer, number of rows.
  • n : integer, number of columns.

Description

This functions performs the two-dimension discrete Fourier
    transform.

y=fft2(x) : y and x have the same size

y=fft2(x,m,n): If m (respectively n ) is less than the rows number (respectively columns) of x then the x rows number (resp. columns) is truncated, else if m (resp. n ) is more than the rows number (resp. columns) of x then x rows are completed by zero (resp. columns) .

if x is a matrix then y is a matrix, if x is a hypermatrix then y is a hypermatrix, with the size of the first dimension of y is equal to m , the size of the second dimension of y is equal to n , the size of the ith dimension of y (for i>2, case hypermatrix) equal to the size of the ith dimension of x . (i.e size(y,1)=m, size(y,2)=n, size(y,i)=size(x,i) for i>2)

Examples

//Comparison with explicit formula
a=[1 2 3 ;4 5 6 ;7 8 9 ;10 11 12]
m=size(a,1)
n=size(a,2)
// fourier transform along the rows
for i=1:n
a1(:,i)=exp(-2*%i*%pi*(0:m-1)'.*.(0:m-1)/m)*a(:,i)
end
// fourier transform along the columns
for j=1:m
a2temp=exp(-2*%i*%pi*(0:n-1)'.*.(0:n-1)/n)*(a1(j,:)).'
a2(j,:)=a2temp.'
end
norm(a2-fft2(a))

See Also

fft ,


fftshift

Scilab Function
Last update : 13/12/2005

fftshift - rearranges the fft output, moving the zero frequency to the center of the spectrum

Calling Sequence

y=fftshift(x [,job])

Parameters

  • x : real or complex vector or matrix.
  • y : real or complex vector or matrix.
  • job : integer, dimension selection, or string 'all'

Description

if x results of an fft computation y= fftshift(x) or y= fftshift(x,"all") moves the zero frequency component to the center of the spectrum, which is sometimes a more convenient form.

If x is a vector of size n, y is the vector x([n/2+1:n,1:n/2])

If x is an m by n matrix y is the matrix x([m/2+1:n,1:m/2],[n/2+1:n,1:n/2]) .

  [x11 x12]                  [x22 x21]
x=[       ]        gives   y=[       ]
  [x21 x22]                  [x12 x11]

y= fftshift(x,n) make the swap only along the n th dimension

Examples

//make a signal
t=0:0.1:1000;
x=3*sin(t)+8*sin(3*t)+0.5*sin(5*t)+3*rand(t);
//compute the fft
y=fft(x,-1);
//display
xbasc();
subplot(2,1,1);plot2d(abs(y))
subplot(2,1,2);plot2d(fftshift(abs(y)))

//make a 2D image
t=0:0.1:30;
x=3*sin(t')*cos(2*t)+8*sin(3*t')*sin(5*t)+..
  0.5*sin(5*t')*sin(5*t)+3*rand(t')*rand(t);
//compute the fft
y=fft(x,-1);
//display
xbasc();
xset('colormap',hotcolormap(256))
subplot(2,1,1);Matplot(abs(y))
subplot(2,1,2);Matplot(fftshift(abs(y)))

See Also

fft ,


fftifft

Scilab Function
Last update : 17/11/2004

fft - fast Fourier transform.

ifft - fast Fourier transform.

Calling Sequence

x=fft(a ,-1) or x=fft(a)
x=fft(a,1) or x=ifft(a)
x=fft(a,-1,dim,incr)
x=fft(a,1,dim,incr)

Parameters

  • x : real or complex vector. Real or complex matrix (2-dim fft)
  • a : real or complex vector, matrix or multidimensionnal array.
  • dim : integer
  • incr : integer

Description

Short syntax
direct

x=fft(a,-1) or x=fft(a) gives a direct transform.

single variate

If a is a vector a single variate direct FFT is computed that is:

x(k)=sum over m from 1 to n of a(m)*exp(-2i*pi*(m-1)*(k-1)/n)

for k varying from 1 to n (n=size of vector a ).

(the -1 argument refers to the sign of the exponent..., NOT to "inverse"),

multivariate

If a is a matrix or or a multidimensionnal array a multivariate direct FFT is performed.

inverse

a=fft(x,1) or a=ifft(x) performs the inverse transform normalized by 1/n .

single variate

If a is a vector a single variate inverse FFT is computed

multivariate

If a is a matrix or or a multidimensionnal array a multivariate inverse FFT is performed.

Long syntax for multidimensional FFT

x=fft(a,-1,dim,incr) allows to perform an multidimensional fft.

If a is a real or complex vector implicitly indexed by j1,j2,..,jp i.e. a(j1,j2,..,jp) where j1 lies in 1:dim(1), j2 in 1:dim(2),... one gets a p-variate FFT by calling p times fft as follows

      incrk=1;
      x=a;
      for k=1:p
             x=fft(x ,-1,dim(k),incrk)
        incrk=incrk*dim(k)
      end

where dimk is the dimension of the current variable w.r.t which one is integrating and incrk is the increment which separates two successive jk elements in a .

In particular,if a is an nxm matrix, x=fft(a,-1) is equivalent to the two instructions:

a1=fft(a,-1,m,1) and x=fft(a1,-1,n,m) .

Examples

  //Comparison with explicit formula
  //----------------------------------
  a=[1;2;3];n=size(a,'*');
  norm(1/n*exp(2*%i*%pi*(0:n-1)'.*.(0:n-1)/n)*a -fft(a,1))
  norm(exp(-2*%i*%pi*(0:n-1)'.*.(0:n-1)/n)*a -fft(a,-1))

  //Frequency components of a signal
  //----------------------------------
  // build a noides signal sampled at 1000hz  containing to pure frequencies
  // at 50 and 70 Hz
  sample_rate=1000;
  t = 0:1/sample_rate:0.6;
  N=size(t,'*'); //number of samples
  s=sin(2*%pi*50*t)+sin(2*%pi*70*t+%pi/4)+grand(1,N,'nor',0,1);

  y=fft(s);
  //the fft response is symetric we retain only the first N/2 points
  f=sample_rate*(0:(N/2))/N; //associated frequency vector
  n=size(f,'*')
  clf()
  plot2d(f,abs(y(1:n)))

See Also

corr ,


filter

Scilab Function
Last update : 12/01/2004

filter - modelling filter

Calling Sequence

[y,xt]=filter(n,F,H,Rt,T)

Parameters

  • n : number of computed points.
  • F, H : relevant matrices of the Markovian model.
  • Rt, T : gain matrices.
  • y : output of the filter.
  • xt : filter process.

Description

This function computes the modelling filter

See Also

faurre ,

Author

G. Le V.


findm

Scilab Function
Last update : 12/01/2004

findm - for elliptic filter design

Calling Sequence

[m]=findm(chi)

Description

Search for m such that chi = %k(1-m)/%k(m) (For use with find_freq ).

See Also

%k ,

Author

F. D.;


find_freq

Scilab Function
Last update : 12/01/2004

find_freq - parameter compatibility for elliptic filter design

Calling Sequence

[m]=find_freq(epsilon,A,n)

Parameters

  • epsilon : passband ripple
  • A : stopband attenuation
  • n : filter order
  • m : frequency needed for construction of elliptic filter

Description

Search for m such that n=K(1-m1)K(m)/(K(m1)K(1-m)) with

m1=(epsilon*epsilon)/(A*A-1) ;

If m = omegar^2/omegac^2 , the parameters epsilon,A,omegac,omegar and n are then compatible for defining a prototype elliptic filter. Here, K=%k(m) is the complete elliptic integral with parameter m .

See Also

%k ,

Author

F. D.


frfit

Scilab Function
Last update : 12/01/2004

frfit - frequency response fit

Calling Sequence

sys=frfit(w,fresp,order)
[num,den]=frfit(w,fresp,order)
sys=frfit(w,fresp,order,weight)
[num,den]=frfit(w,fresp,order,weight)

Parameters

  • w : positive real vector of frequencies (Hz)
  • fresp : complex vector of frequency responses (same size as w )
  • order : integer (required order, degree of den )
  • weight : positive real vector (default value ones(w) ).
  • num,den : stable polynomials

Description

sys=frfit(w,fresp,order,weight) returns a bi-stable transfer function G(s)=sys=num/den , of of given order such that its frequency response G(w(i)) matches fresp(i) , i.e. freq(num,den,%i*w) should be close to fresp . weight(i) is the weight given to w(i) .

Examples

w=0.01:0.01:2;s=poly(0,'s');
G=syslin('c',2*(s^2+0.1*s+2), (s^2+s+1)*(s^2+0.3*s+1));
fresp=repfreq(G,w);
Gid=frfit(w,fresp,4);
frespfit=repfreq(Gid,w);
bode(w,[fresp;frespfit])

See Also

frep2tf , factors , cepstrum , mrfit , freq , calfrq ,


frmag

Scilab Function
Last update : 12/01/2004

frmag - magnitude of FIR and IIR filters

Calling Sequence

[xm,fr]=frmag(num[,den],npts)

Parameters

  • npts : integer (number of points in frequency response)
  • xm : mvector of magnitude of frequency response at the points fr
  • fr : points in the frequency domain where magnitude is evaluated
  • num : if den is omitted vector coefficients/polynomial/rational polynomial of filter
  • num : if den is given vector coefficients/polynomial of filter numerator
  • den : vector coefficients/polynomial of filter denominator

Description

calculates the magnitude of the frequency responses of FIR and IIR filters. The filter description can be one or two vectors of coefficients, one or two polynomials, or a rational polynomial.

Author

C. B.


fsfirlin

Scilab Function
Last update : 12/01/2004

fsfirlin - design of FIR, linear phase filters, frequency sampling technique

Calling Sequence

[hst]=fsfirlin(hd,flag)

Parameters

  • hd : vector of desired frequency response samples
  • flag : is equal to 1 or 2, according to the choice of type 1 or type 2 design
  • hst : vector giving the approximated continuous response on a dense grid of frequencies

Description

function for the design of FIR, linear phase filters using the frequency sampling technique

Examples

//
//Example of how to use the fsfirlin macro for the design
//of an FIR filter by a frequency sampling technique.
//
//Two filters are designed : the first (response hst1) with
//abrupt transitions from 0 to 1 between passbands and stop
//bands; the second (response hst2) with one sample in each
//transition band (amplitude 0.5) for smoothing.
//
hd=[zeros(1,15) ones(1,10) zeros(1,39)];//desired samples
hst1=fsfirlin(hd,1);//filter with no sample in the transition
hd(15)=.5;hd(26)=.5;//samples in the transition bands
hst2=fsfirlin(hd,1);//corresponding filter
pas=1/prod(size(hst1))*.5;
fg=0:pas:.5;//normalized frequencies grid
plot2d([1 1].*.fg(1:257)',[hst1' hst2']);
// 2nd example
hd=[0*ones(1,15) ones(1,10) 0*ones(1,39)];//desired samples
hst1=fsfirlin(hd,1);//filter with no sample in the transition
hd(15)=.5;hd(26)=.5;//samples in the transition bands
hst2=fsfirlin(hd,1);//corresponding filter
pas=1/prod(size(hst1))*.5;
fg=0:pas:.5;//normalized frequencies grid
n=prod(size(hst1))
plot(fg(1:n),hst1);
plot2d(fg(1:n)',hst2',[3],"000");

See Also

ffilt , wfir ,

Author

G. Le Vey


group

Scilab Function
Last update : 12/01/2004

group - group delay for digital filter

Calling Sequence

[tg,fr]=group(npts,a1i,a2i,b1i,b2i)

Parameters

  • npts : integer : number of points desired in calculation of group delay
  • a1i : in coefficient, polynomial, rational polynomial, or cascade polynomial form this variable is the transfer function of the filter. In coefficient polynomial form this is a vector of coefficients (see below).
  • a2i : in coeff poly form this is a vector of coeffs
  • b1i : in coeff poly form this is a vector of coeffs
  • b2i : in coeff poly form this is a vector of coeffs
  • tg : values of group delay evaluated on the grid fr
  • fr : grid of frequency values where group delay is evaluated

Description

Calculate the group delay of a digital filter with transfer function h(z).

The filter specification can be in coefficient form, polynomial form, rational polynomial form, cascade polynomial form, or in coefficient polynomial form.

In the coefficient polynomial form the transfer function is formulated by the following expression

h(z)=prod(a1i+a2i*z+z**2)/prod(b1i+b2i*z+z^2)

Examples

z=poly(0,'z');
h=z/(z-.5);
[tg,fr]=group(100,h);
plot(fr,tg)

Author

C. B.


hank

Scilab Function
Last update : 12/01/2004

hank - covariance to hankel matrix

Calling Sequence

[hk]=hank(m,n,cov)

Parameters

  • m : number of bloc-rows
  • n : number of bloc-columns
  • cov : sequence of covariances; it must be given as :[R0 R1 R2...Rk]
  • hk : computed hankel matrix

Description

this function builds the hankel matrix of size (m*d,n*d) from the covariance sequence of a vector process

Examples

//Example of how to use the hank macro for
//building a Hankel matrix from multidimensional
//data (covariance or Markov parameters e.g.)
//
//This is used e.g. in the solution of normal equations
//by classical identification methods (Instrumental Variables e.g.)
//
//1)let's generate the multidimensional data under the form :
//  C=[c_0 c_1 c_2 .... c_n]
//where each bloc c_k is a d-dimensional matrix (e.g. the k-th correlation
//of a d-dimensional stochastic process X(t) [c_k = E(X(t) X'(t+k)], '
//being the transposition in scilab)
//
//we take here d=2 and n=64
//
c=rand(2,2*64)
//
//generate the hankel matrix H (with 4 bloc-rows and 5 bloc-columns)
//from the data in c
//
H=hank(4,5,c);
//

See Also

toeplitz ,

Author

G. Le Vey


hilb

Scilab Function
Last update : 12/01/2004

hilb - Hilbert transform

Calling Sequence

[xh]=hilb(n[,wtype][,par])

Parameters

  • n : odd integer : number of points in filter
  • wtype : string : window type ('re','tr','hn','hm','kr','ch') (default ='re' )
  • par : window parameter for wtype='kr' or 'ch' default par=[0 0] see the function window for more help
  • xh : Hilbert transform

Description

returns the first n points of the Hilbert transform centred around the origin.

That is, xh=(2/(n*pi))*(sin(n*pi/2))^2 .

Examples

plot(hilb(51))

Author

C. B.


iirgroup

Scilab Function
Last update : 12/01/2004

iirgroup - group delay Lp IIR filter optimization

Calling Sequence

[lt,grad]=iirgroup(p,r,theta,omega,wt,td)
[cout,grad,ind]=iirlp(x,ind,p,[flag],lambda,omega,ad,wa,td,wt)

Parameters

  • r : vector of the module of the poles and the zeros of the filters
  • theta : vector of the argument of the poles and the zeros of the filters
  • omega : frequencies where the filter specifications are given
  • wt : weighting function for and the group delay
  • td : desired group delay
  • lt, grad : criterium and gradient values

Description

optimization of IIR filters for the Lp criterium for the the group delay. (Rabiner & Gold pp270-273).


iirlp

Scilab Function
Last update : 12/01/2004

iirlp - Lp IIR filter optimization

Calling Sequence

[cost,grad,ind]=iirlp(x,ind,p,[flag],lambda,omega,ad,wa,td,wt)

Parameters

  • x : 1X2 vector of the module and argument of the poles and the zeros of the filters
  • flag : string : 'a' for amplitude, 'gd' for group delay; default case for amplitude and group delay.
  • omega : frequencies where the filter specifications are given
  • wa,wt : weighting functions for the amplitude and the group delay
  • lambda : weighting (with 1-lambda ) of the costs ( 'a' and 'gd' for getting the global cost.
  • ad, td : desired amplitude and group delay
  • cost, grad : criterium and gradient values

Description

optimization of IIR filters for the Lp criterium for the amplitude and/or the group delay. (Rabiner & Gold pp270-273).


iir

Scilab Function
Last update : 12/01/2004

iir - iir digital filter

Calling Sequence

[hz]=iir(n,ftype,fdesign,frq,delta)

Parameters

  • n : filter order (pos. integer)
  • ftype : string specifying the filter type 'lp','hp','bp','sb'
  • fdesign : string specifying the analog filter design ='butt','cheb1','cheb2','ellip'
  • frq : 2-vector of discrete cut-off frequencies (i.e., 0<frq<.5 ). For lp and hp filters only frq(1) is used. For bp and sb filters frq(1) is the lower cut-off frequency and frq(2) is the upper cut-off frequency
  • delta

    : 2-vector of error values for cheb1, cheb2 , and ellip filters where only delta(1) is used for cheb1 case, only delta(2) is used for cheb2 case, and delta(1) and delta(2) are both used for ellip case. 0<delta(1),delta(2)<1

    • - for cheb1 filters 1-delta(1)<ripple<1 in passband
    • - for cheb2 filters 0<ripple<delta(2) in stopband
    • - for ellip filters 1-delta(1)<ripple<1 in passband and 0<ripple<delta(2) in stopband

Description

function which designs an iir digital filter using analog filter designs.

Examples

hz=iir(3,'bp','ellip',[.15 .25],[.08 .03]);
[hzm,fr]=frmag(hz,256);
plot2d(fr',hzm')
xtitle('Discrete IIR filter band pass  0.15<fr<0.25 ',' ',' ');
q=poly(0,'q');     //to express the result in terms of the ...
hzd=horner(hz,1/q) //delay operator q=z^-1

See Also

eqfir , eqiir ,

Author

C. B.


intdec

Scilab Function
Last update : 12/01/2004

intdec - Changes sampling rate of a signal

Calling Sequence

[y]=intdec(x,lom)

Parameters

  • x : input sampled signal
  • lom : For a 1D signal this is a scalar which gives the rate change. For a 2D signal this is a 2-Vector of sampling rate changes lom =(col rate change,row rate change)
  • y : Output sampled signal

Description

Changes the sampling rate of a 1D or 2D signal by the rates in lom

Author

C. B.


jmat

Scilab Function
Last update : 12/01/2004

jmat - row or column block permutation

Calling Sequence

[j]=jmat(n,m)

Parameters

  • n : number of block rows or block columns of the matrix
  • m : size of the (square) blocks

Description

This function permutes block rows or block columns of a matrix


kalm

Scilab Function
Last update : 12/01/2004

kalm - Kalman update

Calling Sequence

[x1,p1,x,p]=kalm(y,x0,p0,f,g,h,q,r)

Parameters

  • f,g,h : current system matrices
  • q, r : covariance matrices of dynamics and observation noise
  • x0,p0 : state estimate and error variance at t=0 based on data up to t=-1
  • y : current observation Output from the function is:
  • x1,p1 : updated estimate and error covariance at t=1 based on data up to t=0
  • x : updated estimate and error covariance at t=0 based on data up to t=0

Description

function which gives the Kalman update and error variance

Author

C. B.


lattn

Scilab Function
Last update : 12/01/2004

lattn - recursive solution of normal equations

Calling Sequence

[la,lb]=lattn(n,p,cov)

Parameters

  • n : maximum order of the filter
  • p : fixed dimension of the MA part. If p= -1 , the algorithm reduces to the classical Levinson recursions.
  • cov : matrix containing the Rk 's ( d*d matrices for a d-dimensional process).It must be given the following way
  • la : list-type variable, giving the successively calculated polynomials (degree 1 to degree n),with coefficients Ak

Description

solves recursively on n ( p being fixed) the following system (normal equations), i.e. identifies the AR part (poles) of a vector ARMA(n,p) process

where { Rk;k=1,nlag } is the sequence of empirical covariances

Author

G. Le V.


lattp

Scilab Function
Last update : 12/01/2004

lattp - lattp

Calling Sequence

[la,lb]=lattp(n,p,cov)

Description

see lattn

Author

G.Levey


levin

Scilab Function
Last update : 12/01/2004

levin - Toeplitz system solver by Levinson algorithm (multidimensional)

Calling Sequence

[la,sig]=levin(n,cov)

Parameters

  • n : maximum order of the filter
  • cov : matrix containing the

    (d x d matrices for a d-dimensional process). It must be given the following way :

  • la : list-type variable, giving the successively calculated Levinson polynomials (degree 1 to n), with coefficients Ak
  • sig : list-type variable, giving the successive mean-square errors.

Description

function which solves recursively on n the following Toeplitz system (normal equations)

where { Rk;k=1,nlag } is the sequence of nlag empirical covariances

Examples

//We use the 'levin' macro for solving the normal equations
//on two examples: a one-dimensional and a two-dimensional process.
//We need the covariance sequence of the stochastic process.
//This example may usefully be compared with the results from
//the 'phc' macro (see the corresponding help and example in it)
//
//
//1) A one-dimensional process
//   -------------------------
//
//We generate the process defined by two sinusoids (1Hz and 2 Hz)
//in additive Gaussian noise (this is the observed process);
//the simulated process is sampled at 10 Hz (step 0.1 in t, underafter).
//
t1=0:.1:100;rand('normal');
y1=sin(2*%pi*t1)+sin(2*%pi*2*t1);y1=y1+rand(y1);plot(t1,y1);
//
//covariance of y1
//
nlag=128;
c1=corr(y1,nlag);
c1=c1';//c1 needs to be given columnwise (see the section PARAMETERS of this help)
//
//compute the filter for a maximum order of n=10
//la is a list-type variable each element of which
//containing the filters of order ranging from 1 to n; (try varying n)
//in the d-dimensional case this is a matrix polynomial (square, d X d)
//sig gives, the same way, the mean-square error
//
n=15;
[la1,sig1]=levin(n,c1);
//
//verify that the roots of 'la' contain the
//frequency spectrum of the observed process y
//(remember that y is sampled -in our example
//at 10Hz (T=0.1s) so that we need to retrieve
//the original frequencies (1Hz and 2 Hz) through
//the log and correct scaling by the frequency sampling)
//we verify this for each filter order
//
for i=1:n, s1=roots(la1(i));s1=log(s1)/2/%pi/.1;
//
//now we get the estimated poles (sorted, positive ones only !)
//
s1=sort(imag(s1));s1=s1(1:i/2);end;
//
//the last two frequencies are the ones really present in the observed
//process ---> the others are "artifacts" coming from the used model size.
//This is related to the rather difficult problem of order estimation.
//
//2) A 2-dimensional process
//   -----------------------
//(4 frequencies 1, 2, 3, and 4 Hz, sampled at 0.1 Hz :
//   |y_1|        y_1=sin(2*Pi*t)+sin(2*Pi*2*t)+Gaussian noise
// y=|   | with :
//   |y_2|        y_2=sin(2*Pi*3*t)+sin(2*Pi*4*t)+Gaussian noise
//
//
d=2;dt=0.1;
nlag=64;
t2=0:2*%pi*dt:100;
y2=[sin(t2)+sin(2*t2)+rand(t2);sin(3*t2)+sin(4*t2)+rand(t2)];
c2=[];
for j=1:2, for k=1:2, c2=[c2;corr(y2(k,:),y2(j,:),nlag)];end;end;
c2=matrix(c2,2,128);cov=[];
for j=1:64,cov=[cov;c2(:,(j-1)*d+1:j*d)];end;//covar. columnwise
c2=cov;
//
//in the multidimensional case, we have to compute the
//roots of the determinant of the matrix polynomial
//(easy in the 2-dimensional case but tricky if d>=3 !).
//We just do that here for the maximum desired
//filter order (n); mp is the matrix polynomial of degree n
//
[la2,sig2]=levin(n,c2);
mp=la2(n);determinant=mp(1,1)*mp(2,2)-mp(1,2)*mp(2,1);
s2=roots(determinant);s2=log(s2)/2/%pi/0.1;//same trick as above for 1D process
s2=sort(imag(s2));s2=s2(1:d*n/2);//just the positive ones !
//
//There the order estimation problem is seen to be much more difficult !
//many artifacts ! The 4 frequencies are in the estimated spectrum
//but beneath many non relevant others.
//

See Also

phc ,

Author

G. Le Vey


lev

Scilab Function
Last update : 12/01/2004

lev - Yule-Walker equations (Levinson's algorithm)

Calling Sequence

[ar,sigma2,rc]=lev(r)

Parameters

  • r : correlation coefficients
  • ar : auto-Regressive model parameters
  • sigma2 : scale constant
  • rc : reflection coefficients

Description

resolve the Yule-Walker equations

using Levinson's algorithm.

Author

C. B.


lgfft

Scilab Function
Last update : 12/01/2004

lgfft - utility for fft

Calling Sequence

[y]=lgfft(x)

Parameters

  • x : real or complex vector

Description

returns the lowest power of 2 larger than size(x) (for FFT use).


lindquist

Scilab Function
Last update : 12/01/2004

lindquist - Lindquist's algorithm

Calling Sequence

[P,R,T]=lindquist(n,H,F,G,R0)

Parameters

  • n : number of iterations.
  • H, F, G : estimated triple from the covariance sequence of y .
  • R0 : E(yk*yk')
  • P : solution of the Riccati equation after n iterations.
  • R, T : gain matrices of the filter.

Description

computes iteratively the minimal solution of the algebraic Riccati equation and gives the matrices R and T of the filter model, by the Lindquist's algorithm.

See Also

srfaur , faurre , phc ,

Author

G. Le V.


mese

Scilab Function
Last update : 12/01/2004

mese - maximum entropy spectral estimation

Calling Sequence

[sm,fr]=mese(x [,npts]);

Parameters

  • x : Input sampled data sequence
  • npts : Optional parameter giving number of points of fr and sm (default is 256)
  • sm : Samples of spectral estimate on the frequency grid fr
  • fr : npts equally spaced frequency samples in [0,.5)

Description

Calculate the maximum entropy spectral estimate of x

Author

C. B.


mfft

Scilab Function
Last update : 12/01/2004

mfft - multi-dimensional fft

Calling Sequence

[xk]=mfft(x,flag,dim)

Parameters

  • x : x(i,j,k,...) input signal in the form of a row vector whose values are arranged so that the i index runs the quickest, followed by the j index, etc.
  • flag : (-1) FFT or (1) inverse FFT
  • dim : dimension vector which gives the number of values of x for each of its indices
  • xk : output of multidimensional fft in same format as for x

Description

FFT for a multi-dimensional signal

For example for a three dimensional vector which has three points along its first dimension, two points along its second dimension and three points along its third dimension the row vector is arranged as follows

     x=[x(1,1,1),x(2,1,1),x(3,1,1),
        x(1,2,1),x(2,2,1),x(3,2,1),
              x(1,1,2),x(2,1,2),x(3,1,2),
              x(1,2,2),x(2,2,2),x(3,2,2),
                    x(1,1,3),x(2,1,3),x(3,1,3),
                    x(1,2,3),x(2,2,3),x(3,2,3)]

and the dim vector is: dim=[3,2,3]

Author

C. B.


mrfit

Scilab Function
Last update : 12/01/2004

mrfit - frequency response fit

Calling Sequence

sys=mrfit(w,mag,order)
[num,den]=mrfit(w,mag,order)
sys=mrfit(w,mag,order,weight)
[num,den]=mrfit(w,mag,order,weight)

Parameters

  • w : positive real vector of frequencies (Hz)
  • mag : real vector of frequency responses magnitude (same size as w )
  • order : integer (required order, degree of den )
  • weight : positive real vector (default value ones(w) ).
  • num,den : stable polynomials

Description

sys=mrfit(w,mag,order,weight) returns a bi-stable transfer function G(s)=sys=num/den , of of given order such that its frequency response magnitude abs(G(w(i))) matches mag(i) i.e. abs(freq(num,den,%i*w)) should be close to mag . weight(i) is the weigth given to w(i) .

Examples

w=0.01:0.01:2;s=poly(0,'s');
G=syslin('c',2*(s^2+0.1*s+2),(s^2+s+1)*(s^2+0.3*s+1)); // syslin('c',Num,Den);
fresp=repfreq(G,w);
mag=abs(fresp);
Gid=mrfit(w,mag,4);
frespfit=repfreq(Gid,w);
plot2d([w',w'],[mag(:),abs(frespfit(:))])

See Also

cepstrum , frfit , freq , calfrq ,


%asn

Scilab Function
Last update : 12/01/2004

%asn - elliptic integral

Calling Sequence

[y]=%asn(x,m)

Parameters

  • x : upper limit of integral ( x>0 ) (can be a vector)
  • m : parameter of integral ( 0<m<1 )
  • y : value of the integral

Description

Calculates the elliptic integral

If x is a vector, y is a vector of same dimension as x .

Examples

m=0.8;z=%asn(1/sqrt(m),m);K=real(z);Ktilde=imag(z);
x2max=1/sqrt(m);
x1=0:0.05:1;x2=1:((x2max-1)/20):x2max;x3=x2max:0.05:10;
x=[x1,x2,x3];
y=%asn(x,m);
rect=[0,-Ktilde,1.1*K,2*Ktilde];
plot2d(real(y)',imag(y)',1,'011',' ',rect)
//
deff('y=f(t)','y=1/sqrt((1-t^2)*(1-m*t^2))');
intg(0,0.9,f)-%asn(0.9,m)  //Works for real case only!

Author

F. D.


%k

Scilab Function
Last update : 12/01/2004

%k - Jacobi's complete elliptic integral

Calling Sequence

[K]=%k(m)

Parameters

  • m : parameter of the elliptic integral 0<m<1 ( m can be a vector)
  • K : value of the elliptic integral from 0 to 1 on the real axis

Description

Calculates Jacobi's complete elliptic integral of the first kind :

References

Abramowitz and Stegun page 598

Examples

m=0.4;
%asn(1,m)
%k(m)

See Also

%asn ,

Author

F.D.


%sn

Scilab Function
Last update : 12/01/2004

%sn - Jacobi 's elliptic function

Calling Sequence

[y]=%sn(x,m)

Parameters

  • x : a point inside the fundamental rectangle defined by the elliptic integral; x is a vector of complex numbers
  • m : parameter of the elliptic integral ( 0<m<1 )
  • y : result

Description

Jacobi 's sn elliptic function with parameter m : the inverse of the elliptic integral for the parameter m .

The amplitude am is computed in fortran and the addition formulas for elliptic functions are applied

Examples

m=0.36;
K=%k(m);
P=4*K; //Real period
real_val=0:(P/50):P;
plot(real_val,real(%sn(real_val,m)))
xbasc();
KK=%k(1-m);
Ip=2*KK;
ima_val1=0:(Ip/50):KK-0.001;
ima_val2=(KK+0.05):(Ip/25):(Ip+KK);
z1=%sn(%i*ima_val1,m);z2=%sn(%i*ima_val2,m);
plot2d([ima_val1',ima_val2'],[imag(z1)',imag(z2)']);
xgrid(3)

See Also

%asn , %k ,

Author

F. D.


phc

Scilab Function
Last update : 12/01/2004

phc - Markovian representation

Calling Sequence

[H,F,G]=phc(hk,d,r)

Parameters

  • hk : hankel matrix
  • d : dimension of the observation
  • r : desired dimension of the state vector for the approximated model
  • H, F, G : relevant matrices of the Markovian model

Description

Function which computes the matrices H, F, G of a Markovian representation by the principal hankel component approximation method, from the hankel matrix built from the covariance sequence of a stochastic process.

Examples

//
//This example may usefully be compared with the results from
//the 'levin' macro (see the corresponding help and example)
//
//We consider the process defined by two sinusoids (1Hz and 2 Hz)
//in additive Gaussian noise (this is the observation);
//the simulated process is sampled at 10 Hz.
//
t=0:.1:100;rand('normal');
y=sin(2*%pi*t)+sin(2*%pi*2*t);y=y+rand(y);plot(t,y)
//
//covariance of y
//
nlag=128;
c=corr(y,nlag);
//
//hankel matrix from the covariance sequence
//(we can choose to take more information from covariance
//by taking greater n and m; try it to compare the results !
//
n=20;m=20;
h=hank(n,m,c);
//
//compute the Markov representation (mh,mf,mg)
//We just take here a state dimension equal to 4 :
//this is the rather difficult problem of estimating the order !
//Try varying ns !
//(the observation dimension is here equal to one)
ns=4;
[mh,mf,mg]=phc(h,1,ns);
//
//verify that the spectrum of mf contains the
//frequency spectrum of the observed process y
//(remember that y is sampled -in our example
//at 10Hz (T=0.1s) so that we need
//to retrieve the original frequencies through the log
//and correct scaling by the frequency sampling)
//
s=spec(mf);s=log(s);
s=s/2/%pi/.1;
//
//now we get the estimated spectrum
imag(s),
//

See Also

levin ,


pspect

Scilab Function
Last update : 12/01/2004

pspect - cross-spectral estimate between 2 series

Calling Sequence

[sm,cwp]=pspect(sec_step,sec_leng,wtype,x,y,wpar)

Parameters

  • x : data if vector, amount of input data if scalar
  • y : data if vector, amount of input data if scalar
  • sec_step : offset of each data window
  • sec_leng : length of each data window
  • wtype : window type (re,tr,hm,hn,kr,ch)
  • wpar : optional parameters for wtype='kr', wpar>0 for wtype='ch', 0<wpar(1)<.5, wpar(2)>0
  • sm : power spectral estimate in the interval [0,1]
  • cwp : unspecified Chebyshev window parameter

Description

Cross-spectral estimate between x and y if both are given and auto-spectral estimate of x otherwise. Spectral estimate obtained using the modified periodogram method.

Reference

Digital Signal Processing by Oppenheim and Schafer

Examples

rand('normal');rand('seed',0);
x=rand(1:1024-33+1);
//make low-pass filter with eqfir
nf=33;bedge=[0 .1;.125 .5];des=[1 0];wate=[1 1];
h=eqfir(nf,bedge,des,wate);
//filter white data to obtain colored data
h1=[h 0*ones(1:maxi(size(x))-1)];
x1=[x 0*ones(1:maxi(size(h))-1)];
hf=fft(h1,-1);   xf=fft(x1,-1);yf=hf.*xf;y=real(fft(yf,1));
//plot magnitude of filter
//h2=[h 0*ones(1:968)];hf2=fft(h2,-1);hf2=real(hf2.*conj(hf2));
//hsize=maxi(size(hf2));fr=(1:hsize)/hsize;plot(fr,log(hf2));
//pspect example
sm=pspect(100,200,'tr',y);smsize=maxi(size(sm));fr=(1:smsize)/smsize;
plot(fr,log(sm));
rand('unif');

See Also

cspect ,

Author

C. B.


remezb

Scilab Function
Last update : 12/01/2004

remezb - Minimax approximation of magnitude response

Calling Sequence

[an]=remezb(nc,fg,ds,wt)

Parameters

  • nc : Number of cosine functions
  • fg : Grid of frequency points in [0,.5)
  • ds : Desired magnitude on grid fg
  • wt : Weighting function on error on grid fg
  • an : Cosine filter coefficients

Description

Minimax approximation of a frequency domain magnitude response. The approximation takes the form h = sum[a(n)*cos(wn)] for n=0,1,...,nc. An FIR, linear-phase filter can be obtained from the the output of the function by using the following commands

         hn(1:nc-1)=an(nc:-1:2)/2;
         hn(nc)=an(1);
         hn(nc+1:2*nc-1)=an(2:nc)/2;

Examples

// Choose the number of cosine functions and create a dense grid
// in [0,.24) and [.26,.5)
nc=21;ngrid=nc*16;
fg=.24*(0:ngrid/2-1)/(ngrid/2-1);
fg(ngrid/2+1:ngrid)=fg(1:ngrid/2)+.26*ones(1:ngrid/2);
// Specify a low pass filter magnitude for the desired response
ds(1:ngrid/2)=ones(1:ngrid/2);
ds(ngrid/2+1:ngrid)=zeros(1:ngrid/2);
// Specify a uniform weighting function
wt=ones(fg);
// Run remezb
an=remezb(nc,fg,ds,wt)
// Make a linear phase FIR filter
hn(1:nc-1)=an(nc:-1:2)/2;
hn(nc)=an(1);
hn(nc+1:2*nc-1)=an(2:nc)/2;
// Plot the filter's magnitude response
plot(.5*(0:255)/256,frmag(hn,256));
//////////////
// Choose the number of cosine functions and create a dense grid in [0,.5)
nc=21; ngrid=nc*16;
fg=.5*(0:(ngrid-1))/ngrid;
// Specify a triangular shaped magnitude for the desired response
ds(1:ngrid/2)=(0:ngrid/2-1)/(ngrid/2-1);
ds(ngrid/2+1:ngrid)=ds(ngrid/2:-1:1);
// Specify a uniform weighting function
wt=ones(fg);
// Run remezb
an=remezb(nc,fg,ds,wt)
// Make a linear phase FIR filter
hn(1:nc-1)=an(nc:-1:2)/2;
hn(nc)=an(1);
hn(nc+1:2*nc-1)=an(2:nc)/2;
// Plot the filter's magnitude response
plot(.5*(0:255)/256,frmag(hn,256));

See Also

eqfir ,

Author

C. B.


remez

Scilab Function
Last update : 13/07/2005

remez - Remez's algorithm

Calling Sequence

[an]=remez(nc,fg,ds,wt)

Parameters

  • nc : integer, number of cosine functions
  • fg,ds,wt : real vectors
  • fg : grid of frequency points in [0,.5)
  • ds : desired magnitude on grid fg
  • wt : weighting function on error on grid fg

Description

minimax approximation of a frequency domain magnitude response. The approximation takes the form

 h = sum[a(n)*cos(wn)]

An FIR, linear-phase filter can be obtained from the the output of remez by using the following commands:

                 hn(1:nc-1)=an(nc:-1:2)/2;
                 hn(nc)=an(1);
                 hn(nc+1:2*nc-1)=an(2:nc)/2;

where an = cosine filter coefficients

See Also

remezb ,


rpem

Scilab Function
Last update : 12/01/2004

rpem - RPEM estimation

Calling Sequence

[w1,[v]]=rpem(w0,u0,y0,[lambda,[k,[c]]])

Parameters

  • a,b,c : a=[a(1),...,a(n)], b=[b(1),...,b(n)], c=[c(1),...,c(n)]
  • w0 : list(theta,p,phi,psi,l) where:
    • theta : [a,b,c] is a real vector of order 3*n
    • p : (3*n x 3*n) real matrix.
    • phi,psi,l : real vector of dimension 3*n

    During the first call on can take:

theta=phi=psi=l=0*ones(1,3*n). p=eye(3*n,3*n)
  • u0 : real vector of inputs (arbitrary size) (if no input take u0=[ ] ).
  • y0 : vector of outputs (same dimension as u0 if u0 is not empty). ( y0(1) is not used by rpem).

    If the time domain is (t0,t0+k-1) the u0 vector contains the inputs

    u(t0),u(t0+1),..,u(t0+k-1) and y0 the outputs

    y(t0),y(t0+1),..,y(t0+k-1)

Description

Recursive estimation of parameters in an ARMAX model. Uses Ljung-Soderstrom recursive prediction error method. Model considered is the following:

y(t)+a(1)*y(t-1)+...+a(n)*y(t-n)=
b(1)*u(t-1)+...+b(n)*u(t-n)+e(t)+c(1)*e(t-1)+...+c(n)*e(t-n)

The effect of this command is to update the estimation of unknown parameter theta=[a,b,c] with

a=[a(1),...,a(n)], b=[b(1),...,b(n)], c=[c(1),...,c(n)] .

Optional parameters

  • lambda : optional parameter (forgetting constant) choosed close to 1 as convergence occur:

    lambda=[lambda0,alfa,beta] evolves according to :

lambda(t)=alfa*lambda(t-1)+beta

    with lambda(0)=lambda0

    k : contraction factor to be chosen close to 1 as convergence occurs.

    k=[k0,mu,nu] evolves according to:

k(t)=mu*k(t-1)+nu

    with k(0)=k0 .

    c : large parameter.( c=1000 is the default value).

    • Output parameters:

    w1 : update for w0 .

    v : sum of squared prediction errors on u0, y0 .(optional).

    In particular w1(1) is the new estimate of theta . If a new sample u1, y1 is available the update is obtained by:

    [w2,[v]]=rpem(w1,u1,y1,[lambda,[k,[c]]]) . Arbitrary large series can thus be treated.


sincd

Scilab Function
Last update : 12/01/2004

sincd - digital sinc function or Direchlet kernel

Calling Sequence

[s]=sincd(n,flag)

Parameters

  • n : integer
  • flag : if flag = 1 the function is centred around the origin; if flag = 2 the function is delayed by %pi/(2*n)
  • s : vector of values of the function on a dense grid of frequencies

Description

function which calculates the function Sin(N*x)/N*Sin(x)

Examples

plot(sincd(10,1))

Author

G. Le V.


sinc

Scilab Function
Last update : 12/01/2004

sinc - samples of sinc function

Calling Sequence

[x]=sinc(n,fl)

Parameters

  • n : number of samples
  • fl : cut-off frequency of the associated low-pass filter in Hertz.
  • x : samples of the sinc function

Description

Calculate n samples of the function sin(2*pi*fl*t)/(pi*t) for t=-(n-1)/2:(n-1)/2 (i.e. centred around the origin).

Examples

plot(sinc(100,0.1))

See Also

sincd ,

Author

C. B.;


srfaur

Scilab Function
Last update : 12/01/2004

srfaur - square-root algorithm

Calling Sequence

[p,s,t,l,rt,tt]=srfaur(h,f,g,r0,n,p,s,t,l)

Parameters

  • h, f, g : convenient matrices of the state-space model.
  • r0 : E(yk*yk').
  • n : number of iterations.
  • p : estimate of the solution after n iterations.
  • s, t, l : intermediate matrices for successive iterations;
  • rt, tt : gain matrices of the filter model after n iterations.
  • p, s, t, l : may be given as input if more than one recursion is desired (evaluation of intermediate values of p ).

Description

square-root algorithm for the algebraic Riccati equation.

Examples

//GENERATE SIGNAL
x=%pi/10:%pi/10:102.4*%pi;
rand('seed',0);rand('normal');
y=[1;1]*sin(x)+[sin(2*x);sin(1.9*x)]+rand(2,1024);
//COMPUTE CORRELATIONS
c=[];for j=1:2,for k=1:2,c=[c;corr(y(k,:),y(j,:),64)];end;end
c=matrix(c,2,128);
//FINDING H,F,G with 6 states
hk=hank(20,20,c);
[H,F,G]=phc(hk,2,6);
//SOLVING RICCATI EQN
r0=c(1:2,1:2);
[P,s,t,l,Rt,Tt]=srfaur(H,F,G,r0,200);
//Make covariance matrix exactly symetric
Rt=(Rt+Rt')/2

See Also

phc , faurre , lindquist ,


srkf

Scilab Function
Last update : 12/01/2004

srkf - square root Kalman filter

Calling Sequence

[x1,p1]=srkf(y,x0,p0,f,h,q,r)

Parameters

  • f, h : current system matrices
  • q, r : covariance matrices of dynamics and observation noise
  • x0, p0 : state estimate and error variance at t=0 based on data up to t=-1
  • y : current observation Output from the function is
  • x1, p1 : updated estimate and error covariance at t=1 based on data up to t=0

Description

square root Kalman filter algorithm

Author

C. B.


sskf

Scilab Function
Last update : 12/01/2004

sskf - steady-state Kalman filter

Calling Sequence

[xe,pe]=sskf(y,f,h,q,r,x0)

Parameters

  • y : data in form [y0,y1,...,yn] , yk a column vector
  • f : system matrix dim(NxN)
  • h : observations matrix dim(MxN)
  • q : dynamics noise matrix dim(NxN)
  • r : observations noise matrix dim(MxM)
  • x0 : initial state estimate
  • xe : estimated state
  • pe : steady-state error covariance

Description

steady-state Kalman filter

Author

C. B.


system

Scilab Function
Last update : 12/01/2004

system - observation update

Calling Sequence

[x1,y]=system(x0,f,g,h,q,r)

Parameters

  • x0 : input state vector
  • f : system matrix
  • g : input matrix
  • h : Output matrix
  • q : input noise covariance matrix
  • r : output noise covariance matrix
  • x1 : output state vector
  • y : output observation

Description

define system function which generates the next observation given the old state. System recursively calculated

     x1=f*x0+g*u
     y=h*x0+v

where u is distributed N(0,q) and v is distribute N(0,r) .

Author

C. B.


trans

Scilab Function
Last update : 19/01/2006

trans - low-pass to other filter transform

Calling Sequence

hzt=trans(hz,tr_type,frq)
hzt=trans(pd,zd,gd,tr_type,frq)

Parameters

  • hz : given fiter transfert function
  • pd : Vector of given fiter poles
  • zd : Vector of given fiter zeros
  • gd : scalar: the given fiter gain
  • tr_type : string, the type of transformation, see description for possible values
  • frq : 2-vector of discrete cut-off frequencies (i.e., 0<frq<.5 ). For lp and hp filters only frq(1) is used. For bp and sb filters frq(1) is the lower cut-off frequency and frq(2) is the upper cut-off frequency.
  • hzt : transformed filter transfert function.

Description

function for transforming standardized low-pass filter given its poles-zeros_gain representation into one of the following filters:

low-pass ('lp'), the cutoff frequency is given by the first entry of frq, the second one is ignored

high-pass ('hp'), the cutoff frequency is given by the first entry of frq, the second one is ignored

band-pass ('bp'), the frequency range is given by frq(1) and frq(2)

stop-band ('sb') , the frequency range is given by frq(1) and frq(2).

Examples

clf()

Hlp=iir(3,'lp','ellip',[0.1 0],[.08 .03]);
subplot(311)
gainplot(Hlp,1d-3,0.48)
legend('original low pass')

Hbp=trans(Hlp,'bp',[0.01 0.1]);
subplot(312)
gainplot(Hbp,1d-3,0.48)
legend('band pass')

Hsb=trans(Hlp,'sb',[0.01 0.1])
subplot(313)
gainplot(Hsb,1d-3,0.48)
legend('stop band')

Author

C. Bunks ;


wfir

Scilab Function
Last update : 12/01/2004

wfir - linear-phase FIR filters

Calling Sequence

[wft,wfm,fr]=wfir(ftype,forder,cfreq,wtype,fpar)

Parameters

  • ftype : string : 'lp','hp','bp','sb' (filter type)
  • forder : Filter order (pos integer)(odd for ftype='hp' or 'sb' )
  • cfreq : 2-vector of cutoff frequencies ( 0<cfreq(1),cfreq(2)<.5 ) only cfreq(1) is used when ftype='lp' or 'hp'
  • wtype : Window type ( 're','tr','hm','hn','kr','ch' )
  • fpar : 2-vector of window parameters. Kaiser window fpar(1)>0 fpar(2)=0 . Chebyshev window fpar(1)>0, fpar(2)<0 or fpar(1)<0, 0<fpar(2)<.5
  • wft : time domain filter coefficients
  • wfm : frequency domain filter response on the grid fr
  • fr : Frequency grid

Description

Function which makes linear-phase, FIR low-pass, band-pass, high-pass, and stop-band filters using the windowing technique. Works interactively if called with no arguments.

Author

C. Bunks


wiener

Scilab Function
Last update : 12/01/2004

wiener - Wiener estimate

Calling Sequence

[xs,ps,xf,pf]=wiener(y,x0,p0,f,g,h,q,r)

Parameters

  • f, g, h : system matrices in the interval [t0,tf]
    • f = [f0,f1,...,ff] , and fk is a nxn matrix
    • g = [g0,g1,...,gf] , and gk is a nxn matrix
    • h = [h0,h1,...,hf] , and hk is a mxn matrix
  • q, r : covariance matrices of dynamics and observation noise
    • q = [q0,q1,...,qf] , and qk is a nxn matrix
    • r = [r0,r1,...,rf] , and gk is a mxm matrix
  • x0, p0 : initial state estimate and error variance
  • y : observations in the interval [t0,tf] . y=[y0,y1,...,yf] , and yk is a column m-vector
  • xs : Smoothed state estimate xs= [xs0,xs1,...,xsf] , and xsk is a column n-vector
  • ps : Error covariance of smoothed estimate ps=[p0,p1,...,pf] , and pk is a nxn matrix
  • xf : Filtered state estimate xf= [xf0,xf1,...,xff] , and xfk is a column n-vector
  • pf : Error covariance of filtered estimate pf=[p0,p1,...,pf] , and pk is a nxn matrix

Description

function which gives the Wiener estimate using the forward-backward Kalman filter formulation

Author

C. B.


wigner

Scilab Function
Last update : 12/01/2004

wigner - 'time-frequency' wigner spectrum

Calling Sequence

[tab]=wigner(x,h,deltat,zp)

Parameters

  • tab : wigner spectrum (lines correspond to the time variable)
  • x : analyzed signal
  • h : data window
  • deltat : analysis time increment (in samples)
  • zp : length of FFT's. %pi/zp gives the frequency increment.

Description

function which computes the 'time-frequency' wigner spectrum of a signal.


window

Scilab Function
Last update : 15/09/2004

window - compute symmetric window of various type

Calling Sequence

win_l=window('re',n)
win_l=window('tr',n)
win_l=window('hn',n)
win_l=window('hm',n)
win_l=window('kr',n,alpha)
[win_l,cwp]=window('ch',n,par)

Parameters

  • n : window length
  • par : parameter 2-vector par=[dp,df]) , where dp ( 0<dp<.5 ) rules the main lobe width and df rules the side lobe height ( df>0 ).Only one of these two value should be specified the other one should set equal to -1 .
  • alpha : kaiser window parameter alpha >0 ).
  • win : window
  • cwp : unspecified Chebyshev window parameter

Description

function which calculates various symmetric window for Disgital signal processing

The Kaiser window is a nearly optimal window function. alpha is an arbitrary positive real number that determines the shape of the window, and the integer n is the length of the window.

By construction, this function peaks at unity for k = n/2 , i.e. at the center of the window, and decays exponentially towards the window edges. The larger the value of alpha , the narrower the window becomes; alpha = 0 corresponds to a rectangular window. Conversely, for larger alpha the width of the main lobe increases in the Fourier transform, while the side lobes decrease in amplitude. Thus, this parameter controls the tradeoff between main-lobe width and side-lobe area.

alpha | window shape
0 | Rectangular shape
5 | Similar to the Hamming window
6 | Similar to the Hanning window
8.6 | Similar to the Blackman window

The Chebyshev window minimizes the mainlobe width, given a particular sidelobe height. It is characterized by an equiripple behavior, that is, its sidelobes all have the same height.

The Hanning and Hamming windows are quite similar, they only differ in the choice of one parameter alpha : w=alpha+(1 - alpha)*cos(2*%pi*x/(n-1)) alpha is equal to 1/2 in Hanning window and to 0.54 in Hamming window.

Examples

// Hamming window
clf()
N=64;
w=window('hm',N);
subplot(121);plot2d(1:N,w,style=color('blue'))
set(gca(),'grid',[1 1]*color('gray'))
subplot(122)
n=256;[W,fr]=frmag(w,n);
plot2d(fr,20*log10(W),style=color('blue'))
set(gca(),'grid',[1 1]*color('gray'))

//Kaiser window
clf()
N=64;
w=window('kr',N,6);
subplot(121);plot2d(1:N,w,style=color('blue'))
set(gca(),'grid',[1 1]*color('gray'))
subplot(122)
n=256;[W,fr]=frmag(w,n);
plot2d(fr,20*log10(W),style=color('blue'))
set(gca(),'grid',[1 1]*color('gray'))

//Chebyshev window
clf()
N=64;
[w,df]=window('ch',N,[0.005,-1]);
subplot(121);plot2d(1:N,w,style=color('blue'))
set(gca(),'grid',[1 1]*color('gray'))
subplot(122)
n=256;[W,fr]=frmag(w,n);
plot2d(fr,20*log10(W),style=color('blue'))
set(gca(),'grid',[1 1]*color('gray'))

See Also

wfir , frmag , ffilt ,

Author

Carey Bunks

Bibliography

IEEE. Programs for Digital Signal Processing. IEEE Press. New York: John Wiley and Sons, 1979. Program 5.2.


yulewalk

Scilab Function
Last update : 12/01/2004

yulewalk - least-square filter design

Calling Sequence

Hz = yulewalk(N,frq,mag)

Parameters

  • N : integer (order of desired filter)
  • frq : real row vector (non-decreasing order), frequencies.
  • mag : non negative real row vector (same size as frq), desired magnitudes.
  • Hz : filter B(z)/A(z)

Description

Hz = yulewalk(N,frq,mag) finds the N-th order iir filter

                  n-1         n-2
      B(z)   b(1)z     + b(2)z    + .... + b(n)
H(z)= ---- = ---------------------------------
                n-1       n-2
      A(z)    z   + a(2)z    + .... + a(n)

which matches the magnitude frequency response given by vectors frq and mag. Vectors frq and mag specify the frequency and magnitude of the desired frequency response. The frequencies in frq must be between 0.0 and 1.0, with 1.0 corresponding to half the sample rate. They must be in increasing order and start with 0.0 and end with 1.0.

Examples

f=[0,0.4,0.4,0.6,0.6,1];H=[0,0,1,1,0,0];Hz=yulewalk(8,f,H);
fs=1000;fhz = f*fs/2;
xbasc(0);xset('window',0);plot2d(fhz',H');
xtitle('Desired Frequency Response (Magnitude)')
[frq,repf]=repfreq(Hz,0:0.001:0.5);
xbasc(1);xset('window',1);plot2d(fs*frq',abs(repf'));
xtitle('Obtained Frequency Response (Magnitude)')


zpbutt

Scilab Function
Last update : 12/01/2004

zpbutt - Butterworth analog filter

Calling Sequence

[pols,gain]=zpbutt(n,omegac)

Parameters

  • n : integer (filter order)
  • omegac : real (cut-off frequency in Hertz)
  • pols : resulting poles of filter
  • gain : resulting gain of filter

Description

computes the poles of a Butterworth analog filter of order n and cutoff frequency omegac transfer function H(s) is calculated by H(s)=gain/real(poly(pols,'s'))

Author

F. Delebecque INRIA


zpch1

Scilab Function
Last update : 12/01/2004

zpch1 - Chebyshev analog filter

Calling Sequence

[poles,gain]=zpch1(n,epsilon,omegac)

Parameters

  • n : integer (filter order)
  • epsilon : real : ripple in the pass band ( 0<epsilon<1 )
  • omegac : real : cut-off frequency in Hertz
  • poles : resulting filter poles
  • gain : resulting filter gain

Description

Poles of a Type 1 Chebyshev analog filter. The transfer function is given by :

 H(s)=gain/poly(poles,'s')

Author

F.D.


zpch2

Scilab Function
Last update : 12/01/2004

zpch2 - Chebyshev analog filter

Calling Sequence

[zeros,poles,gain]=zpch2(n,A,omegar)

Parameters

  • n : integer : filter order
  • A : real : attenuation in stop band ( A>1 )
  • omegar : real : cut-off frequency in Hertz
  • zeros : resulting filter zeros
  • poles : resulting filter poles
  • gain : Resulting filter gain

Description

Poles and zeros of a type 2 Chebyshev analog filter gain is the gain of the filter

H(s)=gain*poly(zeros,'s')/poly(poles,'s')

Author

F.D.


zpell

Scilab Function
Last update : 12/01/2004

zpell - lowpass elliptic filter

Calling Sequence

[zeros,poles,gain]=zpell(epsilon,A,omegac,omegar)

Parameters

  • epsilon : real : ripple of filter in pass band ( 0<epsilon<1 )
  • A : real : attenuation of filter in stop band ( A>1 )
  • omegac : real : pass band cut-off frequency in Hertz
  • omegar : real : stop band cut-off frequency in Hertz
  • zeros : resulting zeros of filter
  • poles : resulting poles of filter
  • gain : resulting gain of filter

Description

Poles and zeros of prototype lowpass elliptic filter. gain is the gain of the filter

See Also

ell1mag , eqiir ,

Author

F.D.


Signal

Scilab Function
Last update : 12/01/2004

Signal - Signal manual description

Filters

  • analpf : analog low-pass filter
  • buttmag : squared magnitude response of a Butterworth filter
  • casc : creates cascade realization of filter
  • cheb1mag : square magnitude response of a type 1 Chebyshev filter
  • cheb2mag : square magnitude response of a type 1 Chebyshev filter
  • chepol : recursive implementation of Chebychev polynomial
  • convol : convolution of 2 discrete series
  • ell1 mag : squared magnitude of an elliptic filter
  • eqfir : minimax multi-band, linear phase, FIR filter
  • eqiir : design of iir filter
  • faurre : optimal lqg filter.
  • lindquis : optimal lqg filter lindquist algorithm
  • ffilt : FIR low-pass,high-pass, band-pass, or stop-band filter
  • filter : compute the filter model
  • find_freq : parameter compatibility for elliptic filter design
  • findm : for elliptic filter design
  • frmag : magnitude of the frequency responses of FIR and IIR filters.
  • fsfirlin : design of FIR, linear phase (frequency sampling technique)
  • fwiir : optimum design of IIR filters in cascade realization,
  • iir : designs an iir digital filter using analog filter designs.
  • iirgroup : group delay of iir filter
  • iirlp : Lp IIR filters optimization
  • group : calculate the group delay of a digital filter
  • optfir : optimal design of linear phase filters using linear programming
  • remezb : minimax approximation of a frequency domain magnitude response.
  • kalm : Kalman update and error variance
  • lev : resolve the Yule-Walker equations :
  • levin : solve recursively Toeplitz system (normal equations)
  • srfaur : square-root algorithm for the algebraic Riccati equation.
  • srkf : square-root Kalman filter algorithm
  • sskf : steady-state Kalman filter
  • system : generates the next observation given the old state
  • trans : transformation of standardized low-pass filter into low-pass, high-pass, band-pass, stop-band.
  • wfir : linear-phase windowed FIR low-pass, band-pass, high-pass, stop-band
  • wiener : Wiener estimate (forward-backward Kalman filter formulation)
  • wigner : time-frequency wigner spectrum of a signal.
  • window : calculate symmetric window
  • zpbutt : Butterworth analog filter
  • zpch1 : poles of a type 1 Chebyshev analog filter
  • zpch2 : poles and zeros of a type 2 Chebyshev analog filter
  • zpell : poles and zeros of prototype lowpass elliptic filter

    • Spectral estimation

  • corr : correlation coefficients
  • cspect : spectral estimation using the modified periodogram method.
  • czt : chirp z-transform algorithm
  • intdec : change the sampling rate of a 1D or 2D signal
  • mese : calculate the maximum entropy spectral estimate
  • pspect : auto and cross-spectral estimate
  • wigner : Wigner-Ville time/frequency spectral estimation

    • Transforms

  • dft : discrete Fourier transform
  • fft : fast flourier transform
  • hilb : Hilbert transform centred around the origin.
  • hank : hankel matrix of the covariance sequence of a vector process
  • mfft : fft for a multi-dimensional signal

    • Identification

  • lattn,lattp : recursive solution of normal equations
  • phc : State space realisation by the principal hankel component approximation method,
  • rpem : identification by the recursive prediction error method

    • Miscellaneous

  • lgfft : computes p = ceil (log_2(x))
  • sinc : calculate the function sin(2*pi*fl*t)/(pi*t)
  • sincd : calculates the function Sin(N*x)/Sin(x)
  • %k : Jacobi's complete elliptic integral
  • %asn : .TP the elliptic integral :
  • %sn : Jacobi 's elliptic function with parameter m
  • bilt : bilinear transform or biquadratic transform.
  • jmat : permutes block rows or block columns of a matrix


Modélisation et simulation ARMA
arma - Scilab arma library
arma2p - extract polynomial matrices from ar representation
armac - Scilab description of an armax process
armax - armax identification
armax1 - armax identification
arsimul - armax simulation
narsimul - armax simulation ( using rtitr)
noisegen - noise generation
prbs_a - pseudo random binary sequences generation
reglin - Linear regression


arma2p

Scilab Function
Last update : 12/01/2004

arma2p - extract polynomial matrices from ar representation

Calling Sequence

[A,B,D]=arma2p(ar)

Parameters

  • A,B,D : three polynomial matrices
  • ar : Scilab 'ar' tlist for arma storage (see armac ).

Description

this function extract polynomial matrices (A,B,D) from an armax description.

Examples

a=[1,-2.851,2.717,-0.865].*.eye(2,2)
b=[0,1,1,1].*.[1;1];
d=[1,0.7,0.2].*.eye(2,2);
sig=eye(2,2);
ar=armac(a,b,d,2,1,sig)
// extract polynomial matrices from ar representation
[A,B,D]=arma2p(ar);

See Also

arma , armax , armax1 , arsimul , armac ,


armac

Scilab Function
Last update : 12/01/2004

armac - Scilab description of an armax process

Calling Sequence

[ar]=armac(a,b,d,ny,nu,sig)

Parameters

  • a=[Id,a1,..,a_r] : is a matrix of size (ny,r*ny)
  • b=[b0,.....,b_s] : is a matrix of size (ny,(s+1)*nu)
  • d=[Id,d1,..,d_p] : is a matrix of size (ny,p*ny);
  • ny : dimension of the output y
  • nu : dimension of the output u
  • sig : a matrix of size (ny,ny)

Description

This function creates a description as a tlist of an ARMAX process

ar is defined by

ar=tlist(['ar','a','b','d','ny','nu','sig'],a,b,d,ny,nu,sig);

and thus the coefficients of ar can be retrieved by e.g. ar('a') .

Examples

a=[1,-2.851,2.717,-0.865].*.eye(2,2)
b=[0,1,1,1].*.[1;1];
d=[1,0.7,0.2].*.eye(2,2);
sig=eye(2,2);
ar=armac(a,b,d,2,1,sig)
// extract polynomial matrices from ar representation
[A,B,D]=arma2p(ar);

See Also

arma , armax , armax1 , arsimul , arma2p , tlist ,


armax1

Scilab Function
Last update : 12/01/2004

armax1 - armax identification

Calling Sequence

[arc,resid]=armax1(r,s,q,y,u [,b0f])

Parameters

  • y : output signal
  • u : input signal
  • r,s,q : auto regression orders with r >=0, s >=-1.
  • b0f : optional parameter. Its default value is 0 and it means that the coefficient b0 must be identified. if bof=1 the b0 is supposed to be zero and is not identified
  • arc : is tlist with type "ar" and fields a, b, d, ny, nu, sig
    • a : is the vector [1,a1,...,a_r]
    • b : is the vector [b0,......,b_s]
    • d : is the vector [1,d1,....,d_q]
    • sig : resid=[ sig*echap(1),....,];

Description

armax1 is used to identify the coefficients of a 1-dimensional ARX process:

   A(z^-1)y= B(z^-1)u + D(z^-1)sig*e(t)
   e(t) is a 1-dimensional white noise with variance 1.
   A(z)= 1+a1*z+...+a_r*z^r; ( r=0 => A(z)=1)
   B(z)= b0+b1*z+...+b_s z^s ( s=-1 => B(z)=0)
   D(z)= 1+d1*z+...+d_q*z^q  ( q=0 => D(z)=1)

for the method, see Eykhoff in trends and progress in system identification) page 96. with z(t)=[y(t-1),..,y(t-r),u(t),..., u(t-s),e(t-1),...,e(t-q)] and coef= [-a1,..,-ar,b0,...,b_s,d1,...,d_q]' y(t)= coef'* z(t) + sig*e(t).

a sequential version of the AR estimation where e(t-i) is replaced by an estimated value is used (RLLS). With q=0 this method is exactly a sequential version of armax

Author

J.-Ph.C; ;


armax

Scilab Function
Last update : 12/01/2004

armax - armax identification

Calling Sequence

[arc,la,lb,sig,resid]=armax(r,s,y,u,[b0f,prf])

Parameters

  • y : output process y(ny,n); ( ny: dimension of y , n : sample size)
  • u : input process u(nu,n); ( nu: dimension of u , n : sample size)
  • r and s : auto-regression orders r >=0 et s >=-1
  • b0f : optional parameter. Its default value is 0 and it means that the coefficient b0 must be identified. if bof=1 the b0 is supposed to be zero and is not identified
  • prf : optional parameter for display control. If prf =1, the default value, a display of the identified Arma is given.
  • arc : a Scilab arma object (see armac)
  • la : is the list(a,a+eta,a-eta) ( la = a in dimension 1) ; where eta is the estimated standard deviation. , a=[Id,a1,a2,...,ar] where each ai is a matrix of size (ny,ny)
  • lb : is the list(b,b+etb,b-etb) (lb =b in dimension 1) ; where etb is the estimated standard deviation. b=[b0,.....,b_s] where each bi is a matrix of size (nu,nu)
  • sig : is the estimated standard deviation of the noise and resid=[ sig*e(t0),....] (

Description

armax is used to identify the coefficients of a n-dimensional ARX process

   A(z^-1)y= B(z^-1)u + sig*e(t)

where e(t) is a n-dimensional white noise with variance I. sig an nxn matrix and A(z) and B(z):

A(z) = 1+a1*z+...+a_r*z^r; ( r=0 => A(z)=1)
B(z) = b0+b1*z+...+b_s z^s ( s=-1 => B(z)=0)

for the method see Eykhoff in trends and progress in system identification, page 96. with z(t)=[y(t-1),..,y(t-r),u(t),...,u(t-s)] and coef= [-a1,..,-ar,b0,...,b_s] we can write y(t)= coef* z(t) + sig*e(t) and the algorithm minimises sum_{t=1}^N ( [y(t)- coef'z(t)]^2) where t0=maxi(maxi(r,s)+1,1))).

Examples

//-Ex1- Arma model : y(t) = 0.2*u(t-1)+0.01*e(t-1)
ny=1,nu=1,sig=0.01;
Arma=armac(1,[0,0.2],[0,1],ny,nu,sig)  //defining the above arma model
u=rand(1,1000,'normal');     //a random input sequence u
y=arsimul(Arma,u); //simulation of a y output sequence associated with u.
Armaest=armax(0,1,y,u);   //Identified model given u and y.
Acoeff=Armaest('a');    //Coefficients of the polynomial A(x)
Bcoeff=Armaest('b')     //Coefficients of the polynomial B(x)
Dcoeff=Armaest('d');    //Coefficients of the polynomial D(x)
[Ax,Bx,Dx]=arma2p(Armaest)   //Results in polynomial form.

//-Ex2- Arma1: y_t -0.8*y_{t-1} + 0.2*y_{t-2} =  sig*e(t)
ny=1,nu=1;sig=0.001;
// First step: simulation the Arma1 model, for that we define
// Arma2: y_t -0.8*y_{t-1} + 0.2*y_{t-2} = sig*u(t)
// with normal deviates for u(t).
Arma2=armac([1,-0.8,0.2],sig,0,ny,nu,0);
//Definition of the Arma2 arma model (a model with B=sig and without noise!)
u=rand(1,10000,'normal');  // An input sequence for Arma2
y=arsimul(Arma2,u); // y = output of Arma2 with input u
//                     can be seen as output of Arma1.
// Second step: identification. We look for an Arma model
// y(t) + a1*y(t-1) + a2 *y(t-2) =  sig*e(t)
Arma1est=armax(2,-1,y,[]);
[A,B,D]=arma2p(Arma1est)

See Also

imrep2ss , time_id , arl2 , armax , frep2tf ,

Author

J-Ph. Chancelier.


arma

Scilab Function
Last update : 12/01/2004

arma - Scilab arma library

Description

Armax processes can be coded with Scilab tlist of type 'ar' . armac is used to build Armax scilab object. An 'ar' tlist contains the fields ['a','b','d','ny','nu','sig'] .

armac: this function creates a Scilab tlist which code an Armax process A(z^-1)y= B(z^-1)u + D(z^-1)sig*e(t)

-->ar=armac([1,2],[3,4],1,1,1,sig);

-->ar('a')
 ans  =

!   1.    2. !
-->ar('sig')
 ans  =

    1.
armap(ar [,out]): Display the armax equation associated with ar
armap_p(ar [,out]): Display the armax equation associated with ar using polynomial matrix display.
[A,B,D]=armap2p(ar): extract polynomial matrices from ar representation
armax: is used to identify the coefficients of a n-dimensional ARX process A(z^-1)y= B(z^-1)u + sig*e(t)
armax1: armax1 is used to identify the coefficients of a 1-dimensional ARX process A(z^-1)y= B(z^-1)u + D(z^-1)sig*e(t)
arsimul: armax trajectory simulation.
arspec: Spectral power estimation of armax processes. Test of mese and arsimul
exar1: An Example of ARMAX identification ( K.J. Astrom) The armax process is described by : a=[1,-2.851,2.717,-0.865] b=[0,1,1,1] d=[1,0.7,0.2]
exar2: ARMAX example ( K.J. Astrom). A simulation of a bi dimensional version of the example of exar1.
exar3: Spectral power estimation of arma processes from Sawaragi et all where a value of m=18 is used. Test of mese and arsimul
gbruit: noise generation
narsimul: armax simulation ( using rtitr)
odedi: Simple tests of ode and arsimul. Tests the option 'discret' of ode
prbs_a: pseudo random binary sequences generation
reglin: Linear regression

Author

J.P.C ; ;


arsimul

Scilab Function
Last update : 12/01/2004

arsimul - armax simulation

Calling Sequence

[z]=arsimul(a,b,d,sig,u,[up,yp,ep])
[z]=arsimul(ar,u,[up,yp,ep])

Parameters

  • ar : an armax process. See armac.
  • a : is the matrix[Id,a1,...,a_r] of dimension (n,(r+1)*n)
  • b : is the matrix[b0,......,b_s] of dimension (n,(s+1)*m)
  • d : is the matrix[Id,d_1,......,d_t] of dimension (n,(t+1)*n)
  • u : is a matrix (m,N), which gives the entry u(:,j)=u_j
  • sig : is a (n,n) matrix e_{k} is an n-dimensional Gaussian process with variance I
  • up, yp : optional parameter which describe the past. up=[ u_0,u_{-1},...,u_{s-1}]; yp=[ y_0,y_{-1},...,y_{r-1}]; ep=[ e_0,e_{-1},...,e_{r-1}]; if they are omitted, the past value are supposed to be zero
  • z : z=[ y(1),....,y(N)]

Description

simulation of an n-dimensional armax process A(z^-1) z(k)= B(z^-1)u(k) + D(z^-1)*sig*e(k)

A(z)= Id+a1*z+...+a_r*z^r;  ( r=0  => A(z)=Id)
B(z)= b0+b1*z+...+b_s z^s;  ( s=-1 => B(z)=[])
D(z)= Id+d1*z+...+d_t z^t;  ( t=0  => D(z)=Id)

z et e are in   R^n et u in  R^m

Method

a state-space representation is constructed and ode with the option "discr" is used to compute z

Author

J-Ph.C.;


narsimul

Scilab Function
Last update : 12/01/2004

narsimul - armax simulation ( using rtitr)

Calling Sequence

[z]=narsimul(a,b,d,sig,u,[up,yp,ep])
[z]=narsimul(ar,u,[up,yp,ep])

Description

ARMAX simulation. Same as arsimul but the method is different the simulation is made with rtitr

Author

J-Ph. Chancelier ENPC Cergrene; ;


noisegen

Scilab Function
Last update : 13/12/2005

noisegen - noise generation

Calling Sequence

b=noisegen(pas,Tmax,sig)

Description

generates a Scilab function [b]=Noise(t) where Noise(t) is a piecewise constant function ( constant on [k*pas,(k+1)*pas] ). The value on each constant interval are random values from i.i.d Gaussian variables of standard deviation sig. The function is constant for t<=0 and t>=Tmax .

Examples

noisegen(0.5,30,1.0);
x=-5:0.01:35;
y=feval(x,Noise);
plot(x,y);


prbs_a

Scilab Function
Last update : 12/01/2004

prbs_a - pseudo random binary sequences generation

Calling Sequence

[u]=prbs_a(n,nc,[ids])

Description

generation of pseudo random binary sequences u=[u0,u1,...,u_(n-1)]; u takes values in {-1,1} and changes at most nc times its sign. ids can be used to fix the date at which u must change its sign ids is then an integer vector with values in [1:n] .

Examples

u=prbs_a(50,10);
plot2d2("onn",(1:50)',u',1,"151",' ',[0,-1.5,50,1.5]);


reglin

Scilab Function
Last update : 12/01/2004

reglin - Linear regression

Calling Sequence

[a,b,sig]=reglin(x,y)

Description

solve the regression problem y=a*x+ b in the least square sense. sig is the standard deviation of the residual. x and y are two matrices of size x(p,n) and y(q,n) , where n is the number of samples.

The estimator a is a matrix of size (q,p) and b is a vector of size (q,1)

// simulation of data for a(3,5) and b(3,1)
x=rand(5,100);
aa=testmatrix('magi',5);aa=aa(1:3,:);
bb=[9;10;11]
y=aa*x +bb*ones(1,100)+ 0.1*rand(3,100);
// identification
[a,b,sig]=reglin(x,y);
maxi(abs(aa-a))
maxi(abs(bb-b))
// an other example : fitting a polynom
f=1:100; x=[f.*f; f];
y= [ 2,3]*x+ 10*ones(f) + 0.1*rand(f);
[a,b]=reglin(x,y)

See Also

pinv , leastsq , qr ,


Metanet : graphes et réseaux
add_edge - ajoute une arête ou un arc entre deux sommets
add_node - ajoute un sommet déconnecté à un graphe
adj_lists - calcule des listes d'adjacence
arc_graph - graphe avec sommets correspondant aux arcs
arc_number - nombre d'arcs d'un graphe
articul - trouve un ou plusieurs points d'articulation
bandwr - réduction de largeur de bande pour une matrice creuse
best_match - meilleur appariement d'un graphe
chain_struct - structure chaînée à partir d'une liste d'adjacence d'un graphe
check_graph - vérifie un graphe Scilab
circuit - trouve un circuit ou la fonction de rang dans un graphe orienté
con_nodes - ensemble de sommets d'une composante connexe
connex - composante connexe
contract_edge - contracte des arêtes entre deux sommets
convex_hull - enveloppe convexe d'un ensemble de points dans le plan
cycle_basis - base des cycles d'un graphe simple non-orienté
delete_arcs - détruit tous les arcs ou arêtes reliant un ensemble de sommets
delete_nodes - détruit des sommets
edge_number - nombre d'arêtes d'un graphe
edit_graph - graph and network graphical editor
edit_graph_menus - edit_graph menus description
find_path - trouve un chemin entre deux sommets
gen_net - génération aléatoire ou interactive d'un réseau
girth - circonférence d'un graphe orienté
glist - création d'un graphe
graph-list - description d'un graphe (sous forme de liste)
graph_2_mat - matrice d'incidence sommets-arcs ou sommets-sommets d'un graphe
graph_center - centre d'un graphe
graph_complement - complément d'un graphe
graph_diameter - diamètre d'un graphe
graph_power - puissance k-ième d'un 1-graphe orienté
graph_simp - convertit un graphe en un graphe simple non-orienté
graph_sum - somme de deux graphes
graph_union - union de deux graphes
hamilton - circuit hamiltonien d'un graphe
is_connex - test de connexité
knapsack - résout un problème du sac à dos 0-1 multiple
line_graph - graphe avec sommets correspondant aux arêtes
load_graph - charge un graphe
make_graph - création d'un graphe
mat_2_graph - graphe à partir de matrice d'incidence sommets-arcs ou sommets-sommets
max_cap_path - chemin de capacité maximum
max_clique - clique maximum d'un graphe
max_flow - flot maximum entre deux sommets
mesh2d - triangulation of n points in the plane
min_lcost_cflow - flot contraint de coût linéaire minimum
min_lcost_flow1 - flot de coût linéaire minimum
min_lcost_flow2 - flot de coût linéaire minimum
min_qcost_flow - flot de coût quadratique minimum
min_weight_tree - arbre couvrant de poids minimum
neighbors - sommets voisins connectés à un sommet
netclose - closes an edit_graph window
netwindow - selects the current edit_graph window
netwindows - gets the numbers of edit_graph windows
node_number - nombre de sommets d'un graphe
nodes_2_path - chemin reliant un ensemble de sommets
nodes_degrees - degrés des sommets d'un graphe
path_2_nodes - ensemble de sommets d'un chemin
perfect_match - appariement parfait de coût minimum
pipe_network - résout le problème du réseau de tuyaux
plot_graph - affichage général d'un graphe
predecessors - sommets origines des arcs entrants d'un sommet donné
qassign - résout un problème d'affectation quadratique
salesman - résout le problème du voyageur de commerce
save_graph - sauve un graphe
shortest_path - chemin le plus court
show_arcs - highlights a set of arcs
show_graph - displays a graph
show_nodes - highlights a set of nodes
split_edge - divise une arête en insérant un sommet
strong_con_nodes - ensemble de sommets d'une composante fortement connexe
strong_connex - composantes fortement connexes
subgraph - sous-graphe d'un graphe
successors - sommets extrémités des arcs sortant d'un sommet donné
supernode - remplace un groupe de sommets par un super-sommet
trans_closure - fermeture transitive


add_edge

Scilab function
Last update : 16/06/2004

add_edge - ajoute une arête ou un arc entre deux sommets

Calling Sequence

g1 = add_edge(i,j,g)

Parameters

  • i : entier, numéro du sommet origine
  • j : entier, numéro du sommet extrémité
  • g : graphe (liste)
  • g1 : nouveau graphe avec la nouvelle arête (liste)

Description

add_edge renvoie le graphe g1 avec une nouvelle arête du numéro de sommet i au numéro de sommet j . Si le graphe est orienté, l'arête est un arc. Le nombre d'arêtes plus 1 est pris comme nom de la nouvelle arête.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
g=add_edge(1,7,g);
g('edge_color')=[ones(ta) 11];
show_graph(g);

See Also

add_node , delete_arcs , delete_nodes ,


add_node

Scilab function
Last update : 16/06/2004

add_node - ajoute un sommet déconnecté à un graphe

Calling Sequence

g1 = add_node(g,[xy,name])

Parameters

  • g : graphe (liste)
  • xy : vecteur ligne optionnel des coordonnées du nouveau sommet
  • name : nom optionnel du nouveau sommet
  • g1 : nouveau graphe (liste)

Description

add_node ajoute un sommet déconnecté à un graphe g et renvoie le nouveau graphe g1 .

Les coordonnées du nouveau sommet sont éventuellement précisées dans un vecteur ligne xy . Si les sommets du graphe g n'ont pas de coordonnées, (les éléments node_x et node_y sont égaux à [] ) donner xy n'a aucun effet. Si les sommets du graphe g ont des coordonnées et que xy n'est pas donné, le nouveau sommet a (0,0) comme coordonnées.

Si name est donné, il est le nom du nouveau sommet, sinon le nombre de sommets plus 1 est pris comme nouveau nom.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
n=g('node_number');
g1=add_node(g,[270 140]);
g1('node_color')=[ones(1,n) 11];
show_graph(g1);

See Also

add_edge , delete_arcs , delete_nodes ,


adj_lists

Scilab function
Last update : 16/06/2004

adj_lists - calcule des listes d'adjacence

Calling Sequence

[lp,la,ls] = adj_lists(g)
[lp,la,ls] = adj_lists(oriented,n,tail,head)

Parameters

  • g : graphe (liste)
  • oriented : entier, 0 (graphe non-orienté) ou 1 (graphe orienté)
  • n : entier, le nombre de sommets du graphe
  • tail : le vecteur ligne des numéros des sommets origines du graphe (sa taille est égale au nombre d'arêtes du graphe)
  • head : le vecteur ligne des numéros des sommets extrémités du graphe (sa taille est égale au nombre d'arêtes du graphe)
  • lp : vecteur ligne, tableau de pointeurs de la description du graphe sous forme de liste d'adjacence (sa taille est égale au nombre de sommets du graphe + 1)
  • la : vecteur ligne, tableau d'arcs de la description du graphe sous forme de liste d'adjacence (sa taille est égale au nombre d'arêtes du graphe)
  • ls : vecteur ligne, tableau de sommets de la description du graphe sous forme de liste d'adjacence (sa taille est égale au nombre d'arêtes du graphe)

Description

adj_lists calcule le vecteur ligne de la description du graphe g sous forme de liste d'adjacence. Il est aussi possible de donner adj_lists , la description du graphe donnée par le nombre de sommets n ainsi que les vecteurs lignes tail et head .

Examples

ta=[2 3 3 5 3 4 4 5 8];
he=[1 2 4 2 6 6 7 7 4];
g=make_graph('foo',1,8,ta,he);
g('node_x')=[129 200 283 281 128 366 122 333];
g('node_y')=[61 125 129 189 173 135 236 249];
show_graph(g);
[lp,la,ls]=adj_lists(g)
[lp,la,ls]=adj_lists(1,g('node_number'),ta,he)

See Also

chain_struct , graph_2_mat ,


arc_graph

Scilab function
Last update : 16/06/2004

arc_graph - graphe avec sommets correspondant aux arcs

Calling Sequence

g1 = arc_graph(g)

Parameters

  • g : ancien graphe (liste)
  • g1 : nouveau graphe (liste)

Description

arc_graph renvoie le graphe orienté g1 avec les sommets correspondant aux arcs du graphe orienté g . g1 est défini de la façon suivante :

- ses sommets correspondent aux arcs de g

- 2 sommets du nouveau graphe sont adjacents si et seulement si les arcs correspondants du graphe g sont consécutifs.

Les coordonnées des sommets de g1 sont données par les milieux des arêtes correspondantes de g .

Si un tel graphe d'arcs n'existe pas, un vecteur vide est renvoyé

Examples

ta=[1 1 2 4 4 5 6 7 2 3 5 1];
he=[2 6 3 6 7 8 8 8 4 7 3 5];
g=make_graph('foo',1,8,ta,he);
g('node_x')=[281  284  360  185  405  182  118  45];
g('node_y')=[262  179  130  154  368  248  64  309];
show_graph(g);
g1=arc_graph(g);
show_graph(g1,'new');

See Also

line_graph ,


arc_number

Scilab function
Last update : 16/06/2004

arc_number - nombre d'arcs d'un graphe

Calling Sequence

ma = arc_number(g)

Parameters

  • g : graphe (liste)
  • ma : entier, nombre d'arcs

Description

arc_number renvoie le nombre ma d'arcs du graphe. Si le graphe est orienté, il s'agit du nombre d'arêtes. Si le graphe est non-orienté, il est égal à deux fois le nombre d'arêtes.

See Also

edge_number , node_number ,


articul

Scilab function
Last update : 16/06/2004

articul - trouve un ou plusieurs points d'articulation

Calling Sequence

nart = articul([i],g)

Parameters

  • g : graphe (liste)
  • i : entier
  • nart : vecteur ligne d'entiers

Description

articul trouve un ou plusieurs points d'articulation (s'il existent) du graphe g . nart est le vecteur ligne des numéros des sommets d'articulation : détruire un de ces sommets augmente le nombre de composantes connexes du graphe. i est le numéro optionnel de sommet à partir duquel l'algorithme démarre. La valeur par défaut est 1. Notez que le résultat dépend fortement du choix de ce sommet.

Examples

ta=[2  1 3 2 2 4 4 5 6 7 8 8 9 10 10 10 10 11 12 13 14 15 16 17 17];
he=[1 10 2 5 7 3 2 4 5 8 6 9 7  7 11 13 15 12 13 14 11 16 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
g('node_diam')=[1:(g('node_number'))]+20;
show_graph(g);
nart = articul(g)
show_nodes(nart);


bandwr

Scilab function
Last update : 16/06/2004

bandwr - réduction de largeur de bande pour une matrice creuse

Calling Sequence

[iperm,mrepi,prof,ierr] = bandwr(sp,[iopt])
[iperm,mrepi,prof,ierr] = bandwr(lp,ls,n,[iopt])

Parameters

  • sp : matrice creuse
  • lp : vecteur ligne d'entiers
  • ls : vecteur ligne d'entiers
  • n : entier
  • iopt : entier
  • iperm : vecteur ligne d'entiers
  • mrepi : vecteur ligne d'entiers
  • prof : vecteur ligne d'entiers
  • ierr : entier

Description

bandwr résout le problème de la réduction de largeur de bande pour une matrice creuse : la matrice est supposée triangulaire supérieure avec une diagonale pleine.

Dans la première séquence d'appel, sp désigne une matrice creuse; l'argument optionnel iopt vaut 0 ou 1 : 1 si réduire le profil de la matrice est plus important que réduire la largeur de bande et 0 si la largeur de bande est plus important.

La deuxième séquence d'appel correspond à la description d'un graphe : lp est un vecteur ligne de pointeurs de la description du graphe sous forme de liste d'adjacence (sa taille est le nombre de sommets du graphe + 1); ls est un vecteur ligne, tableau de sommets de la description du graphe sous forme de liste d'adjacence (sa taille est le nombre d'arêtes du graphe, c'est à dire le nombre de termes non-nuls de la matrice creuse associée). n est le nombre de sommets (dimension de sp ).

iperm est le vecteur de la permutation pour réordonner les lignes et les colonnes, qui réduit la largeur de bande et/ou le profil (nouvelle numérotation des sommets du graphe). mrepi est la permutation inverse (mrepi(iperm) est l'identité). prof est le tableau donnant le profil de la matrice creuse après la réduction de largeur de bande si iopt vaut 1. Si iopt vaut 0 ce tableau est nul sauf pour le premier terme, donnant alors la largeur de bande. La simple commande max(prof(2:$)-prof(1:($-1))) renvoie la largeur de bande de la matrice. ierr est un entier indiquant une erreur si sa valeur est non nulle.

Examples

ta=[2  1 3 2 2 4 4 5 6 7 8 8 9 10 10 10 10 11 12 13 13 14 15 16 16 17 17];
he=[1 10 2 5 7 3 2 4 5 8 6 9 7 7 11 13 15 12 13  9 14 11 16 1 17 14 15];
g=make_graph('foo',0,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
// LE GRAPHE
show_graph(g);
a=graph_2_mat(g,'node-node');
ww=tril(a)'+eye();
ww1=full(ww);
xset('window',1)
hist3d((ww1+tril(ww1',-1)+tril(ww1,-1)'),52,85);
// RÉDUCTION DE LARGEUR DE BANDE POUR LA MATRICE
[iperm,mrepi,prof,ierr]=bandwr(ww);
max(prof(2:$)-prof(1:($-1)))
// GRAPHE AVEC LA NOUVELLE NUMÉROTATION
g2=g;g2('node_name')=string(iperm);
show_graph(g2,'new')
// NOUVELLE MATRICE
n=g('node_number');
yy=ww1(mrepi,mrepi);
xset('window',3)
hist3d((yy+tril(yy',-1)+tril(yy,-1)'),52,85);
// ON COMMENCE AVEC LA MÊME MATRICE
[ij,v,mn]=spget(ww);
g1=make_graph('foo',0,n,ij(:,1)',ij(:,2)');
g1('node_x')=g('node_x');g1('node_y')=g('node_y');
// GRAPHE
//show_graph(g1,'rep');
[lp,la,ls] = adj_lists(1,n,g1('tail'),g1('head'));
[iperm,mrepi,prof,ierr]=bandwr(lp,ls,n,0);
g2=g;g2('node_name')=string(iperm);
show_graph(g2,'new');


best_match

Scilab function
Last update : 15/12/2005

best_match - meilleur appariement d'un graphe

Calling Sequence

[card,match] = best_match(g)

Parameters

  • g : graphe (liste)
  • card : entier
  • match : vecteur ligne d'entiers

Description

best_match trouve un appariement optimal pour le graphe g . Les sorties sont card et le vecteur match . card est la cardinalité d'un appariement optimal de g. match(i) est le sommet adjacent au sommet i dans l'appariement optimal ou 0 si i n'est pas apparié.

Examples

ta=[27 27 3 12 11 12 27 26 26 25 25 24 23 23 21 22 21 20 19 18 18];
ta=[ta  16 15 15 14 12 9 10 6 9 17 8 17 10 20 11 23 23 12 18 28];
he=[ 1  2 2  4  5 11 13  1 25 22 24 22 22 19 13 13 14 16 16  9 16];
he=[he  10 10 11 12  2 6  5 5 7  8 7  9  6 11  4 18 13  3 28 17];
n=28;
g=make_graph('foo',0,n,ta,he);
xx=[46 120 207 286 366 453 543 544 473 387 300 206 136 250 346 408];
g('node_x')=[xx 527 443 306 326 196 139 264  55  58  46 118 513];
yy=[36  34  37  40  38  40  35 102 102  98  93  96 167 172 101 179];
g('node_y')=[yy 198 252 183 148 172 256 259 258 167 109 104 253];
show_graph(g);
[card,match] = best_match(g);
sp=sparse([ta' he'],[1:size(ta,2)]',[n,n]);
sp1=sparse([[1:n]' match'],ones(1,size(match,2))',[n,n]);
[ij,v,mn]=spget(sp.*sp1);
show_arcs(v');
//
// AVEC UN GRAPHE PLUS GRAND
g=load_graph(SCI+'/demos/metanet/mesh1000');
g('directed')=0;
ta=g('tail');he=g('head');n=node_number(g);
show_graph(g,'new',1/2,[1000,400]);
[card,match] = best_match(g);
sp=sparse([ta' he'],[1:size(ta,2)]',[n,n]);
sp1=sparse([[1:n]' match'],ones(1,size(match,2))',[n,n]);
[ij,v,mn]=spget(sp.*sp1);
show_arcs(v');

See Also

perfect_match ,


chain_struct

Scilab function
Last update : 16/06/2004

chain_struct - structure chaînée à partir d'une liste d'adjacence d'un graphe

Calling Sequence

[fe,che,fn,chn] = chain_struct(g)
[fe,che,fn,chn] = chain_struct(lp,la,ls)

Parameters

  • g : graphe (liste)
  • lp : vecteur ligne de pointeurs de la description du graphe sous forme de liste d'adjacence (sa taille est le nombre de sommets du graphe + 1)
  • la : vecteur ligne, tableau d'arcs de la description du graphe sous forme de liste d'adjacence (sa taille est le nombre d'arêtes du graphe)
  • ls : vecteur ligne, tableau de sommets de la description du graphe sous forme de liste d'adjacence (sa taille est le nombre d'arêtes du graphe)
  • fe : vecteur ligne des numéros des premières arêtes partant des sommets (sa taille est le nombre de sommets du graphe)
  • che : vecteur ligne des numéros des arêtes chaînées (sa taille est le nombre d'arêtes du graphe)
  • fn : vecteur ligne des numéros des premiers sommets atteints par les arêtes de fe (sa taille est le nombre de sommets du graphe)
  • chn : vecteur ligne des sommets atteints par les arêtes de che

Description

chain_struct calcule les vecteurs lignes de la description par structure chaînée d'arêtes du graphe g . Il est aussi possible de donner directement chain_struct , la liste d'adjacence du graphe. Ceci est plus efficace si la liste d'adjacence est déjà disponible puisque chain_struct l'utilise pour faire les calculs.

Les vecteurs fe , che , fn et chn décrivent la structure chaînée de la manière suivante :

fe(i)) est le numéro de la première arête partant du sommet i,

che(fe(i)) est le numéro de la deuxième arête partant du sommet i, che(che(fe(i))) est le numéro de la troisième arête partant du sommet i et ainsi de suite jusqu'à ce que la valeur soit égale à 0.

fn(i) est le numéro du premier sommet atteint à partir du sommet i

ch(i) est le numéro du sommet atteint par l'arête che(i) .

Examples

ta=[1 1 2 3 5 4 6 7 7 3 3 8 8 5];
he=[2 3 5 4 6 6 7 4 3 2 8 1 7 4];
g=make_graph('foo',1,8,ta,he);
g('node_x')=[116 231 192 323 354 454 305 155];
g('node_y')=[118 116 212 219 117 185 334 316];
show_graph(g);
[fe,che,fn,chn] = chain_struct(g)

See Also

adj_lists , graph_2_mat ,


check_graph

Scilab function
Last update : 16/06/2004

check_graph - vérifie un graphe Scilab

Calling Sequence

check_graph(g)

Parameters

  • g : graphe (liste) à vérifier

Description

check_graph vérifie si g est un graphe. La vérification est non seulement syntaxique (nombre d'éléments de la liste, tailles compatibles des vecteurs), mais aussi sémantique au sens où check_graph vérifie que les éléments node_number , tail et head de la liste représentent vraiment un graphe.

De plus, les noms des sommets doivent être différents. En fait, cela ne donne pas d'erreur dans Scilab, mais un comportement étrange peut en résulter dans la fenêtre Metanet. Ceci n'est pas vérifié par check_graph car cela prendrait trop de temps. Cela est seulement vérifié lors de la visualisation, sauvegarde ou chargement du graphe.

See Also

graph-list ,


circuit

Scilab function
Last update : 16/06/2004

circuit - trouve un circuit ou la fonction de rang dans un graphe orienté

Calling Sequence

[p,r] = circuit(g)

Parameters

  • g : graphe (liste)
  • p : vecteur ligne des numéros des arcs du circuit s'il existe
  • r : vecteur ligne de la fonction de rang s'il n'y a pas de circuit

Description

circuit essaye de trouver un circuit pour le graphe orienté g . Elle renvoie, s'il existe, le circuit p en temps que vecteur ligne des numéros d'arcs correspondants et renvoie le vecteur vide [] sinon. Si le graphe n'a pas de circuit, la fonction de rang est renvoyée dans r , sinon sa valeur est le vecteur vide [] .

Examples

// graphe avec circuit
ta=[1 1 2 3 5 4 6 7 7 3 3 8 8 5];
he=[2 3 5 4 6 6 7 4 3 2 8 1 7 4];
g=make_graph('foo',1,8,ta,he);
g('node_x')=[116 231 192 323 354 454 305 155];
g('node_y')=[ 118 116 212 219 117 185 334 316];
show_graph(g);
p=circuit(g)
show_arcs(p)
// graphe sans circuit
g=make_graph('foo',1,4,[1 2 2 3],[2 3 4 4]);
[p,r]=circuit(g)


connex

Scilab function
Last update : 16/06/2004

connex - composante connexe

Calling Sequence

[nc,ncomp] = connex(g)

Parameters

  • g : graphe (liste)
  • nc : entier, nombre de composantes connexes
  • ncomp : vecteur ligne des composantes connexes

Description

connex renvoie nc le nombre de composantes connexes d'un graphe g et un vecteur ligne ncomp donnant le numéro de la composante connexe pour chaque sommet. Par exemple, si i est un numéro de sommet, ncomp(i) est le numéro de la composante connexe à laquelle le sommet i appartient.

Examples

ta=[1 1 2 2 2 3 4 4 5 6 7 7 7 8 9 10 12 12 13 13 14 15];
he=[2 6 3 4 5 1 3 5 1 7 5 8 9 5 8 11 10 11 11 15 13 14];
g=make_graph('foo',1,15,ta,he);
g('node_x')=[197 191 106 194 296 305 305 418 422 432 552 550 549 416 548];
g('node_y')=[76 181 276 278 276 83 174 281 177 86 175 90 290 397 399];
show_graph(g);
[nc,ncomp]=connex(g)
g('node_color')=10+ncomp;
g('node_diam')=10+10*ncomp;
x_message('Affichage des composantes connexes du graphe');
show_graph(g);

See Also

con_nodes , is_connex , strong_connex , strong_con_nodes ,


contract_edge

Scilab function
Last update : 16/06/2004

contract_edge - contracte des arêtes entre deux sommets

Calling Sequence

g1 = contract_edge(i,j,g)

Parameters

  • i : entier, numéros des sommets origines ou extrémités des arêtes
  • j : entier, numéros des sommets origines ou extrémités des arêtes
  • g : graphe (liste)
  • g1 : nouveau graphe (liste)

Description

contract_edge renvoie le graphe g1 , les arêtes entre les sommets numéros i et j étant détruits, les sommets étant réduits à un seul sommet avec le même nom que le sommet i et placé au milieu des deux sommets précédents.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 13 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
g1=contract_edge(10,13,g);
show_graph(g1,'new');

See Also

add_edge , add_node , delete_arcs , delete_nodes ,


convex_hull

Scilab function
Last update : 16/06/2004

convex_hull - enveloppe convexe d'un ensemble de points dans le plan

Calling Sequence

[nhull,ind] = convex_hull(xy)

Parameters

  • xy : matrice réelle 2 x n
  • nhull : entier
  • ind : vecteur ligne d'entiers

Description

convex_hull trouve l'enveloppe convexe d'un ensemble de n points dans le plan. xy est la matrice 2 x n des coordonnées (x,y) des points. convex_hull renvoie dans nhull le nombre de points de l'enveloppe convexe et dans ind le vecteur ligne (de taille nhull ) donnant les indices dans xy des points de la frontière. L'ordre dans ind correspond à des points consécutifs sur la frontière.

Examples

ta=[27 27 3 12 11 12 27 26 26 25 25 24 23 23 21 22 21 20 19 18 18];
ta=[ta  16 15 15 14 12 9 10 6 9 17 8 17 10 20 11 23 23 12 18 28];
he=[ 1  2 2  4  5 11 13  1 25 22 24 22 22 19 13 13 14 16 16  9 16];
he=[he  10 10 11 12  2 6  5 5 7  8 7  9  6 11  4 18 13  3 28 17];
g=make_graph('foo',0,28,ta,he);
xx=[46 120 207 286 366 453 543 544 473 387 300 206 136 250 346 408];
g('node_x')=[xx 527 443 306 326 196 139 264  55  58  46 118 513];
yy=[36  34  37  40  38  40  35 102 102  98  93  96 167 172 101 179];
g('node_y')=[yy 198 252 183 148 172 256 259 258 167 109 104 253];
show_graph(g);
xy=[g('node_x');g('node_y')];
[nhull,ind] = convex_hull(xy)
show_nodes(ind);


con_nodes

Scilab function
Last update : 16/06/2004

con_nodes - ensemble de sommets d'une composante connexe

Calling Sequence

ns = con_nodes(i,g)

Parameters

  • i : entier, numéro de la composante connexe
  • g : graphe (liste)
  • ns : vecteur ligne, numéros des sommets de la composante connexe

Description

con_nodes renvoie le vecteur ligne ns des numéros des sommets appartenant à la composante connexe numéro i . Si i n'est pas le numéro d'une composante connexe, le vecteur vide [] est renvoyé.

Examples

ta=[1 1 2 2 2 3 4 4 5 7 7 9 10 12 12 13 13 14 15];
he=[2 6 3 4 5 1 3 5 1 8 9 8 11 10 11 11 15 13 14];
g=make_graph('foo',1,15,ta,he);
g('node_x')=[197 191 106 194 296 305 305 418 422 432  552 550 549 416 548];
g('node_y')=[76 181 276 278 276 83 174 281 177 86 175 90 290 397 399];
show_graph(g);
con_nodes(2,g)
x_message('Affichage des sommets de la composante connexe #2');
n=g('node_number');
nodecolor=0*ones(1,n);
nodecolor(1,con_nodes(2,g))=11*ones(con_nodes(2,g));
g('node_color')=nodecolor;
nodediam=20.*ones(1,n);
nodediam(1,con_nodes(2,g))=30*ones(con_nodes(2,g));
g('node_diam')=nodediam;
show_graph(g);

See Also

connex , is_connex , strong_connex , strong_con_nodes ,


cycle_basis

Scilab function
Last update : 16/06/2004

cycle_basis - base des cycles d'un graphe simple non-orienté

Calling Sequence

spc = cycle_basis(g)

Parameters

  • g : graphe (liste)
  • spc : matrice creuse

Description

Tout d'abord un arbre couvrant est trouvé avec min_weight_tree et est ensuite utilisé pour trouver tous les cycles fondamentaux par rapport à cet arbre. Ils sont renvoyés sous forme d'un ensemble de cycles, chaque cycle étant représenté par un ensemble d'arêtes. Ces cycles sont renvoyés dans une matrice creuse spc : chaque ligne de cette matrice correspond à un cycle.

Le graphe g est supposé simple, non-orienté et connecté ( cycle_basis ne vérifie pas que le graphe est simple, utiliser graph_simp m avant l'appel si nécessaire).

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 13 15 12 13 9 10 14 11 16 1 17 14 15];
gt=make_graph('foo',1,17,ta,he);
gt('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
gt('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
gt('edge_color')=modulo([1:(edge_number(gt))],15)+1;
gt('node_diam')=[1:(gt('node_number'))]+20;
show_graph(gt);
g=graph_simp(gt);
g('edge_color')=modulo([1:(edge_number(g))],15)+1;
g('node_diam')=gt('node_diam');
g('default_edge_hi_width')=12;
show_graph(g);
spc=cycle_basis(g);
for kk=1:(size(spc,1)),
  aaa=spc(kk,:);aaa=full(aaa);aaa(aaa==0)=[];
  show_arcs(aaa);
end;

See Also

min_weight_tree , graph_simp ,


delete_arcs

Scilab function
Last update : 16/06/2004

delete_arcs - détruit tous les arcs ou arêtes reliant un ensemble de sommets

Calling Sequence

g1 = delete_arcs(ij,g)

Parameters

  • ij : matrice d'entiers (numéros des sommets)
  • g : graphe (liste)
  • g1 : nouveau graphe (liste)

Description

Si g est un graphe orienté, delete_arcs renvoie le graphe g1 avec les arcs définis par la matrice ij ayant été détruits. ij doit être une matrice n x 2 contenant les numéros des sommets : les n arcs à détruire sont définis par les couples de sommets ( ij(i,1) , ij(i,2) ).

Si g est un graphe non-orienté, les arêtes correspondant à la matrice ij sont détruites.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 13 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
ij=[13 10;8 6;5 4;4 2];
gt=delete_arcs(ij,g);
show_graph(gt,'new');
g('directed')=0;
gt=delete_arcs(ij,g);
show_graph(gt,'new');

See Also

add_edge , add_node , delete_nodes ,


delete_nodes

Scilab function
Last update : 16/06/2004

delete_nodes - détruit des sommets

Calling Sequence

g1 = delete_nodes(v,g)

Parameters

  • v : vecteur d'entiers, numéros des sommets à détruire
  • g : graphe (liste)
  • g1 : nouveau graphe (liste)

Description

delete_nodes renvoie le graphe g1 , avec les sommets donnés par le vecteur v ayant été détruits.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 13 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
v=[10 13 4];
gt=delete_nodes(v,g);
show_graph(gt,'new');

See Also

add_edge , add_node , delete_arcs ,


edge_number

Scilab function
Last update : 16/06/2004

edge_number - nombre d'arêtes d'un graphe

Calling Sequence

ma = edge_number(g)

Parameters

  • g : graphe (liste)
  • m : entier, nombre d'arêtes

Description

edge_number renvoie le nombre m d'arêtes du graphe. Si le graphe est orienté, il s'agit du nombre d'arcs. Si le graphe est non-orienté, il s'agit de la moitié du nombre d'arêtes. Ce nombre est toujours égal aux dimensions de g('tail') et g('head') .

See Also

arc_number , node_number ,


edit_graph_menus

Description
Last update : 12/01/2004

edit_graph_menus - edit_graph menus description

Description

The edit_graph editor supports the following menus:

Graph/New: This menu erases the currently edited network.
Graph/Zoom: This menu allows to set the scale factor for the display
Graph/Replot: This menu erases and re-displays the network.

This edition mode can also be entered pressing the " r " key while locator is in the edition window.

Graph/Find Node: This menu asks for a node number or a node name. If this node exists the view is modified such as the node appears in the middle of the graphic window.
Graph/Find Arc: This menu asks for an arc number or aa arc name. If this arc exists the view is modified such as the arc appears in the middle of the graphic window.
Graph/SaveAs: This menu allows to save the graph under a specified name
Graph/Save: This menu allows to save the graph under its current name

This edition mode can also be entered pressing the " s " key while locator is in the edition window.

Graph/Load: This menu allows to load a "graph" file.
Graph/Options: This menu allows to set global graph properties This edition mode can also be entered pressing the " o " key while locator is in the edition window.
Graph/Settings: This menu allows to set if graph is directed or not. It also sets default values for node diameter, node border width, edge width, and font size.
Information: This menu outputs graph informations, like number of nodes, number of arcs, nodes properties ans arc properties.
Graph/Quit: Use this menu to exit out of the editor.
Edit/NewNode: This menu set the current edition mode to "node addition". To add a node just click on its desired position. This edition mode can also be entered pressing the "n" key while locator is in the edition window (Under windows, the edition window should also have the focus). It is the current editing mode when edit_graph is started. This mode remains active until an other edition mode is selected.

This edition mode can also be entered pressing the " n " key while locator is in the edition window.

Edit/NewArc: This menu set the current edition mode to "edge addition". To add an edge between two nodes just left click on the initial node and on the final node (click on right button cancels current edge addition).

This edition mode can also be entered pressing the "a" key while locator is in the edition window (Under windows, the edition window should also have the focus). This mode remains active until an other edition mode is selected.

This edition mode can also be entered pressing the " a " key while locator is in the edition window.

Edit/Move Node: This menu set the current edition mode to "move node". To move a node just left click on the selected node move the mouse up to the final position and left click (click on right button cancels move).

This edition mode can also be entered pressing the " m " key while locator is in the edition window.

This mode remains active until an other edition mode is selected.

Edit/Move Region: This menu set the current edition mode to "move region mode". To move a rectangular region just click left on a rectangle corner, drag rectangle to the desired area, click left to validate the area (click on right button cancels move) then move the rectangle to the desired position and click to validate.
Edit/Copy Region To ClipBoard: This menu set the current edition mode to "copy region to clipboard mode". To copy a rectangular region into the edit_graph clipboard just click left on a rectangle corner, drag rectangle to the desired area, click left to validate the area (click on right button cancels copy) .

The edit_graph clipboard is shared by all edit_graph editors.

This mode remains active until an other edition mode is selected.

Edit/Paste: This menu set the current edition mode to "paste from clipboard mode" to clipboard mode". To paste clipboard into the edit_graph editor click left to select the editor window, drag rectangle to the desired area, click left to validate the position (click on right button cancels copy) .

This edition mode can also be entered pressing the " v " key while locator is in the edition window.

This mode remains active until an other edition mode is selected.

Edit/Delete: This menu set the current edition mode to "delete object mode". To delete a node or an edge just left click on the selected object.

This edition mode can also be entered pressing the " d " key while locator is in the edition window.

This mode remains active until an other edition mode is selected.

Edit/Delete RegionThis menu set the current edition mode to "delete region mode". To delete a rectangular region just click left on a rectangle corner, drag rectangle to the desired area, click left to validate the area (click on right button cancels selection).

Note that the deleted region is not send to the clipboard

This mode remains active until an other edition mode is selected. This edition mode can also be entered pressing the " x " key while locator is in the edition window.

Edit/Properties: This menu set the current edition mode to "set object properties". To set a node or an edge properties, just left click on the selected object; a popup dialog appears.

This mode remains active until an other edition mode is selected.

This edition mode can also be entered pressing the " p " key while locator is in the edition window.

Edit/Default names: This menu automatically sets the node and egde names properties to node and egde internal number.
Edit/Undo: This menu set the current edition mode to "undo previous edition". It can be used recursively.

This edition mode can also be entered pressing the " u " key while locator is in the edition window.

Note that Under windows, the shortcuts are taken into accound only if the edition have the focus.

See Also

edit_graph ,


edit_graph

Scilab Function
Last update : 12/01/2004

edit_graph - graph and network graphical editor

Calling Sequence

num=edit_graph()
num=edit_graph(file_name [,zoom [,wsize]])
num=edit_graph(G [,zoom [,wsize]])

Parameters

  • file_name : character string. The path of a "graph" file
  • G : a graph-list data structure
  • zoom : real positive scalar. The zoom factor, its default value is 1.
  • wsize : real positive vector [width height] . The initial window dimensions, its default value is [600,400] .
  • num : integer scalar. The associated window number window dimension.

Description

This function starts a network graphical editor. Each time edit_graph is executed, a new editor window is created. The editor capabilities and menus are described in edit_graph_menus

Examples

 ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
 he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
 g=make_graph('foo',1,17,ta,he);
 g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
 g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
 edit_graph(g)

See Also

netclose , show_graph , netwindow , edit_graph_menus ,


find_path

Scilab function
Last update : 16/06/2004

find_path - trouve un chemin entre deux sommets

Calling Sequence

p = find_path(i,j,g)

Parameters

  • i : entier, numéro du sommet de départ
  • j : entier, numéro su sommet d'arrivée
  • g : graphe (liste)
  • p : vecteur ligne des numéros des arcs du chemin s'il existe

Description

find_path renvoie un chemin p du sommet numéro i au sommet numéro j s'il en existe un, et le vecteur vide [] sinon.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
p=find_path(1,14,g);
edgecolor=1*ones(ta); edgecolor(p)=11*ones(p); g('edge_color')=edgecolor;
show_graph(g); show_arcs(p);

See Also

nodes_2_path , shortest_path ,


gen_net

Scilab function
Last update : 16/06/2004

gen_net - génération aléatoire ou interactive d'un réseau

Calling Sequence

g = gen_net(name,oriented,v)
g = gen_net()

Parameters

  • name : chaîne de caractères, le nom du graphe
  • oriented : entier, 0 (graphe non-orienté) ou 1 (graphe orienté)
  • v : vecteur ligne avec 12 valeurs pour définir le réseau
  • g : graphe (liste)

Description

gen_net génère un réseau g . Les arguments sont le nom du graphe, un flag égal à 0 (graphe non-orienté) ou 1 (graphe orienté) et un vecteur décrivant le réseau (voir ci-dessous).

Si aucun argument n'est donné, une boîte de dialogue pour la définition de tous les arguments est ouverte.

v doit être un vecteur ligne avec 12 valeurs. La signification de ces valeurs est :

Graine pour random : utilisé pour l'initialisation du générateur aléatoire

Nombre de sommets

Nombre de sources

Nombre de puits

Coût Minimum

Coût Maximum

Ressources d'entrée

Ressources de sortie

Capacité Minimum

Capacité Maximum

Pourcentage d'arêtes avec coûts : entre 0 et 100 Pourcentage d'arêtes avec capacités : entre 0 et 100

Le coût des arêtes sans coût est fixé au coût minimum. La capacité maximum des arêtes sans capacité est fixée aux ressources d'entrée.

Le résultat est un réseau g construit sur un graphe planaire connecté, en utilisant une méthode de triangulation. De plus, les calculs sont faits de manière à obtenir un réseau cohérent. Les valeurs des coûts et des capacités maximum sont affectées aux arêtes. Les capacités minimum sont réduites à 0.

Examples

v=[1,10,2,1,0,10,100,100,0,100,50,50];
g=gen_net('foo',1,v);
show_graph(g)
// génération interactive
g=gen_net();
show_graph(g)

See Also

mesh2d ,


girth

Scilab function
Last update : 16/06/2004

girth - circonférence d'un graphe orienté

Calling Sequence

d = girth(g)

Parameters

  • g : graphe (liste)
  • d : entier

Description

girth calcule la longueur (nombre d'arcs) du cycle le plus petit dans un graphe orienté non pondéré g .

Examples

ta=[1 6 2 4 7 5 6 8 4 3 5 1];
he=[2 1 3 6 4 8 8 7 2 7 3 5];
g=make_graph('foo',1,8,ta,he);
g('node_x')=[285  284  335  160  405  189  118  45];
g('node_y')=[266  179   83  176  368  252  64  309];
show_graph(g);
d=girth(g)


glist

Scilab Function
Last update : 16/06/2004

glist - création d'un graphe

Calling Sequence

g = glist(a1, ... ,a34)

Description

glist(a1,....a34) est un raccourci de la commande : tlist(['graph','name','oriented','node_number','tail','head',.. 'node_name','node_type','node_x','node_y','node_color',.. 'node_diam','node_border','node_font_size','node_demand',.. 'edge_name','edge_color','edge_width','edge_hi_width',.. 'edge_font_size','edge_length','edge_cost',.. 'edge_min_cap','edge_max_cap','edge_q_weight','edge_q_orig',.. 'edge_weight','default_node_diam','default_node_border',.. 'default_edge_width','default_edge_hi_width',.. 'default_font_size','node_label','edge_label'],a1, ... ,a34) Il s'agit d'une fonction de bas niveau pour créer un graphe. Aucune vérification n'est faite. Pour créer un graphe de façon plus standard, utiliser make_graph .

See Also

check_graph , graph-list , make_graph ,


graph_2_mat

Scilab function
Last update : 16/06/2004

graph_2_mat - matrice d'incidence sommets-arcs ou sommets-sommets d'un graphe

Calling Sequence

a = graph_2_mat(g,mat)

Parameters

  • g : graphe (liste)
  • mat : chaîne optionnelle, 'node-arc' ou 'node-node'
  • a : matrice d'incidence (creuse)

Description

graph_2_mat calcule la matrice d'incidence sommets-arcs ou sommets-sommets d'un graphe g .

Si l'argument optionnel mat est omis ou est égal à la chaîne de caractères 'node-arc' , la matrice sommets-arcs est calculée. Si mat est la chaîne de caractères 'node-node' , la matrice sommets-sommets est calculée.

Si n est le nombre de sommets du graphe et m est le nombre d'arêtes du graphe, la matrice sommets-arcs est une matrice creuse de taille (n,m) .

Elle est définie comme suit; si le graphe est orienté :

a(i,j) = +1 si le sommet i est l'origine de l'arc j

a(i,j) = -1 si le sommet i est la destination de l'arc j

Si le graphe est non-orienté :

a(i,j) = 1 si le sommet i est l'origine ou la destination de l'arc j

Si n est le nombre de sommets du graphe, la matrice sommets-sommets est une matrice creuse de taille (n,n) .

Elle est définie comme suit :

a(i,j) = 1 si il y a un arc du sommet i au sommet j

Examples

g=load_graph(SCI+'/demos/metanet/colored');
a=graph_2_mat(g)
a=graph_2_mat(g,'node-node')

See Also

mat_2_graph ,


graph_center

Scilab function
Last update : 16/06/2004

graph_center - centre d'un graphe

Calling Sequence

[no,rad] = graph_center(g)

Parameters

  • g : graphe (liste)
  • no : entier
  • rad : entier

Description

graph_center calcule le centre du graphe g i.e. le sommet pour lequel le plus grand des plus petits chemins vers tous les autres sommets est minimum. La longueur des arcs est supposée entière (1 par défaut). La sortie est la valeur rad de la longueur du rayon et no qui est le numéro du sommet du centre du graphe.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 11 12 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 15 12 13  9 14 11 16 1 17 14 15];
g=make_graph('foo',0,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
g('node_diam')=[1:(g('node_number'))]+20;
show_graph(g);
[no,rad] = graph_center(g)
show_nodes(no);

See Also

graph_diameter ,


graph_complement

Scilab function
Last update : 16/06/2004

graph_complement - complément d'un graphe

Calling Sequence

g1 = graph_complement(g,[gmax])

Parameters

  • g : graphe (liste)
  • gmax : graphe (liste)
  • g1 : nouveau graphe (liste)

Description

graph_complement renvoie le graphe non-orienté g1 qui est le complément du graphe g par rapport au graphe complet correspondant.

Quand gmax est donné, le complément est fait par rapport à gmax . g et gmax sont supposés être des graphes simples (utiliser graph_simp avant d'appeler graph_complement si nécessaire) avec le même nombre de sommets.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 11 12 13 13 13 14 15 17 17 16 16];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 15 12 13 9 10 14 11 16 14 15 1 17];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
g('edge_color')=modulo([1:(edge_number(g))],15)+1;
g('node_diam')=[1:(g('node_number'))]+20;
show_graph(g);
g1=graph_complement(g);
show_graph(g1,'new');
g=graph_complement(g1);
show_graph(g);

See Also

graph_sum , graph_simp ,


graph_diameter

Scilab function
Last update : 16/06/2004

graph_diameter - diamètre d'un graphe

Calling Sequence

[d,p] = graph_diameter(g)

Parameters

  • g : graphe (liste)
  • d : entier
  • p : vecteur ligne d'entiers

Description

graph_diameter calcule le diamètre du graphe g i.e. le plus grand des plus courts chemins entre deux sommets. La longueur des arcs est supposée entière (1 par défaut). La sortie est la valeur d de la longueur du diamètre et p est le chemin correspondant.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 11 12 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 15 12 13  9 14 11 16 1 17 14 15];
g=make_graph('foo',0,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
g('node_diam')=[1:(g('node_number'))]+20;
show_graph(g);
[d,p] = graph_diameter(g)
show_arcs(p);

See Also

graph_center ,


graph_power

Scilab function
Last update : 16/06/2004

graph_power - puissance k-ième d'un 1-graphe orienté

Calling Sequence

g1 = graph_power(g,k)

Parameters

  • g : graphe (liste)
  • k : entier
  • g1 : nouveau graphe (liste)

Description

graph_power calcule le graphe orienté g1 qui est la puissance k-ième du 1-graphe orienté g . Il y a un arc entre deux sommets dans g1 s'il existe un chemin entre ces sommets de longueur au plus k dans g . graph_power(g,1) est le graphe g .

Si un tel graphe n'existe pas, un vecteur vide est renvoyé.

Examples

ta=[1 1 2 4 4 5 6 7 2 3 5 1];
he=[2 6 3 6 7 8 8 8 4 7 3 5];
g=make_graph('foo',1,8,ta,he);
g('node_x')=[285  284  335  160  405  189  118  45];
g('node_y')=[266  179   83  176  368  252  64  309];
show_graph(g);
g1=graph_power(g,2);
show_graph(g1,'new');


graph_simp

Scilab function
Last update : 16/06/2004

graph_simp - convertit un graphe en un graphe simple non-orienté

Calling Sequence

g1 = graph_simp(g)

Parameters

  • g : ancien graphe (liste)
  • g1 : nouveau graphe (liste)

Description

graph_simp renvoie le graphe simple non-orienté g1 correspondant au multigraphe g . Elle détruit les boucles de g , remplace les arêtes orientées par des arêtes non-orientées et remplace les arêtes multiples par une seule arête.

Examples

ta=[1 1  1 2 2 2 3 4 4 4 5 5 6 7 7 8 8 9 9 10 10 10 10 10 11 12 12 13 13 13 14 15 16 16 17 17];
he=[1 2 10 3 5 7 4 2 9 9 4 6 6 8 2 6 9 7 4  7 11 13 13 15 12 11 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163  63  98 164 162 273 235 267 384 504 493 409 573 601 627 642];
g('node_y')=[ 59 133 223 311 227 299 221 288 384 141 209 299 398 383 187 121 301];
show_graph(g);
g1=graph_simp(g);
show_graph(g1,'new');


graph_sum

Scilab function
Last update : 16/06/2004

graph_sum - somme de deux graphes

Calling Sequence

g2 = graph_sum(g,g1)

Parameters

  • g : graphe (liste)
  • g1 : graphe (liste)
  • g2 : nouveau graphe (liste)

Description

graph_sum crée un graphe g2 avec une matrice d'adjacence égale à la somme des matrices d'adjacence des deux graphes g et g1 . g et g1 sont supposés simples (utiliser graph_simp avant d'appeler graph_complement si nécessaire) et avoir le même nombre de sommets.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
g('edge_color')=modulo([1:(edge_number(g))],15)+1;
g('edge_width')=ones(1,(edge_number(g)));
g('node_diam')=[1:(g('node_number'))]+20;
g('node_name')=['A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q'];
show_graph(g);
ta=[2 3 4 5 11 12 1];
he=[10 5 6 7 15 17 7];
g1=make_graph('foo',1,17,ta,he);
g1('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g1('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
g1('edge_color')=modulo([1:(edge_number(g1))],15)+1;
g1('edge_width')=10*ones(1,(edge_number(g1)));
g1('node_diam')=[1:(g1('node_number'))]+20;
g1('node_name')=['A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q'];
show_graph(g1,'new');
g2=graph_sum(g,g1);
show_graph(g2,'new');

See Also

graph_complement , graph_union ,


graph_union

Scilab function
Last update : 16/06/2004

graph_union - union de deux graphes

Calling Sequence

g2 = graph_union(g,g1)

Parameters

  • g : graphe (liste)
  • g1 : graphe (liste)
  • g2 : nouveau graphe (liste)

Description

graph_union crée un nouveau graphe g2 . L'ensemble des sommets de g2 est l'union (au sens usuel) de l'ensemble des sommets de g et g1 . g2 a une arête pour chaque arête de g et une arête pour chaque arête de g1 . Les arêtes de g et g1 ayant les mêmes destinations sont conservées et dans ce cas g2 a des arêtes multiples.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 13 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
g('edge_color')=modulo([1:(edge_number(g))],15)+1;
g('node_diam')=[1:(g('node_number'))]+20;
g('node_name')=['A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q'];
w=show_graph(g);
v=[7 8 9 10 11 12 13];
show_nodes(v);
g1=subgraph(v,'nodes',g);
show_graph(g1,'new');
v=[1 2 5 6 7 8 9 10];
netwindow(w);
show_nodes(v);
g2=subgraph(v,'nodes',g);
show_graph(g2,'new');
g=graph_union(g1,g2);
show_graph(g,'new');

See Also

supernode , subgraph ,


graph-list

Scilab type
Last update : 17/06/2004

graph-list - description d'un graphe (sous forme de liste)

Description

Un graphe dans Scilab est représenté par une liste typée.

Voir ci-dessous la description complète de cette liste. Chaque élément est décrit par une ou plusieurs lignes. La première ligne donne le nom de l'élément et sa définition. Des informations supplémentaires, telles que les valeurs par défaut des éléments pouvant en avoir une, sont données sur les autres lignes. En fait, seul les 5 premiers éléments doivent avoir une valeur, les autres pouvant être définis comme un vecteur vide [] , la valeur par défaut étant utilisée par les fonctions ou la fenêtre de Metanet. Par exemple, il est possible de définir un graphe par :

      g=make_graph('min',1,1,[1],[1]);

qui est le graphe le plus simple que l'on puisse créer avec Metanet (il est orienté, possède un sommet et une boucle sur ce sommet).

Le nom des élément dans la liste est très important car il est utilisé pour y accéder. Par exemple si g est un graphe, pour obtenir le nom du graphe, il suffit de taper :

      g('name')

ou

      g.name

et pour changer le nom du graphe en 'toto' :

      g('name')='toto';

ou

      g.name='toto';

On peut obtenir le nombre d'arêtes et le nombre d'arcs du graphe avec edge_number(g) et arc_number(g) (ces noms ne sont pas ceux des éléments de la liste). Pour raisons de compatibilité node_number(g) peut être utilisé à la place de g('node_number') ou g.node_number .

Un graphe peut être syntaxiquement correct mais ne pas représenter un graphe valide. Utiliser la fonction check_graph pour le vérifier. De plus, les noms des sommets doivent être différents. En fait, cela ne donne pas d'erreur dans Scilab, mais un comportement étrange peut en résulter. Ceci n'est pas vérifié par check_graph car cela prendrait trop de temps. Cela est seulement vérifié lors de sa visualisation, sauvegarde ou chargement.

Les éléments d'un graphe sont les suivants :

name : le nom du graphe. C'est une chaîne de caractères (longueur < 80).
oriented : flag donnant le type du graphe. Il est égal à 1 (graphe orienté) ou égal à 0 (graphe non-orienté).
node_number : nombre de sommets
tail : vecteur ligne des numéros des sommets origines
head : vecteur ligne des numéros des sommets extrémités
node_name : vecteur ligne des noms des sommets. Les noms des sommets doivent être différents. Par défaut les noms des sommets sont égaux à leurs numéros.
node_type : vecteur ligne des types des sommets. Le type est un entier entre 0 et 2, 0 par défaut:
0 = sommet normal
1= puits
2= source
node_x : vecteur ligne des coordonnées x des sommets. Valeur par défaut calculée.
node_y : vecteur ligne des coordonnées y des sommets. Valeur par défaut calculée.
node_color : vecteur ligne des couleurs des sommets, des entiers correspondants a la table de couleur courante.
node_diam : vecteur ligne des diamètres des sommets en pixels, un sommet est dessiné sous forme d'un cercle. Par défaut, valeur de l'élément default_node_diam .
node_border : vecteur ligne de l'épaisseur des bords des sommets. un sommet est dessiné sous forme d'un cercle, par défaut, valeur de l'élément default_node_border .
node_font_size : vecteur ligne de la taille de la police utilisée pour afficher le nom du sommet. Les tailles possibles sont: 8, 10, 12, 14, 18 ou 24. Par défaut, valeur de l'élément default_font_size .
node_demand : vecteur ligne des demandes des sommets, 0 par défaut;
edge_name : vecteur ligne des noms d'arêtes. Il est souhaitable que les noms des arêtes soient différents, mais c'est n'est pas obligatoire. Par défaut les noms des arêtes sont leur numéros.
edge_color: vecteur ligne des couleurs des arêtes. des entiers correspondants a la table de couleur courante.
edge_width: vecteur ligne des épaisseurs des arêtes en pixels, par défaut, valeur de l'élément default_edge_width .
edge_hi_width : vecteur ligne des épaisseurs des arêtes mises en évidence (en pixels), par défaut, valeur de l'élément default_edge_hi_width .
edge_font_size: vecteur ligne de la taille de la police utilisée pour afficher le nom des arêtes. Les tailles possibles sont:8, 10, 12, 14, 18 ou 24. Par défaut, valeur de l'élément default_font_size .
edge_length : vecteur ligne des longueurs des arêtes, 0 par défaut.
edge_cost : vecteur ligne des coûts des arêtes, 0 par défaut.
edge_min_cap : vecteur ligne des capacités minimum des arêtes, 0 par défaut.
edge_max_cap : vecteur ligne des capacités maximum des arêtes, 0 par défaut.
edge_q_weight : vecteur ligne des poids quadratiques des arêtes, 0 par défaut.
edge_q_orig : vecteur ligne des origines quadratiques des arêtes, 0 par défaut.
edge_weight : vecteur ligne des poids des arêtes, 0 par défaut.
default_node_diam : diamètre par défaut des sommets du graphe, 20 pixels par défaut.
default_node_border : épaisseur du bord des sommets, 2 pixels par défaut.
default_edge_width : épaisseur par défaut des arêtes du graphe,1 pixel par défaut.
default_edge_hi_width : taille par défaut des arêtes mises en évidence (en pixels), 3 pixels par défaut.
default_font_size : taille par défaut de la police utilisée pour afficher le nom des sommets et arêtes. 12 par défaut
node_label : vecteur ligne des noms des sommets
edge_label : vecteur ligne des noms des arêtes

Examples

    g=load_graph(SCI+'/demos/metanet/mesh100');
    g('node_color')=int(rand(1:g('node_number'))*16);
    g('edge_color')=int(rand(1:edge_number(g))*16);
    show_graph(g)

See Also

edit_graph , arc_number , check_graph , edge_number , glist , make_graph , node_number ,


hamilton

Scilab function
Last update : 16/06/2004

hamilton - circuit hamiltonien d'un graphe

Calling Sequence

cir = hamilton(g)

Parameters

  • g : graphe (liste)
  • cir : vecteur ligne d'entiers

Description

hamilton trouve un circuit Hamiltonien (s'il existe) du graphe orienté g .

Examples

ta=[2  1 3 2 2 4 4 5 6 7 8 8 9 10 10 10 10 11 12 13 13 14 15 16 16 17 17];
he=[1 10 2 5 7 3 2 4 5 8 6 9 7 7 11 13 15 12 13  9 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
g('node_diam')=[1:(g('node_number'))]+20;
show_graph(g);
cir=hamilton(g)
show_arcs(cir);


is_connex

Scilab function
Last update : 16/06/2004

is_connex - test de connexité

Calling Sequence

res = is_connex(g)

Parameters

  • g : graphe (liste)
  • res : entier, résultat du test

Description

is_connex renvoie 1 si le graphe g est connexe et 0 sinon.

Examples

g=make_graph('foo',1,3,[1,2,3,1],[2,3,1,3]);
is_connex(g)
g=make_graph('foo',1,4,[1,2,3,1],[2,3,1,3]);
is_connex(g)

See Also

con_nodes , strong_connex ,


knapsack

Scilab function
Last update : 16/06/2004

knapsack - résout un problème du sac à dos 0-1 multiple

Calling Sequence

[earn,ind] = knapsack(profit,weight,capa,[bck])

Parameters

  • profit : vecteur ligne d'entiers
  • weight : vecteur ligne d'entiers
  • capa : vecteur ligne d'entiers
  • bck : entier
  • earn : entier
  • ind : vecteur ligne d'entiers

Description

knapsack résout un problème du sac à dos 0-1 multiple avec n (n >= 2) objets et m sacs à dos (m >= 1). profit est le vecteur des profits (entiers) des n objets et weight est le vecteur des poids correspondants (entiers). capa est le vecteur des capacités (entières) des m sacs à dos. bck est un entier optionnel : le nombre maximum de backtrackings à effectuer, si une solution heuristique est exigée. Si la solution exacte est exigée bck peut être omis ou avoir une valeur négative. earn est la valeur du critère pour la solution "optimale" et ind est un vecteur donnant les positions optimales : ind(i) donne le numéro du sac à dos où l'objet i est mis et cette valeur est 0 si l'objet i n'est pas dans la solution optimale.

Rappelons que le problème à résoudre est le suivant : p(i) et w désignent respectivement le profit et le poids de l'objet i 1=1,...,n; c(j) désigne la capacité du sac à dos j j=1,...,m; q(j,i) désigne la quantité d'objets i dans le sac à dos j (en fait 0 ou 1).

On cherche à maximiser le profit global E : E=p(1)*[x(1,1)+...+x(m,1)]+...+p(n)*[x(1,n)+...+x(m,n)]

sous les contraintes :

    [w(1)*x(j,1)+...+w(n)*x(j,m)] <= c(j) ; j=1,...,m

    [x(1,i)+...+x(m,i)] <= 1 ; i=1,...,n

    x(j,i)= 0 ou 1

    p(),w(),c()
   sont des entiers positifs.

Examples

weight=ones(1,15).*.[1:4];
profit=ones(1,60);
capa=[15 45 30 60];
[earn,ind]=knapsack(profit,weight,capa)

See Also

qassign ,


line_graph

Scilab function
Last update : 16/06/2004

line_graph - graphe avec sommets correspondant aux arêtes

Calling Sequence

g1 = line_graph(g)

Parameters

  • g : graphe (liste)
  • g1 : nouveau graphe (liste)

Description

line_graph renvoie le graphe g1 avec les sommets correspondant aux arêtes du graphe g . g1 est défini de la façon suivante : - ses sommets correspondent aux arêtes de g - 2 sommets du nouveau graphe sont adjacents si et seulement si les arêtes correspondantes du graphe g sont adjacentes.

Les coordonnées des sommets de g1 sont données par les milieux des arêtes correspondantes de g .

Examples

ta=[1 1 2 4 4 5 6 7 2 3 5 1];
he=[2 6 3 6 7 8 8 8 4 7 3 5];
g=make_graph('foo',0,8,ta,he);
g('node_x')=[281  284  360  185  405  182  118  45];
g('node_y')=[262  179  130  154  368  248  64  309];
show_graph(g);
g1=line_graph(g);
show_graph(g1,'new');

See Also

arc_graph ,


load_graph

Scilab function
Last update : 16/06/2004

load_graph - charge un graphe

Calling Sequence

g = load_graph(name)

Parameters

  • name : chaîne de caractères, le chemin du graphe à charger
  • g : graphe (liste)

Description

name est le nom d'un fichier contenant la description ASCII d'un graphe. Un tel fichier doit avoir l'extension "graph" . name peut être le nom ou le chemin du fichier; si l'extension "graph" est omise dans name , elle est ajoutée. load_graph renvoie le graphe correspondant.

Examples

g=load_graph(SCI+'/demos/metanet/mesh100.graph');
show_graph(g);
g=load_graph(SCI+'/demos/metanet/colored');
show_graph(g,'new');

See Also

save_graph ,


make_graph

Scilab function
Last update : 16/06/2004

make_graph - création d'un graphe

Calling Sequence

g = make_graph(name,oriented,n,tail,head)

Parameters

  • name : chaîne de caractères, le nom du graphe
  • oriented : entier, 0 (graphe non-orienté graph) ou 1 (graphe orienté)
  • n : entier, le nombre de sommets du graphe
  • tail : vecteur ligne des numéros des sommets origines (sa taille est le nombre d'arêtes du graphe)
  • head : vecteur ligne des numéros des sommets destinations (sa taille est le nombre d'arêtes du graphe)
  • g : graphe (liste)

Description

make_graph crée un graphe à partir des arguments qui sont respectivement le nom du graphe, un flag pour orienté ou non-orienté, le nombre de sommets et les vecteurs lignes tail et head. Ce sont les données minimales nécessaires pour un graphe.

Si n est un nombre positif, le graphe g a n sommets; ce nombre doit être supérieur ou égal à max(max(tail),max(head)) . S'il est plus grand, le graphe g a des sommets isolés. Les noms des sommets sont égaux à leurs numéros. Si n est égal à 0, le graphe g n'a pas de sommets isolés et le nombre de sommets est calculé à partir de tail et head . Les noms des sommets sont pris à partie des numéros dans tail et head .

Examples

// création d'un graphe orienté avec 3 sommets et 4 arcs.
g=make_graph('foo',1,3,[1,2,3,1],[2,3,1,3]);
// création d'un graphe orienté avec 13 sommets et 14 arcs.
ta=[1  1 2 7 8 9 10 10 10 10 11 12 13 13];
he=[2 10 7 8 9 7  7 11 13 13 12 13  9 10];
g=make_graph('foo',1,13,ta,he);
g('node_x')=[120  98  87 188 439 698 226 127 342 467 711 779 477];
g('node_y')=[ 21 184 308 426 435 428 129 360 435  55 109 320 321];
show_graph(g)
// création d'un graphe sans sommet isolé et avec 14 arcs.
g=make_graph('foo',1,0,ta,he);
g('node_x')=[120  98 226 127 342 467 711 779 477];
g('node_y')=[ 21 184 129 360 435  55 109 320 321];
show_graph(g,'new')

See Also

graph-list ,


mat_2_graph

Scilab function
Last update : 16/06/2004

mat_2_graph - graphe à partir de matrice d'incidence sommets-arcs ou sommets-sommets

Calling Sequence

g = mat_2_graph(a,oriented,[mat])

Parameters

  • a : matrice creuse d'incidence sommets-arcs ou sommets-sommets
  • orienté : entier, 0 (graphe non-orienté ) ou 1 (graphe orienté)
  • mat : chaîne optionnelle, 'node-arc' ou 'node-node'
  • g : graphe (liste)

Description

mat_2_graph calcule le graphe g correspondant à la matrice creuse d'incidence sommets-arcs ou sommets-sommets a . Vérification est faite que a est une matrice d'incidence sommets-arcs ou sommets-sommets d'un graphe orienté ( orienté = 1 ) ou non-orienté ( non-orienté = 0 ). Si l'argument optionnel mat est omis ou est la chaîne de caractères 'node-arc' , a doit être une matrice sommets-arcs. Si mat est la chaîne de caractères 'node-node' , a doit être une matrice sommets-sommets.

Examples

g=load_graph(SCI+'/demos/metanet/colored');
show_graph(g);
a=graph_2_mat(g);
g1=mat_2_graph(a,1);
g1('node_x')=g('node_x'); g1('node_y')=g('node_y');
show_graph(g1,'new');
a=graph_2_mat(g,'node-node');
g1=mat_2_graph(a,1,'node-node');
g1('node_x')=g('node_x'); g1('node_y')=g('node_y');
show_graph(g1,'new');

See Also

adj_lists , chain_struct , graph_2_mat ,


max_cap_path

Scilab function
Last update : 16/06/2004

max_cap_path - chemin de capacité maximum

Calling Sequence

[p,cap] = max_cap_path(i,j,g)

Parameters

  • i,j : entiers, numéros des sommets
  • g : graphe (liste)
  • p : vecteur ligne des numéros des arcs du chemin s'il existe
  • cap : valeur de la capacité du chemin

Description

max_cap_path renvoie le chemin de capacité maximum du sommet i au sommet j pour le graphe g s'il existe, et renvoie le vecteur vide [] sinon.

Les capacités des arêtes sont données par l'élément edge_max_cap du graphe. Si sa valeur n'est pas donnée (vecteur vide [] ), max_cap_path renvoie le vecteur vide [] . Les capacités doivent être strictement positives, i.e les capacités négatives sont considérées égales à 0 (aucune capacité).

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
ma=edge_number(g);
g('edge_max_cap')=int(rand(1,ma)*16)+5;
[p,cap]=max_cap_path(1,14,g);
edgecolor=1*ones(1,ma); edgecolor(p)=11*ones(p); g('edge_color')=edgecolor;
x_message(['La capacité maximum est : '+string(cap);
           'Voici le chemin correspondant']);
show_graph(g); show_arcs(p);


max_clique

Scilab function
Last update : 16/06/2004

max_clique - clique maximum d'un graphe

Calling Sequence

[size,nodes] = max_clique(g,[ind])

Parameters

  • g : graphe (liste)
  • ind : entier (optionnel)
  • size : entier
  • nodes : vecteur ligne d'entiers

Description

max_clique calcule la clique maximum d'un graphe g i.e. le sous-graphe complet de taille maximum. ind est un paramètre pour le choix de la méthode: si ind vaut 0 la méthode est un algorithme partiellement énumératif et si ind vaut 1 l'algorithme est de type programmation quadratique zéro-un. La valeur est 0 par défaut. La sortie size est le nombre de sommets de la clique trouvée par l'algorithme et nodes est le vecteur des sommets correspondants.

Examples

ta=[1 2 3 4 5 6 6 7 8  9 10 16 16 10 11 11 12 12 11 14 15 15 13 7 13 13];
he=[2 3 4 5 6 7 8 8 9 10 16  2  3 11 12 13  1 14 14 15  5  9 12 4 14 15];
g=make_graph('foo',0,16,ta,he);
g('node_x')=[106 199 369 467 470 403 399 347 308 269 184 108 199 268 345 272];
g('node_y')=[341 420 422 321 180 212 286 246 193 244 243 209  59 134  51 348];
g('node_diam')=[1:(g('node_number'))]+20;
show_graph(g);
[ns,no] = max_clique(g);
show_nodes(no);
g1=graph_complement(g);
[ns,no] = max_clique(g1);
show_nodes(no);


max_flow

Scilab function
Last update : 16/06/2004

max_flow - flot maximum entre deux sommets

Calling Sequence

[v,phi,flag] = max_flow(i,j,g)

Parameters

  • i : entier, numéro du sommet de départ
  • j : entier, numéro du sommet d'arrivée
  • g : graphe (liste)
  • v : valeur du flot maximum, si elle existe
  • phi : vecteur ligne des valeurs des flots sur les arcs
  • flag : problème soluble ou non (0 ou 1)

Description

max_flow renvoie la valeur du flot maximum v du sommet i au sommet j si elle existe, et la valeur des flots sur chaque arc sous forme d'un vecteur ligne phi . Les calculs sont faits en nombres entiers. Le graphe doit être orienté. Si le problème n'est pas soluble, flag est égal à 0, sinon il est égal à 1.

Les bornes sur le flot sont données par les éléments edge_min_cap et edge_max_cap du graphe. La valeur de la capacité maximum doit être supérieure ou égale à la capacité minimum. Si la valeur de edge_min_cap ou edge_max_cap n'est pas donnée (vecteur ligne vide [] ), elle est supposée égale à 0 sur chaque arête.

Examples

ta=[1 1 2 2 3 3 4 4 5 5 5 5 6 6 6 7 7 15 15 15 15 15 15];
ta=[ta, 15 8 9 10 11 12 13 14];
he=[10 13 9 14 8 11 9 11 8 10 12 13 8 9 12 8 11 1 2 3 4];
he=[he, 5 6 7 16 16 16 16 16 16 16];
n=16;
g=make_graph('foo',1,n,ta,he);
g('node_x')=[42 615 231 505 145 312 403 233 506 34 400 312 142 614 260 257];
g('node_y')=[143 145 154 154 147 152 157 270 273 279 269 273 273 274 50 376];
ma=edge_number(g);
g('edge_max_cap')=ones(1,ma);
g('edge_min_cap')=zeros(1,ma);
source=15; sink=16;
nodetype=0*ones(1,n); nodetype(source)=2; nodetype(sink)=1;
g('node_type')=nodetype;
nodecolor=0*ones(1,n); nodecolor(source)=11; nodecolor(sink)=11;
g('node_color')=nodecolor;
show_graph(g);
[v,phi,ierr]=max_flow(source,sink,g);
ii=find(phi<>0); edgecolor=phi; edgecolor(ii)=11*ones(ii);
g('edge_color')=edgecolor;
edgefontsize=8*ones(1,ma); edgefontsize(ii)=18*ones(ii);
g('edge_font_size')=edgefontsize;
g('edge_label')=string(phi);
show_graph(g);


mesh2d

Scilab function
Last update : 13/05/2004

mesh2d - triangulation of n points in the plane

Calling Sequence

[nutr,A] = mesh2d(x,y,[front])

Parameters

  • x : real row array
  • y : real row array
  • front : integer row array
  • nutr : integer matrix
  • A : sparse 0-1 matrix

Description

The arrays x and y are the coordinates of n points in the plane. mesh2d returns a matrix nutr(3,nbt) of the numbers of the nodes of the nbt triangles of the triangulation of the points. It returns also a sparse matrix A representing the connections between the nodes ( A(i,j)=1 if (i,j) is a side of one of the triangles or i=j ). In the case of 3 parameters front is the array defining the boundary: it is the array of the indices of the points located on the boundary . The boundary is defined such that the normal to the boundary is oriented towards outside. The boundary is given by its connected components: a component is the part (i1,i2) such that front(i1)=front(i2) (the external boundary is defined in the counterclockwise way, see the examples below). The error cases are the following: err = 0 if no errors were encountered; err = 3 all nodes are collinear.

If the boundary is given, the other error cases are:
           err = 2 some points are identical;
    err = 5 wrong boundary array;
           err = 6 crossed boundary;
           err = 7 wrong orientation of the boundary;
           err = 10 an interior point is on the boundary;
           err = 8 size limitation;
           err = 9 crossed boundary;
           err = 12 some points are identical or size limitation.

Examples

// FIRST CASE
theta=0.025*[1:40]*2.*%pi;
x=1+cos(theta);
y=1.+sin(theta);
theta=0.05*[1:20]*2.*%pi;
x1=1.3+0.4*cos(theta);
y1=1.+0.4*sin(theta);
theta=0.1*[1:10]*2.*%pi;
x2=0.5+0.2*cos(theta);
y2=1.+0.2*sin(theta);
x=[x x1 x2];
y=[y y1 y2];
//
nu=mesh2d(x,y);
nbt=size(nu,2);
jj=[nu(1,:)' nu(2,:)';nu(2,:)' nu(3,:)';nu(3,:)' nu(1,:)'];
as=sparse(jj,ones(size(jj,1),1));
ast=tril(as+abs(as'-as));
[jj,v,mn]=spget(ast);
n=size(x,2);
g=make_graph('foo',0,n,jj(:,1)',jj(:,2)');
g('node_x')=300*x;
g('node_y')=300*y;
g('default_node_diam')=10;
show_graph(g)
// SECOND CASE !!! NEEDS x,y FROM FIRST CASE
x3=2.*rand(1:200);
y3=2.*rand(1:200);
wai=((x3-1).*(x3-1)+(y3-1).*(y3-1));
ii=find(wai >= .94);
x3(ii)=[];y3(ii)=[];
wai=((x3-0.5).*(x3-0.5)+(y3-1).*(y3-1));
ii=find(wai <= 0.055);
x3(ii)=[];y3(ii)=[];
wai=((x3-1.3).*(x3-1.3)+(y3-1).*(y3-1));
ii=find(wai <= 0.21);
x3(ii)=[];y3(ii)=[];
xnew=[x x3];ynew=[y y3];
fr1=[[1:40] 1];fr2=[[41:60] 41];fr2=fr2($:-1:1);
fr3=[[61:70] 61];fr3=fr3($:-1:1);
front=[fr1 fr2 fr3];
//
nu=mesh2d(xnew,ynew,front);
nbt=size(nu,2);
jj=[nu(1,:)' nu(2,:)';nu(2,:)' nu(3,:)';nu(3,:)' nu(1,:)'];
as=sparse(jj,ones(size(jj,1),1));
ast=tril(as+abs(as'-as));
[jj,v,mn]=spget(ast);
n=size(xnew,2);
g=make_graph('foo',0,n,jj(:,1)',jj(:,2)');
g('node_x')=300*xnew;
g('node_y')=300*ynew;
g('default_node_diam')=10;
show_graph(g)
// REGULAR CASE !!! NEEDS PREVIOUS CASES FOR x,y,front
xx=0.1*[1:20];
yy=xx.*.ones(1,20);
zz= ones(1,20).*.xx;
x3=yy;y3=zz;
wai=((x3-1).*(x3-1)+(y3-1).*(y3-1));
ii=find(wai >= .94);
x3(ii)=[];y3(ii)=[];
wai=((x3-0.5).*(x3-0.5)+(y3-1).*(y3-1));
ii=find(wai <= 0.055);
x3(ii)=[];y3(ii)=[];
wai=((x3-1.3).*(x3-1.3)+(y3-1).*(y3-1));
ii=find(wai <= 0.21);
x3(ii)=[];y3(ii)=[];
xnew=[x x3];ynew=[y y3];
nu=mesh2d(xnew,ynew,front);
nbt=size(nu,2);
jj=[nu(1,:)' nu(2,:)';nu(2,:)' nu(3,:)';nu(3,:)' nu(1,:)'];
as=sparse(jj,ones(size(jj,1),1));
ast=tril(as+abs(as'-as));
[jj,v,mn]=spget(ast);
n=size(xnew,2);
g=make_graph('foo',0,n,jj(:,1)',jj(:,2)');
g('node_x')=300*xnew;
g('node_y')=300*ynew;
g('default_node_diam')=3;
show_graph(g)

//An example with a random set of points
function []=test(X,Y)
  Tr=mesh2d(X,Y);
  plot2d(X,Y,[-1,-2,3]);
  [m,n]=size(Tr);
  xpols= matrix(X(Tr),m,n);
  ypols= matrix(Y(Tr),m,n);
  xset("colormap",rand(2*n,3));
  xfpolys(xpols,ypols,[n/4:n/4+n-1]);
endfunction
N=1000;xbasc();X=rand(1,N); Y=rand(1,N);
xset("wdim",700,700);
test(X,Y);


min_lcost_cflow

Scilab function
Last update : 16/06/2004

min_lcost_cflow - flot contraint de coût linéaire minimum

Calling Sequence

[c,phi,v,flag] = min_lcost_cflow(i,j,cv,g)

Parameters

  • i : entier, numéros des sommets sources
  • j : entier, numéros des sommets puits
  • cv : scalaire, valeur du flot contraint
  • g : graphe (liste)
  • c : valeur du coût
  • phi : vecteur ligne des valeurs des flots sur les arcs
  • v : vecteur ligne des flots des sources aux puits
  • flag : problème soluble ou pas (0 ou 1)

Description

min_lcost_cflow calcule flot de coût linéaire minimum dans un réseau g , avec les valeurs des flots des sommets sources i aux puits j contraints à valoir cv .

Elle renvoie le coût total du flot sur les arcs c et le vecteur ligne des flots sur les arcs phi et les valeurs des flots v sur les arcs virtuels des sources aux puits. Si v est plus petit que cv , un message est affiché, mais le calcul est fait quand même. Dans ce cas flag est égal à 0, sinon il est égal à 1.

es bornes sur les flots sont données par les éléments edge_min_cap et edge_max_cap du graphe. La valeur de la capacité minimum doit être égal à zéro. Les valeurs des capacités maximum doivent être entières et positives. Si les valeurs edge_min_cap ou edge_max_cap ne sont pas données (vecteur vide [] ), elles sont supposées nulles sur chaque arête.

Les coûts sur les arêtes sont donnés par les éléments edge_cost du graphe. Les coûts doivent être positifs.

Si la valeur de edge_cost n'est pas donnée (vecteur vide [] ), elle est supposé nulle sur chaque arête.

Si la valeur de edge_cost n'est pas donnée (vecteur vide [] ), elle est supposé nulle sur chaque arête.

Cette fonction utilise l'algorithme de Busacker et Goven.

Examples

ta=[1 1 2 2 2 3 4 4 5 6 6 6 7 7 7 8 9 10 12 12 13 13 13 14 15 14 9 11 10];
he=[2 6 3 4 5 1 3 5 1 7 10 11 5 8 9 5 8 11 10 11 9 11 15 13 14 4 6 9 1];
g=make_graph('foo',1,15,ta,he);
g('node_x')=[194 191 106 194 296 305 305 418 422 432 552 550 549 416 548];
g('node_y')=[56 181 276 278 276 103 174 281 177 86 175 90 290 397 399];
show_graph(g);
g1=g; ma=arc_number(g1); n=g1('node_number');
g1('edge_min_cap')=0*ones(1,ma);
rand('uniform');
g1('edge_max_cap')=round(20*rand(1,ma))+ones(1,ma);
g1('edge_cost')=10*rand(1,ma)+ones(1,ma);
source=15; sink=1; cv=5;
[c,phi,v]=min_lcost_cflow(source,sink,cv,g1);
x_message(['Le cout est: '+string(c);
           'Voici les flots sur les arcs']);
nodetype=0*ones(1,n); nodetype(source)=2; nodetype(sink)=1;
g1('node_type')=nodetype;
ii=find(phi<>0); edgecolor=phi; edgecolor(ii)=11*ones(ii);
g1('edge_color')=edgecolor;
edgefontsize=8*ones(1,ma); edgefontsize(ii)=18*ones(ii);
nodecolor=0*ones(1,n); nodecolor(source)=11; nodecolor(sink)=11;
g1('node_color')=nodecolor;
g1('edge_font_size')=edgefontsize;
g1('edge_label')=string(phi);
show_graph(g1);

See Also

min_lcost_flow1 , min_lcost_flow2 , min_qcost_flow ,


min_lcost_flow1

Scilab function
Last update : 16/06/2004

min_lcost_flow1 - flot de coût linéaire minimum

Calling Sequence

[c,phi,flag] = min_lcost_flow1(g)

Parameters

  • g : graphe (liste)
  • c : valeur du coût
  • phi : vecteur ligne des valeurs des flots sur les arcs
  • flag : problème soluble ou pas (0 ou 1)

Description

min_lcost_flow1 calcule flot de coût linéaire minimum dans un réseau g . Elle renvoie le coût total du flot sur les arcs c et le vecteur ligne des flots sur les arcs phi . Si le problème n'est pas soluble (impossible de trouver un flot compatible), flag est égal à 0, sinon il est égal à 1.

Les bornes sur les flots sont données par les éléments edge_min_cap et edge_max_cap du graphe. Les valeurs des capacités maximum et minimum doivent être entières et positives. La valeur de la capacité maximum doit être supérieure ou égale à la valeur de la capacité minimum. Si la valeur de edge_cost n'est pas donnée (vecteur vide [] ), elle est supposé nulle sur chaque arête.

Les coûts sur les arêtes sont donnés par les éléments edge_cost du graphe. Les coûts doivent être positifs. Si la valeur de edge_cost n'est pas donnée (vecteur vide [] ), elle est supposé nulle sur chaque arête.

Les demandes, i.e. les élément node_demand du graphe, doivent être égales à zéro.

Cette fonction utilise l'algorithme out-of-kilter.

Examples

ta=[1 1 2 2 2 3 4 4 5 6 6 6 7 7 7 8 9 10 12 12 13 13 13 14 15 14 9 11 10 1 8];
he=[2 6 3 4 5 1 3 5 1 7 10 11 5 8 9 5 8 11 10 11 9 11 15 13 14 4 6 9 1 12 14];
g=make_graph('foo',1,15,ta,he);
g('node_x')=[194 191 106 194 296 305 305 418 422 432 552 550 549 416 548];
g('node_y')=[56 221 316 318 316 143 214 321 217 126 215 80 330 437 439];
show_graph(g);
g1=g;ma=arc_number(g1);
rand('uniform');
while %T then
  g1('edge_min_cap')=round(20*rand(1,ma));
  g1('edge_max_cap')=round(20*rand(1,ma))+g1('edge_min_cap')+33*ones(1,ma);
  g1('edge_cost')=round(10*rand(1,ma))+ones(1,ma);
  [c,phi,flag]=min_lcost_flow1(g1);
  if flag==1 then break; end;
end;
x_message(['Le cout est: '+string(c);
           'Flots sur les arcs ']);
ii=find(phi<>0); edgecolor=phi; edgecolor(ii)=11*ones(ii);
g1('edge_color')=edgecolor;
edgefontsize=8*ones(1,ma); edgefontsize(ii)=18*ones(ii);
g1('edge_font_size')=edgefontsize;
g1('edge_label')=string(phi);
show_graph(g1);

See Also

min_lcost_cflow , min_lcost_flow2 , min_qcost_flow ,


min_lcost_flow2

Scilab function
Last update : 16/06/2004

min_lcost_flow2 - flot de coût linéaire minimum

Calling Sequence

[c,phi,flag] = min_lcost_flow2(g)

Parameters

  • g : graphe (liste)
  • c : valeur du coût
  • phi : vecteur ligne des valeurs des flots sur les arcs
  • flag : problème soluble ou pas (0 ou 1)

Description

min_lcost_flow2 calcule flot de coût linéaire minimum dans un réseau g . Elle renvoie le coût total du flot sur les arcs c et le vecteur ligne des flots sur les arcs phi . Si le problème n'est pas soluble (impossible de trouver un flot compatible), flag est égal à 0, sinon il est égal à 1.

Les bornes sur les flots sont données par les éléments edge_min_cap et edge_max_cap du graphe. La valeur de la capacité minimum doit être égal à zéro. Les valeurs des capacités maximum doivent être entières et positives. Si les valeurs edge_min_cap ou edge_max_cap ne sont pas données (vecteur vide [] ), elles sont supposées nulles sur chaque arête.

Les coûts sur les arêtes sont donnés par les éléments edge_cost du graphe. Les coûts doivent être entiers et positifs. Si la valeur de edge_cost n'est pas donnée (vecteur vide [] ), elle est supposé nulle sur chaque arête.

La demande sur les sommets est donnée par l'élément node_demand du graphe. Les demandes doivent être des nombre entiers. La somme des demandes doit être nulle pour que le problème soit soluble. Si la valeur de node_demand n'est pas donnée (vecteur vide [] ), elle est supposée nulle sur chaque sommet.

Cette fonction utilise un algorithme de relaxation dû à D. Bertsekas.

Examples

ta=[1 1 2 2 2 3 4 4 5 6 6 6 7 7 7 8 9 10 12 12 13 13 13 14 15 14 9 11 10 1 8];
he=[2 6 3 4 5 1 3 5 1 7 10 11 5 8 9 5 8 11 10 11 9 11 15 13 14 4 6 9 1 12 14];
g=make_graph('foo',1,15,ta,he);
g('node_x')=[194 191 106 194 296 305 305 418 422 432 552 550 549 416 548];
g('node_y')=[56 221 316 318 316 143 214 321 217 126 215 80 330 437 439];
show_graph(g);
g1=g; ma=arc_number(g1); n=g1('node_number');
g1('edge_min_cap')=0.*ones(1,ma);
x_message(['Generation aléatoire des données';
           'Les premiers problèmes générés peuvent être insolubles']);
while %T then
 rand('uniform');
 g1('edge_max_cap')=round(20*rand(1,ma))+20*ones(1,ma);
 g1('edge_cost')=round(10*rand(1,ma)+ones(1,ma));
 rand('normal');
 dd=20.*rand(1,n)-10*ones(1,n);
 dd=round(dd-sum(dd)/n*ones(1,n));
 dd(n)=dd(n)-sum(dd);
 g1('node_demand')=dd;
 [c,phi,flag]=min_lcost_flow2(g1);
 if flag==1 then break; end;
end;
x_message(['Le cout est: '+string(c);
           'Voici le flot sur les arcs et les demandes des sommets']);
ii=find(phi<>0); edgecolor=phi; edgecolor(ii)=11*ones(ii);
g1('edge_color')=edgecolor;
edgefontsize=8*ones(1,ma); edgefontsize(ii)=18*ones(ii);
g1('edge_font_size')=edgefontsize;
g1('edge_label')=string(phi);
g1('node_label')=string(g1('node_demand'));
show_graph(g1);

See Also

min_lcost_cflow , min_lcost_flow1 , min_qcost_flow ,


min_qcost_flow

Scilab function
Last update : 16/06/2004

min_qcost_flow - flot de coût quadratique minimum

Calling Sequence

[c,phi,flag] = min_qcost_flow(eps,g)

Parameters

  • eps : scalaire, précision
  • g : graphe (liste)
  • c : valeur du coût
  • phi : vecteur ligne des valeurs des flots sur les arcs
  • flag : problème soluble ou pas (0 ou 1)

Description

min_qcost_flow calcule flot de coût quadratique minimum dans un réseau g . Elle renvoie le coût total du flot sur les arcs c et le vecteur ligne des flots sur les arcs phi . eps est la précision de l'algorithme itératif. Si le problème n'est pas soluble (impossible de trouver un flot compatible), flag est égal à 0, sinon il est égal à 1.

Les bornes sur les flots sont données par les éléments edge_min_cap et edge_max_cap du graphe. La valeur de la capacité maximum doit être supérieure ou égale à la valeur de la capacité minimum. Si les valeurs edge_min_cap ou edge_max_cap ne sont pas données (vecteur vide [] ), elles sont supposées nulles sur chaque arête.

Les coûts sur les arêtes sont donnés par les éléments edge_q_orig et edge_q_weight du graphe. Le coût sur l'arc u est donné par:

(1/2)*edge_q_weight[u](phi[u]-edge_q_orig[u])^2

Les coûts doivent être positifs. Si les valeurs de edge_q_orig ou edge_q_weight ne sont pas données (vecteur vide [] ), elles sont supposées nulles sur chaque arête.

Cette fonction utilise un algorithme dû à M. Minoux.

Examples

ta=[1 1 2 2 2 3 4 4 5 6 6 6 7 7 7 8 9 10 12 12 13 13 13 14 15 14 9 11 10 1 8];
he=[2 6 3 4 5 1 3 5 1 7 10 11 5 8 9 5 8 11 10 11 9 11 15 13 14 4 6 9 1 12 14];
g=make_graph('foo',1,15,ta,he);
g('node_x')=[194 191 106 194 296 305 305 418 422 432 552 550 549 416 548];
g('node_y')=[56 221 316 318 316 143 214 321 217 126 215 80 330 437 439];
show_graph(g);
g1=g; ma=arc_number(g1);
rand('uniform');
while %T then
  g1('edge_min_cap')=round(5*rand(1,ma));
  g1('edge_max_cap')=round(20*rand(1,ma))+30*ones(1,ma);
  g1('edge_q_orig')=0*ones(1,ma);
  g1('edge_q_weight')=ones(1,ma);
  [c,phi,flag]=min_qcost_flow(0.001,g1);
 if flag==1 then break; end;
end;
x_message(['Le cout est: '+string(c);
          'Voici le flot sur les arcs']);
ii=find(phi<>0); edgecolor=phi; edgecolor(ii)=11*ones(ii);
g1('edge_color')=edgecolor;
edgefontsize=8*ones(1,ma); edgefontsize(ii)=18*ones(ii);
g1('edge_font_size')=edgefontsize;
g1('edge_label')=string(phi);
show_graph(g1);

See Also

min_lcost_cflow , min_lcost_flow1 , min_lcost_flow2 ,


min_weight_tree

Scilab function
Last update : 16/06/2004

min_weight_tree - arbre couvrant de poids minimum

Calling Sequence

t = min_weight_tree([i],g)

Parameters

  • i : entier, numéro de sommet racine de l'arbre
  • g : graphe (liste)
  • t : vecteur ligne d'entiers : numéros des arcs de l'arbre s'il existe

Description

min_weight_tree essaye de trouver un arbre couvrant de poids minimum pour l'arbre graphe g . L'argument optionnel i est le numéro du sommet racine de l'arbre; sa valeur par défaut est le sommet 1. Ce sommet n'est pas significatif pour un graphe non-orienté.

Les poids sont données par les éléments edge_weight du graphe. Si ces valeurs ne sont pas données (vecteur vide [] ), elles sont supposées nulles. Les poids peuvent être positifs, nuls ou négatifs. Pour calculer un arbre recouvrant sans tenir compte des poids, leur donner une valeur nulle ou vide [] .

min_weight_tree renvoie l'arbre t sous forme d'un vecteur ligne des numéros d'arcs (cas orienté) ou d'arêtes (cas non-orienté), si il existe, ou le vecteur vide [] sinon. Si l'arbre existe, la dimension de t est le nombre de sommets moins 1. Si t(i) est la racine de l'arbre, - pour j < i, t(j) est le numéro de l'arc dans l'arbre après le sommet t(j) - pour j > i, t(j) est le numéro de l'arc dans l'arbre avant le sommet t(j)

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
t=min_weight_tree(1,g);
g1=g; ma=arc_number(g1); n=g1('node_number');
nodetype=0*ones(1,n); nodetype(1)=2; g1('node_type')=nodetype;
edgecolor=1*ones(1,ma); edgecolor(t)=11*ones(t); g1('edge_color')=edgecolor;
edgewidth=1*ones(1,ma); edgewidth(t)=4*ones(t); g1('edge_width')=edgewidth;
x_message('Arbre de poids minimum à partir du sommet 1');
show_graph(g1);


neighbors

Scilab function
Last update : 16/06/2004

neighbors - sommets voisins connectés à un sommet

Calling Sequence

a = neighbors(i,g)

Parameters

  • i : entier
  • g : graphe (liste)
  • a : vecteur d'entiers

Description

neighbors renvoie les numéros des sommets connectés avec le sommet i pour le graphe g (orienté ou non).

Examples

ta=[1  6  2  4  7  5  6  8  4  3  5  1];
he=[2  1  3  6  4  8  8  7  2  7  3  5];
g=make_graph('foo',1,8,ta,he);
g('node_x')=[285  284  335  160  405  189  118  45];
g('node_y')=[266  179   83  176  368  252  64  309];
show_graph(g);
a=neighbors(6,g)
show_nodes(a);

See Also

predecessors , successors ,


netclose

Scilab Function
Last update : 12/01/2004

netclose - closes an edit_graph window

Calling Sequence

netclose(window)

Parameters

  • window : integer, window number

Description

Each editgraph window has a window number returned by edit_graph and show_graph functions. This function is used to close the edit_graph window with number window .

See Also

edit_graph , netwindow , netwindows , show_graph ,


netwindows

Scilab function
Last update : 12/01/2004

netwindows - gets the numbers of edit_graph windows

Calling Sequence

l = netwindows()

Parameters

  • l : list

Description

This function returns a list l . Its first element is the row vector of all the edit_graph windows and the second element is the number of the current edit_graph window. This number is equal to 0 if no current Metanet window exists.

See Also

edit_graph , netclose , netwindow , show_graph ,


netwindow

Scilab function
Last update : 12/01/2004

netwindow - selects the current edit_graph window

Calling Sequence

netwindow(window)

Parameters

  • window : integer, window number

Description

This function is used to change the current edit_graph window to those given by the window argument. Current edit_graph window is used by show_arcs, show_nodes,.. functions. The numbers of existing windows are given by the function netwindows .

See Also

edit_graph , netclose , netwindows , show_graph ,


nodes_2_path

Scilab function
Last update : 16/06/2004

nodes_2_path - chemin reliant un ensemble de sommets

Calling Sequence

p = nodes_2_path(ns,g)

Parameters

  • ns : vecteur ligne des numéros de sommets
  • g : graphe (liste)
  • p : vecteur ligne des numéros des arcs si le chemin existe

Description

nodes_2_path renvoie, s'il existe, le chemin p correspondant à la séquence de sommets ns ; sinon, le vecteur vide [] est renvoyé

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
ns=[1 10 15 16 17 14 11 12 13 9 7 8 6];
g1=g; nodecolor=1*ones(g('node_x')); nodecolor(ns)=11*ones(ns);
g1('node_color')=nodecolor;
show_graph(g1); show_nodes(ns);
p=nodes_2_path(ns,g);
g1=g; edgecolor=1*ones(ta); edgecolor(p)=11*ones(p);
g1('edge_color')=edgecolor;
show_graph(g1); show_arcs(p);
show_nodes(ns,'sup');

See Also

path_2_nodes ,


nodes_degrees

Scilab function
Last update : 16/06/2004

nodes_degrees - degrés des sommets d'un graphe

Calling Sequence

[outdegree,indegree] = graph_degree(g)

Parameters

  • g : graphe (liste)
  • outdegree : vecteur ligne des degrés entrants des sommets
  • indegree : vecteur ligne des degrés sortants des sommets

Description

nodes_degrees renvoie les 2 vecteurs lignes des degrés entrants et sortants des sommets du graphe g .

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
[outdegree,indegree]=nodes_degrees(g)

See Also

adj_lists ,


node_number

Scilab function
Last update : 16/06/2004

node_number - nombre de sommets d'un graphe

Calling Sequence

n = node_number(g)

Parameters

  • g : graphe (liste)
  • n : entier, nombre de sommets

Description

node_number renvoie le nombre n de sommets du graphe.

See Also

arc_number , edge_number ,


path_2_nodes

Scilab function
Last update : 16/06/2004

path_2_nodes - ensemble de sommets d'un chemin

Calling Sequence

ns = path_2_nodes(p,g)

Parameters

  • p : vecteur ligne des numéros des arcs formant le chemin
  • g : graphe (liste)
  • ns : vecteur ligne des numéros des sommets

Description

path_2_nodes renvoie le vecteur des numéros des sommets ns correspondant au chemin p donné par les numéros des arcs le composant; si p n'est pas un chemin, le vecteur vide [] est renvoyé.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
p=[2 16 23 25 26 22 17 18 19 13 10 11];
g1=g; edgecolor=1*ones(ta); edgecolor(p)=11*ones(p);
g1('edge_color')=edgecolor;
show_graph(g1); show_arcs(p);
ns=path_2_nodes(p,g);
g1=g; nodecolor=1*ones(g1('node_number')); nodecolor(ns)=11*ones(ns);
g1('node_color')=nodecolor;
show_graph(g1);show_nodes(ns);
show_arcs(p,'sup');

See Also

nodes_2_path ,


perfect_match

Scilab function
Last update : 16/06/2004

perfect_match - appariement parfait de coût minimum

Calling Sequence

[cst,nmatch] = perfect_match(g,arcost)

Parameters

  • g : graphe (liste)
  • arcost : vecteur ligne d'entiers
  • cst : entier
  • nmatch : vecteur ligne d'entiers

Description

perfect_match trouve un appariement parfait de coût minimum pour le graphe g . g doit être un graphe non-orienté avec un nombre pair de sommets. arcost est le vecteur des coût (entiers) des arcs (la dimension de arcost est le double du nombre d'arêtes du graphe). Les sorties sont le vecteur nmatch de l'appariement parfait et le coût correspondant cst .

Examples

ta=[27 27 3 12 11 12 27 26 26 25 25 24 23 23 21 22 21 20 19 18 18];
ta=[ta  16 15 15 14 12 9 10 6 9 17 8 17 10 20 11 23 23 12 18 28];
he=[ 1  2 2  4  5 11 13  1 25 22 24 22 22 19 13 13 14 16 16  9 16];
he=[he  10 10 11 12  2 6  5 5 7  8 7  9  6 11  4 18 13  3 28 17];
n=28;
g=make_graph('foo',0,n,ta,he);
xx=[46 120 207 286 366 453 543 544 473 387 300 206 136 250 346 408];
g('node_x')=[xx 527 443 306 326 196 139 264  55  58  46 118 513];
yy=[36  34  37  40  38  40  35 102 102  98  93  96 167 172 101 179];
g('node_y')=[yy 198 252 183 148 172 256 259 258 167 109 104 253];
show_graph(g);m2=2*size(ta,2);
arcost=round(100.*rand(1,m2));
[cst,nmatch] = perfect_match(g,arcost);
sp=sparse([ta' he'],[1:size(ta,2)]',[n,n]);
sp1=sparse([[1:n]' nmatch'],ones(1,size(nmatch,2))',[n,n]);
[ij,v,mn]=spget(sp.*sp1);
show_arcs(v');

See Also

best_match ,


pipe_network

Scilab function
Last update : 16/06/2004

pipe_network - résout le problème du réseau de tuyaux

Calling Sequence

[x,pi] = pipe_network(g)

Parameters

  • g : graphe (liste)
  • x : vecteur ligne des valeurs des flots sur les arcs
  • pi : vecteur ligne des potentiels sur les sommets

Description

pipe_network renvoie les valeurs des flots et des potentiels pour le problème du réseau de tuyaux (problème de flots avec deux lois de Kirchhoff). Le graphe doit être orienté. Le problème doit être soluble (la somme des demandes des sommets doit être égale à 0). Les résistances sur les arcs doivent être strictement positives et sont données par les valeurs de l'élément 'edge_weight' du graphe.

Le problème est résolu à l'aide d'une factorisation LU creuse.

Examples

ta=[1 1 2 2 3 3 4 4 5 5 5 5 6 6 6 7 7 15 15 15 15 15 15];
ta=[ta, 15 8 9 10 11 12 13 14];
he=[10 13 9 14 8 11 9 11 8 10 12 13 8 9 12 8 11 1 2 3 4];
he=[he, 5 6 7 16 16 16 16 16 16 16];
n=16;
g=make_graph('foo',1,n,ta,he);
g('node_x')=[42 615 231 505 145 312 403 233 506 34 400 312 142 614 260 257];
g('node_y')=[143 145 154 154 147 152 157 270 273 279 269 273 273 274 50 376];
show_graph(g);
g('node_demand')=[0 0 0 0 0 0 0 0 0 0 0 0 0 0 -100 100];
w = [1 3 2 6 4 7 8 1 2 2 2 4 7 8 9 2 3 5 7 3 2 5 8 2 5 8];
g('edge_weight')=[w, 6 4 3 5 6];
[x,pi] = pipe_network(g)


plot_graph

Scilab function
Last update : 16/06/2004

plot_graph - affichage général d'un graphe

Calling Sequence

plot_graph(g,[rep,rep1])

Parameters

  • g : graphe (liste)
  • rep : vecteur ligne de 13 valeurs de paramètres pour l'affichage
  • rep1 : vecteur ligne de 4 valeurs définissant le rectangle d'affichage

Description

plot_graph représente le graphe g dans une fenêtre graphique Scilab. Les arguments optionnels rep et rep1 définissent les paramètres d'affichage. S'ils ne sont pas fournis, une boîte de dialogue permet de les définir interactivement.

rep doit être un vecteur ligne avec 13 nombres entiers égaux à 1 ou 2. La signification des ces valeurs de rep est :

Définition du cadre : 1 = Automatique 2 = Donné (voir ci dessous)

Affichage des flèches : 1 = oui, 2 = non

Affichage des sommets sources et puits : 1 = oui, 2 = non

Affichage des noms des sommet : 1 = oui, 2 = non

Affichage des labels des sommets : 1 = oui, 2 = non

Affichage des noms des arcs : 1 = oui, 2 = non

Affichage des labels des arcs : 1 = oui, 2 = non

Affichage des demandes des sommets : 1 = oui, 2 = non

Affichage des longueurs des arêtes : 1 = oui, 2 = non

Affichage des coûts des arêtes : 1 = oui, 2 = non

Affichage des capacités min des arêtes : 1 = oui, 2 = non

Affichage des capacités max des arêtes : 1 = oui, 2 = non

Affichage des poids des arêtes : 1 = oui, 2 = non

Si rep(1) vaut 2, la définition du cadre doit être donnée par rep1 . Sinon, rep1 peut être omis. rep1 doit être un vecteur ligne [orx,ory,w,h] donnant respectivement les coordonnées du point en haut à gauche, la largeur et la hauteur du rectangle d'affichage.

Examples

// graphe simple avec différents choix pour l'affichage
ta=[2 2 1 1 2 4 3 3 4];
he=[2 2 3 2 3 2 1 2 1];
g=make_graph('foo',1,4,ta,he);
g('node_type')=[1 1 1 2];g('node_name')=string([1:4]);
g('node_x')=[73 737 381 391]; g('node_y')=[283 337 458 142];
g('node_color')=[3 3 3 11];
g('node_diam')=[30 30 30 60];
g('edge_color')=[10 0 2 6 11 11 0 0 11];
rep=[2 2 1 1 2 2 2 2 2 2 2 2 2];
rep1=[100 -400 650 300];
xbasc(); plot_graph(g,rep,rep1);
rep=[2 1 1 1 2 2 2 2 2 2 2 2 2];
x_message('Represente le graphe avec differents parametres');
xbasc(); plot_graph(g,rep,rep1);
// Affichage avec une boîte de dialogue
xbasc(); plot_graph(g);
xset("thickness",4);
xbasc();
plot_graph(g);

See Also

show_graph ,


predecessors

Scilab function
Last update : 16/06/2004

predecessors - sommets origines des arcs entrants d'un sommet donné

Calling Sequence

a = predecessors(i,g)

Parameters

  • i : entier
  • g : graphe (liste)
  • a : vecteur ligne d'entiers

Description

predecessors renvoie le vecteur ligne des numéros des sommets origines des arcs entrants d'un sommet donné i pour un graphe orienté g .

Examples

ta=[1  6  2  4  7  5  6  8  4  3  5 1];
he=[2  1  3  6  4  8  8  7  2  7  3 5];
g=make_graph('foo',1,8,ta,he);
g('node_x')=[285  284  335  160  405  189  118  45];
g('node_y')=[266  179   83  176  368  252  64  309];
show_graph(g);
a=predecessors(8,g)
show_nodes(a);

See Also

neighbors , successors ,


qassign

Scilab function
Last update : 16/06/2004

qassign - résout un problème d'affectation quadratique

Calling Sequence

[crit,order] = qassign(c,f,d)

Parameters

  • c : matrice réelle
  • f : matrice réelle
  • d : matrice réelle
  • crit : scalaire
  • order : vecteur ligne d'entiers

Description

qassign résout un problème d'affectation quadratique i.e. minimiser le critère global : crit = e(1)+...+e(n) where e(i) = c(i,l(i))+ fd(i) where fd(i) = f(i,1)*d(l(i),l(1))+...+f(i,n)*d(l(i),l(n))

c , f et d sont des matrices n x n; leurs termes diagonaux sont nuls.

Examples

n=15;
d=100*rand(15,15);
d=d-diag(diag(d));
c=zeros(n,n);f=c;
f(2:n,1)=ones(1:n-1)';
[crit,order]=qassign(c,f,d)

See Also

knapsack ,


salesman

Scilab function
Last update : 16/06/2004

salesman - résout le problème du voyageur de commerce

Calling Sequence

cir = salesman(g,[nstac])

Parameters

  • g : graphe (liste)
  • nstac : entier
  • cir : vecteur ligne d'entiers

Description

salesman résout le problème du voyageur de commerce. g est un graphe orienté; nstac est un entier optionnel qui est une borne sur la mémoire allouée pour résoudre ce problème. Sa valeur est 100*n*n par défaut où n est le nombre de sommets.

Examples

ta=[2  1 3 2 2 4 4 5 6 7 8 8 9 10 10 10 10 11 12 13 13 14 15 16 16 17 17];
he=[1 10 2 5 7 3 2 4 5 8 6 9 7 7 11 13 15 12 13  9 14 11 16 1 17 14 15];
g=make_graph('foo',0,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
g('node_diam')=[1:(g('node_number'))]+20;
show_graph(g);
g1=make_graph('foo1',1,17,[ta he],[he ta]);
m=arc_number(g1);
g1('edge_length')=5+round(30*rand(1,m));
cir = salesman(g1);
ii=find(cir > edge_number(g));
if(ii <> []) then cir(ii)=cir(ii)-edge_number(g);end;
show_arcs(cir);


save_graph

Scilab function
Last update : 16/06/2004

save_graph - sauve un graphe

Calling Sequence

save_graph(g,chemin)

Parameters

  • g : graphe (liste)
  • chemin : chaîne de caractères, nom de fichier

Description

save_graph sauve le graphe g dans un fichier. chemin est le nom du fichier où le graphe est sauvé. chemin peut être le nom du fichier ou le nom d'un répertoire; si l'extension "graph" est omise dans name , elle est ajoutée. Si chemin est le nom d'un répertoire, le nom du graphe est utilisé comme nom de fichier.

Examples

g=load_graph(SCI+'/demos/metanet/mesh100');
show_graph(g);
if MSDOS then
  unix('del mymesh100.graph');
else
  unix('rm -f mymesh100.graph');
end
save_graph(g,'mymesh100.graph');
g=load_graph('mymesh100');
show_graph(g,'new');

See Also

load_graph ,


shortest_path

Scilab function
Last update : 19/12/2005

shortest_path - chemin le plus court

Calling Sequence

[p,lp] = shortest_path(i,j,g,[typ])

Parameters

  • i : entier, numéro du sommet de départ
  • j : entier, numéro du sommet d'arrivée
  • g : graphe (liste)
  • typ : chaîne de caractères, type du chemin le plus court
  • p : vecteur ligne des numéros des arcs du chemin s'il existe
  • lp : longueur du chemin

Description

shortest_path renvoie le chemin le plus court p du sommet i au sommet j s'il existe, et le vecteur vide [] sinon. L'argument optionnel typ est une chaîne définissant le type du chemin, 'arc' pour le chemin le plus court par rapport au nombre d'arcs et 'length' pour le chemin le plus court par rapport à la longueur des arêtes edge_length .

Pour le chemin le plus court par rapport à la longueur des arêtes, les longueurs sont données par les éléments edge_length du graphe. Si cette valeur n'est pas donnée (vecteur vide [] ), elle est supposée nulle sur chaque arête. Les longueurs peuvent être positives ou négatives (ou nulles).

Quand le chemin le plus court existe, lp est la longueur du chemin.

Examples

ta=[1 1 2 2 2 3 4 4 5 6 6 6 7 7 7 8 9 10 12 12 13 13 13 14 15 14 9 11 10];
he=[2 6 3 4 5 1 3 5 1 7 10 11 5 8 9 5 8 11 10 11 9 11 15 13 14 4 6 9 1];
g=make_graph('foo',1,15,ta,he);
g('node_x')=[194 191 106 194 296 305 305 418 422 432 552 550 549 416 548];
g('node_y')=[56 181 276 278 276 103 174 281 177 86 175 90 290 397 399];
show_graph(g);
g1=g;ma=prod(size(g1('head')));
rand('uniform');
g1('edge_length')=int(20*rand(1,ma));
[p,lp]=shortest_path(13,1,g1,'length');
p
x_message(['Voici le chemin le plus court';
           'Le nom des arcs peut être visualisé en selectionnant la valeur ""Name"" pour les arcs';
           'dans le menu Graph->Options.']);
g1('edge_name')=string(g1('edge_length'));
edgecolor=ones(1:ma);edgecolor(p)=11*ones(p);
g1('edge_color')=edgecolor;
edgefontsize=12*ones(1,ma);edgefontsize(p)=18*ones(p);
g1('edge_font_size')=edgefontsize;
show_graph(g1);

See Also

find_path , nodes_2_path ,


show_arcs

Scilab function
Last update : 12/01/2004

show_arcs - highlights a set of arcs

Calling Sequence

show_arcs(p,[sup])

Parameters

  • p : row vector of arc numbers (directed graph) or edge numbers (undirected graph)
  • sup : string, superposition flag

Description

show_arcs highlights the set of arcs or edges p of the displayed graph in the current edit_graph window. If the optional argument sup is equal to the string 'sup', the highlighting is superposed on the previous one.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
t=min_weight_tree(1,g); g1=g; ma=edge_number(g1);
edgecolor=1*ones(1,ma); g1('edge_color')=edgecolor;
edgewidth=1*ones(1,ma); edgewidth(t)=4*ones(t); g1('edge_width')=edgewidth;
for i=8:12,
 edgecolor(t)=i*ones(t); g1('edge_color')=edgecolor;
 xpause(3d5); show_graph(g1);
 show_arcs(t);
end;

See Also

edit_graph , show_nodes , netwindow , netwindows ,


show_graph

Scilab function
Last update : 12/01/2004

show_graph - displays a graph

Calling Sequence

nw = show_graph(g,[smode,scale])
nw = show_graph(g,[scale,winsize])

Parameters

  • g : graph list
  • smode : string, mode value
  • winsize : row vector defining the size of edit_graph window
  • scale : real value, scale factor
  • nw : integer

Description

show_graph displays the graph g in the current edit_graph window. If there is no current edit_graph window, a edit_graph window is created. The return value nw is the number of the edit_graph window where the graph is displayed.

If the optional argument smode is equal to the string 'rep' or is not given and if there is already a graph displayed in the current edit_graph window, the new graph is displayed instead.

If the optional argument smode is equal to the string 'new', a new edit_graph window is created. In this case, if the optional argument winsize is given as a row vector [width height] , it is the size in pixels of edit_graph window. The default is [600,400] .

The optional argument scale is the value of the scale factor when drawing the graph. The default value is 1.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g,2);
show_graph(g,0.5);
show_graph(g,1);

See Also

edit_graph , netwindow , netwindows ,


show_nodes

Scilab function
Last update : 12/01/2004

show_nodes - highlights a set of nodes

Calling Sequence

show_nodes(nodes,[sup])

Parameters

  • nodes : row vector of node numbers
  • sup : string, superposition flag

Description

show_nodes highlights the set of nodes nodes of the displayed graph in the current edit_graph window. If the optional argument sup is equal to the string 'sup', the highlighting is superposed on the previous one.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
for i=2:3:g('node_number'), show_nodes([i]); end;
for i=1:3:g('node_number'), show_nodes([i],'sup'); end;

See Also

edit_graph , show_arcs , netwindow , netwindows ,


split_edge

Scilab function
Last update : 16/06/2004

split_edge - divise une arête en insérant un sommet

Calling Sequence

g1 = split_edge(i,j,g,name)

Parameters

  • i : entier, numéro du sommet origine
  • j : entier, numéro du sommet extrémité
  • g : graphe (liste)
  • name : nom optionnel du sommet ajouté
  • g1 : nouveau graphe (liste)

Description

split_edge renvoie le graphe g1 , l'arête allant du sommet i au sommet j ayant été divisée : un nouveau sommet est créé au milieu de ces deux sommets. Ce nouveau sommet est connecté aux sommets i et j . Si name est donné, il définit le nom du nouveau sommet, sinon le nombre total de sommets plus 1 est pris comme nouveau nom.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 13 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
show_graph(g);
gt=split_edge(1,2,g);
show_graph(gt,'new');

See Also

add_edge , add_node , delete_arcs , delete_nodes ,


strong_connex

Scilab function
Last update : 16/06/2004

strong_connex - composantes fortement connexes

Calling Sequence

[nc,ncomp] = strong_connex(g)

Parameters

  • g : graphe (liste)
  • nc : entier, nombre de composantes fortement connexes
  • ncomp : vecteur ligne des composantes fortement connexes

Description

strong_connex renvoie le nombre nc de composantes fortement connexes pour le graphe g et un vecteur ligne ncomp donnant le nombre de composantes fortement connexes pour chaque sommet. Par exemple, si i est un numéro de sommet, ncomp(i) est le numéro de la composante fortement connexe à laquelle le sommet i appartient.

Examples

ta=[1 1 2 2 2 3 4 4 5 6 6 6 7 7 7 8 9 10 12 12 13 13 13 14 15];
he=[2 6 3 4 5 1 3 5 1 7 10 11 5 8 9 5 8 11 10 11 9 11 15 13 14];
g=make_graph('foo',1,15,ta,he);
g('node_x')=[197 191 106 194 296 305 305 418 422 432 552 550 549 416 548];
g('node_y')=[76 181 276 278 276 83 174 281 177 86 175 90 290 397 399];
show_graph(g);
[nc,ncomp]=strong_connex(g);
g1=g; g1('node_color')=8+ncomp; g1('node_diam')=10+5*ncomp;
x_message('Composante fortement connexe du graphe');
show_graph(g1);

See Also

connex , con_nodes , strong_con_nodes ,


strong_con_nodes

Scilab function
Last update : 16/06/2004

strong_con_nodes - ensemble de sommets d'une composante fortement connexe

Calling Sequence

ns = strong_con_nodes(i,g)

Parameters

  • i : entier, numéro de la composante fortement connexe
  • g : graphe (liste)
  • ns : vecteur ligne, numéros des sommets de la composante fortement connexe

Description

strong_con_nodes renvoie le vecteur ligne ns des numéros des sommets appartenant à la composante fortement connexe numéro i .

Examples

ta=[1 1 2 2 2 3 4 4 5 6 6 6 7 7 7 8 9 10 12 12 13 13 13 14 15];
he=[2 6 3 4 5 1 3 5 1 7 10 11 5 8 9 5 8 11 10 11 9 11 15 13 14];
g=make_graph('foo',1,15,ta,he);
g('node_x')=[197 191 106 194 296 305 305 418 422 432 552 550 549 416 548];
g('node_y')=[76 181 276 278 276 83 174 281 177 86 175 90 290 397 399];
show_graph(g);
ncomp=strong_con_nodes(3,g);
n=g('node_number');
nodecolor=0*ones(1,n); nodecolor(ncomp)=11*ones(ncomp);
g('node_color')=nodecolor;
nodediam=20*ones(1,n); nodediam(ncomp)=40*ones(ncomp);
g('node_diam')=nodediam;
x_message('Ensemble des sommets de la composante fortement connexe numéro 3');
show_graph(g);

See Also

connex , con_nodes , strong_connex ,


subgraph

Scilab function
Last update : 16/06/2004

subgraph - sous-graphe d'un graphe

Calling Sequence

g1 = subgraph(v,ind,g)

Parameters

  • v : vecteur ligne, numéros des sommets ou arêtes
  • ind : chaîne de caractères, 'nodes' ou 'edges'
  • g : graphe (liste)
  • g1 : nouveau graphe (liste)

Description

subgraph renvoie le graphe g1 , construit avec les numéros donnés par le vecteur ligne v . Si ind est la chaîne de caractères 'nodes' , g1 est construit avec les numéros de sommets donnés par v et les arêtes connectées à ces sommets dans g . Si ind est la chaîne de caractères 'edges' , g1 est construit avec les numéros d'arêtes donnés par v et les sommets origines et extrémités de ces arêtes dans g .

Toutes les caractéristiques des anciens sommets et arêtes de g sont préservées.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 13 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
g('edge_color')=modulo([1:(edge_number(g))],15)+1;
g('node_diam')=[1:(g('node_number'))]+20;
show_graph(g);
v=[2 3 4 5 17 13 10];
show_nodes(v);
g1=subgraph(v,'nodes',g);
show_graph(g1);
v=[10 13 12 16 20 19];
show_graph(g);
show_arcs(v);
g1=subgraph(v,'edges',g);
show_graph(g1);

See Also

add_edge , add_node , delete_arcs , delete_nodes , supernode ,


successors

Scilab function
Last update : 16/06/2004

successors - sommets extrémités des arcs sortant d'un sommet donné

Calling Sequence

a = successors(i,g)

Parameters

  • i : entier
  • g : graphe (liste)
  • a : vecteur ligne d'entiers

Description

successors renvoie le vecteur ligne des numéros des sommets extrémités des arcs sortants du sommet i pour un graphe orienté g .

Examples

ta=[1  6  2  4  7  5  6  8  4  3  5  1];
he=[2  1  3  6  4  8  8  7  2  7  3  5];
g=make_graph('foo',1,8,ta,he);
g('node_x')=[285  284  335  160  405  189  118  45];
g('node_y')=[266  179   83  176  368  252  64  309];
show_graph(g);
a=successors(6,g)
show_nodes(a);

See Also

neighbors , predecessors ,


supernode

Scilab function
Last update : 16/06/2004

supernode - remplace un groupe de sommets par un super-sommet

Calling Sequence

g1 = supernode(v,g)

Parameters

  • v : vecteur ligne, numéros des sommets
  • g : graphe (liste)
  • g1 : nouveau graphe (liste)

Description

supernode renvoie le graphe g1 avec les sommets de numéros donnés par le vecteur v contractés en un seul sommet. Le numéro du super-sommet est le plus petit numéro de v . Les caractéristiques des anciens sommets et arêtes sont conservées. Le super-sommet est positionné au barycentre des sommets de v . Le diamètre et l'épaisseur du super-sommet sont le double de ceux du sommet remplacé.

La demande du nouveau sommet, si elle est définie, est la somme des demandes des sommets contractés.

Examples

ta=[1 1 2 2 2 3 4 5 5 7 8 8 9 10 10 10 10 10 11 12 13 13 13 14 15 16 16 17 17];
he=[2 10 3 5 7 4 2 4 6 8 6 9 7 7 11 13 13 15 12 13 9 10 14 11 16 1 17 14 15];
g=make_graph('foo',1,17,ta,he);
g('node_x')=[283 163 63 57 164 164 273 271 339 384 504 513 439 623 631 757 642];
g('node_y')=[59 133 223 318 227 319 221 324 432 141 209 319 428 443 187 151 301];
g('edge_color')=modulo([1:(edge_number(g))],15)+1;
g('node_diam')=[1:(g('node_number'))]+20;
show_graph(g);
v=[7 10 13 9];
show_nodes(v);
g1=supernode(v,g);
show_graph(g1,'new');

See Also

add_edge , add_node , delete_arcs , delete_nodes ,


trans_closure

Scilab function
Last update : 16/06/2004

trans_closure - fermeture transitive

Calling Sequence

g1 = trans_closure(g)

Parameters

  • g : graphe (liste)
  • g1 : nouveau graphe (liste)

Description

trans_closure renvoie sous forme d'un nouveau graphe g1 la fermeture transitive du graphe g . Ce graphe doit être orienté et connecté. Si <name> est le nom du graphe g , <name>_trans_closure est le nom de la fermeture transitive.

Examples

ta=[2 3 3 5 3 4 4 5 8];
he=[1 2 4 2 6 6 7 7 4];
g=make_graph('foo',1,8,ta,he);
g('node_x')=[129 200 283 281 128 366 122 333];
g('node_y')=[61 125 129 189 173 135 236 249];
show_graph(g);
g1=trans_closure(g);
vv=1*ones(ta); aa=sparse([ta' he'],vv');
ta1=g1('tail'); he1=g1('head');
ww=1*ones(ta1); bb=sparse([ta1' he1'],ww');
dif=bb-aa; lim=size(ta1); edgecolor=0*ones(ta1);
for i=1:lim(2)
 if dif(ta1(i),he1(i))==1 then edgecolor(i)=11; end;
end;
g1('edge_color')=edgecolor;
x_message('Fermeture transitive du graphe');
show_graph(g1);


Manipulation de fichiers sons
analyze - frequency plot of a sound signal
auread - load .au sound file
auwrite - writes .au sound file
beep - Produit le son "beep"
lin2mu - linear signal to mu-law encoding
loadwave - load a sound wav file into scilab
mapsound - Plots a sound map
mcisendstring - sends a command string to an MCI device (Windows only).
mu2lin - mu-law encoding to linear signal
playsnd - sound player facility
savewave - save data into a sound wav file.
sound - sound player facility
soundsec - generates n sampled seconds of time parameter
wavread - load .wav sound file
wavwrite - writes .wav sound file


analyze

Scilab Function
Last update : 12/01/2004

analyze - frequency plot of a sound signal

Parameters

  • fmin,fmax,rate,points : scalars. default values fmin=100,fmax=1500,rate=22050,points=8192;

Description

Make a frequency plot of the signal w with sampling rate rate . The data must be at least points long. The maximal frequency plotted will be fmax , the minimal fmin .

Examples

// At first we create 0.5 seconds of sound parameters.
t=soundsec(0.5);
// Then we generate the sound.
s=sin(440*t)+sin(220*t)/2+sin(880*t)/2;
[nr,nc]=size(t);
s(nc/2:nc)=sin(330*t(nc/2:nc));
analyze(s);


auread

Scilab Function
Last update : 12/01/2004

auread - load .au sound file

Calling Sequence

y=auread(aufile)
y=auread(aufile,ext)
[y,Fs,bits]=auread(aufile)
[y,Fs,bits]=auread(aufile,ext)

Parameters

  • aufile : string (The .au extension is appended if no extension is given)
  • Fs ...
  • [] : integer, frequency sampling in Hz.
  • ext : string ( 'size' or 'snd' ) or integer (to read n samples) or 1 x 2 integer vector [n1,n2] (to read from n1 to n2).

Description

Utility function to read .au sound file. auread(aufile) loads a sound file specified by the string aufile, returning the sampled data in y. Amplitude values are in the range [-1,+1].

Supports multi-channel data in the following formats: 8-bit mu-law, 8-, 16-, and 32-bit linear, and floating point.

[y,Fs,bits]=auread(aufile) returns the sample rate (Fs) in Hertz and the number of bits per sample used to encode the data in the file.

auread(aufile,n) returns the first n samples from each channel.

auread(aufile,[n1,n2]) returns samples n1 to n2.

auread(aufile,'size') returns the size of the audio data contained in the file in place of the actual audio data, returning the vector as [samples channels].

auread(aufile,'snd') returns information about the sample and data as a tlist.

See Also

savewave , analyze , mapsound ,


auwrite

Scilab Function
Last update : 12/01/2004

auwrite - writes .au sound file

Calling Sequence

auwrite(y,aufile)
auwrite(y,Fs,aufile)
auwrite(y,Fs,bits,aufile)
auwrite(y,Fs,bits,method,aufile)

Parameters

  • y : real vector or matrix with entries in [-1,1].
  • aufile : string (The .au extension is appended if no extension is given)
  • Fs : integer, frequency sampling in Hz.
  • bits : integer, number of bits in the encoding.
  • method : string , 'mu' (default) or 'linear' , encoding method.

Description

Utility function to save .au sound file. auwrite(y,aufile) writes a sound file specified by the string aufile. The data should be arranged with one channel per column. Amplitude values outside the range [-1,+1] are ignored. Supports multi-channel data for 8-bit mu-law, and 8- and 16-bit linear formats.

auwrite(y,Fs,aufile) specifies in Fs the sample rate of the data in Hertz.

auwrite(y,Fs,bits,aufile) selects the number of bits in the encoder. Allowable settings are bits=8 and bits=16. auwrite(y,Fs,bits,method,aufile) allows selection of the encoding method, which can be either 'mu' or 'linear'. Note that mu-law files must be 8-bit. By default, method='mu'.

See Also

auread , wavread , savewave , analyze , mapsound ,


beep

Fonction Scilab
Last update : 08/06/2005

beep - Produit le son "beep"

Calling Sequence

beep();
beep('on')
beep('off')
s=beep()

Description

beep() produit le son "beep".

beep('on') active le "beep"

beep('off') desactive le "beep"

s=beep() retourne le mode courantreturns the current beep mode (on or off).

Authors

A.C


lin2mu

Scilab Function
Last update : 12/01/2004

lin2mu - linear signal to mu-law encoding

Calling Sequence

mu=lin2mu(y)

Parameters

  • y : real vector
  • mu : real vector

Description

Utility fct: converts linear signal to mu-law encoding. mu = lin2mu(y) converts linear audio signal amplitudes in the range -1 <= y <= 1 to mu-law in the range 0 <= mu <= 255.

See Also

mu2lin ,


loadwave

Scilab Function
Last update : 02/09/2005

loadwave - load a sound wav file into scilab

Calling Sequence

x=loadwave(filename);
[x,y]=loadwave(filename);

Parameters

  • filename : a string. The path of the wav file to be loaded
  • x : a matrix one line for each channel
  • y : vector

Description

Reads a .wav sound file into Scilab as a matrix. If y is given, it is filled with information about the samples (See the message sent by loadwave ).

Examples

// At first we create 0.5 seconds of sound parameters.
t=soundsec(0.5);
// Then we generate the sound: a two channels sound.
s=[sin(2*%pi*440*t);sin(2*%pi*350*t)];
savewave(TMPDIR+'/foo.wav',s);
s1=loadwave(TMPDIR+'/foo.wav');
max(abs(s1-s))

See Also

savewave , analyze , mapsound ,


mapsound

Scilab Function
Last update : 12/01/2004

mapsound - Plots a sound map

Calling Sequence

mapsound (w,dt,fmin,fmax,simpl,rate)

Parameters

  • dt,fmin,fmax,simpl,rate : scalars. default values dt=0.1,fmin=100,fmax=1500,simpl=1,rate=22050;

Description

Plots a sound map for a sound. It does FFT at time increments dt. rate is the sampling rate. simpl points are collected for speed reasons. fmin and fmax are used for graphic boundaries.

Examples

// At first we create 0.5 seconds of sound parameters.
t=soundsec(0.5);
// Then we generate the sound.
s=sin(440*t)+sin(220*t)/2+sin(880*t)/2;
[nr,nc]=size(t);
s(nc/2:nc)=sin(330*t(nc/2:nc));
mapsound(s);


mcisendstring

Scilab Function
Last update : 08/06/2005

mcisendstring - sends a command string to an MCI device (Windows only).

Calling Sequence

mcisendstring(mcistring)
bOK=mcisendstring(mcistring)
[bOK,CodeError]=mcisendstring(mcistring)
[bOK,CodeError,StringError]=mcisendstring(mcistring)

Parameters

  • mcistring : a command string to send to an MCI device
  • bOK : returns %T or %F
  • CodeError : returns error code (0 --> if bOK == %T)
  • StringError : returns MCI interpreter message ('OK' --> if bOK == %T)

Description

The mciSendString primitive sends a command string to an MCI device. The device that the command is sent to is specified in the command string.

see on http://msdn.microsoft.com/library/default.asp and search "Windows Multimedia SDK open"

Examples

mcisendstring("open ""d:\audio.mp3"" type MPEGVideo alias MP3_Device")
mcisendstring("play MP3_Device")
mcisendstring("close MP3_Device")

mcisendstring("open ""d:\video.avi"" type avivideo alias AVI_Device")
mcisendstring("play AVI_Device from 0")
mcisendstring("close AVI_Device")

Author

Allan Cornet


mu2lin

Scilab Function
Last update : 12/01/2004

mu2lin - mu-law encoding to linear signal

Calling Sequence

mu=lin2mu(y)

Parameters

  • y : real vector
  • mu : real vector

Description

Utility fct: y=mu2lin(mu) converts mu-law encoded 8-bit audio signals, stored in the range 0 <= mu <= 255, to linear signal amplitude in the range -s < y < s where s = 32124/32768 ~= .9803. The input mu is often obtained using mget(...,'uc') to read byte-encoded audio files. Translation of C program by Craig Reese: IDA/Supercomputing Research Center Joe Campbell: Department of Defense

See Also

mu2lin ,


playsnd

Scilab Function
Last update : 31/03/2004

playsnd - sound player facility

Calling Sequence

[]=playsnd(y)
[]=playsnd(y,fs,bits)

Parameters

  • y : real vector
  • fs : real number, sampling frequency. Unused yet.
  • bits : real number, number of bits (usually 8 or 16). Unused yet.

Description

Redirects a linear signal to /dev/audio/ .

Examples

  y=wavread('SCI/demos/signal/sound/chimes.wav');
  playsnd(y)

See Also

lin2mu , wavread ,


savewave

Scilab Function
Last update : 02/09/2005

savewave - save data into a sound wav file.

Calling Sequence

savewave(filename,x [, rate ]);

Parameters

  • filename : a string. The path of the output wav file
  • x : vector
  • rate : a scalar. 22050 is the default value.

Description

save x into a wav sound file. you can transform other sound files into wav file with the sox program.

Examples

// At first we create 0.5 seconds of sound parameters.
t=soundsec(0.5);
// Then we generate the sound.
s=sin(440*t)+sin(220*t)/2+sin(880*t)/2;
[nr,nc]=size(t);
s(nc/2:nc)=sin(330*t(nc/2:nc));
savewave(TMPDIR+'/foo.wav',s);

See Also

loadwave , analyze , mapsound ,


soundsec

Scilab Function
Last update : 06/01/2006

soundsec - generates n sampled seconds of time parameter

Calling Sequence

t=soundsec(n [,rate])

Parameters

  • n : an integer, the number of seconds to generate.
  • rate : an integer, the number of samples per second.

Description

generates a vector coding time from 0 to n seconds at sampled rate rate .

Examples

// At first we create 0.5 seconds of sound parameters.
t=soundsec(0.5);
// Then we generate the sound.
s=sin(2*%pi*440*t);
analyze(s,200,600,22050);

See Also

playsnd , analyze ,


sound

Scilab Function
Last update : 12/01/2004

sound - sound player facility

Calling Sequence

sound(y)
sound(y,fs)
sound(y,fs,bits)

Parameters

  • y : real vector
  • fs : real number, sampling frequency
  • bits : real number, number of bits (usually 8 or 16)

Description

sound(y,fs) sends the signal in vector y (with sample frequency fs) out to the speaker. Values in y are assumed to be in the range -1.0 <= y <= 1.0. Values outside that range are ugnored. Stereo sounds are played, on platforms that support it, when y is an N-by-2 matrix. sound(y) plays the sound at the default sample rate of 8192 Hz. sound(y,fs,nbits) plays the sound using nbits bits/sample if possible. Most platforms support bits=8 or 16.

See Also

playsnd ,


wavread

Scilab Function
Last update : 17/12/2004

wavread - load .wav sound file

Calling Sequence

y=wavread(wavfile)
y=wavread(wavfile,ext)
[y,Fs,bits]=wavread(wavfile)
[y,Fs,bits]=wavread(wavfile,ext)

Parameters

  • wavfile : string (The .wav extension is appended if no extension is given)
  • Fs : integer, frequency sampling in Hz.
  • ext : string ( 'size' ) or integer (to read n samples) or 1 x 2 integer vector [n1,n2] (to read from n1 to n2).

Description

Utility function to read .wav sound file. wavread(wavfile) loads a sound file specified by the string wavfile, returning the sampled data in y. Amplitude values are in the range [-1,+1]. Supports multi-channel data in the following formats: 8-bit mu-law, 8-, 16-, and 32-bit linear, and floating point.

[y,Fs,bits]=wavread(wavfile) returns the sample rate (Fs) in Hertz and the number of bits per sample used to encode the data in the file.

wavread(wavfile,n) returns the first n samples from each channel.

wavread(wavfile,[n1,n2]) returns samples n1 to n2.

read(wavfile,'size') returns the size of the audio data contained in the file in place of the actual audio data, returning the vector as [samples channels].

Examples

  wavread('SCI/demos/signal/sound/chimes.wav','size')

  [y,Fs,bits]=wavread('SCI/demos/signal/sound/chimes.wav');Fs,bits
  subplot(2,1,1)
  plot2d(y(:,1))
  subplot(2,1,2)
  plot2d(y(:,2))

  y=wavread('SCI/demos/signal/sound/chimes.wav',[1 5]) //the first five samples

See Also

auread , savewave , analyze , mapsound ,


wavwrite

Scilab Function
Last update : 19/10/2005

wavwrite - writes .wav sound file

Calling Sequence

wavwrite(y,wavfile)
wavwrite(y,Fs,wavfile)

Parameters

  • y : real vector or matrix with entries in [-1,1].
  • wavfile : string (The .wav extension is appended if no extension is given)
  • Fs : integer, frequency sampling in Hz.

Description

Utility function to save .wav sound file. wavwrite(y,wavfile) writes a sound file specified by the string wavfile. The data should be arranged with one channel per column. Amplitude values outside the range [-1,+1] are ignored.

wavwrite(y,Fs,wavfile) specifies in Fs the sample rate of the data in Hertz.

Examples

  A=matrix(1:6,2,3);
  wavwrite(A/6,TMPDIR+'/foo.wav');
  B=wavread(TMPDIR+'/foo.wav');
  maxi(abs(A- round(B*6)))

See Also

auread , wavread , savewave , analyze , mapsound ,


Génération de code, traduction de données
ascii - string ascii conversions
excel2sci - reads ascii Excel files
formatman - translates old NROFF man files in a directory into ascii, tex, html or xml
fun2string - generates ascii definition of a scilab function
mfile2sci - Fonction de conversion de M-file Matlab vers Scilab
pol2tex - convert polynomial to TeX format
sci2for - scilab function to Fortran routine conversion
texprint - TeX output of Scilab object
translatepaths - convertit un ensemble de répertoires contenant des M-files vers Scilab
tree2code - genère le code ASCII d'une fonction Scilab


ascii

Scilab Function
Last update : 12/01/2004

ascii - string ascii conversions

Calling Sequence

a=ascii(txt)
txt=ascii(a)

Parameters

  • txt : character string or matrix of strings.
  • a : vector of integer ascii codes

Description

This function convert Scilab string to a vector of ascii code or vector of ascii code to Scilab strings.

If txt is a matrix of string, ascii(txt) is equivalent to ascii(strcat(txt))

See Also

code2str , str2code ,


excel2sci

Scilab Function
Last update : 12/01/2004

excel2sci - reads ascii Excel files

Calling Sequence

M=excel2sci(fname [,sep])

Parameters

  • fname : character string. The file path
  • sep : character string. Excel separator used, default value is ","
  • M : matrix of strings

Description

Given an ascii file created by Excel using "Text and comma" format exel2sci(fname) returns the corresponding Scilab matrix of strings. Use exel2sci(fname,sep ) for an other choice of separator.

Note: You may eval all or part ot M using function evstr .

See Also

read , evstr ,


formatman

Scilab Function
Last update : 12/01/2004

formatman - translates old NROFF man files in a directory into ascii, tex, html or xml

Calling Sequence

formatman(path [,to])

Parameters

  • path : character string, giving the path of the directory
  • to : character string with possible values "ascii", "tex", "html", "xml"

Description

This function, not yet fully checked, formats old help files (*.man) of a given directory, written in a subset of NROFF, to ascii, tex, html or xml.

NOTE: this function is obsolete and MUST ONLY be used to translate old NROFF help files into new XML help files.

Known NROFF directives are .TH, .SH, .TP, .RS, .RE, .LP, .IG, .nf, .fi, .TS, .TE, .ft, .IP

Font handling like

, , , , ,  ]

are ignored

asciimode generates a .cat file for each .man file and a whatis file
texmode generates a .tex file for each .man file and a whatis.tex file
htmlmode generates a .html file for each .man file and a index.html file
xmlmode generates a .xml file for each .man file

See Also

help , man ,


fun2string

Scilab Function
Last update : 10/05/2005

fun2string - generates ascii definition of a scilab function

Calling Sequence

txt=fun2string(fun,name)

Parameters

  • fun : a function type variable
  • name : a character string, the generated function name
  • txt : a column vector of strings, the text giving the scilab instructions

Description

Given a loaded Scilab function pseudo-code fun2string allow to re-generate the the code. The generated code is indented and beautified.

The mechanism is similar, but simpler than the mfile2sci one. It may be adapted for syntax translations.

Examples

txt=fun2string(asinh,'foo');
write(%io(2),txt,'(a)')

See Also

getf , edit , macrovar ,


mfile2sci

Fonction Scilab
Last update : 30/03/2004

mfile2sci - Fonction de conversion de M-file Matlab vers Scilab

Calling Sequence

mfile2sci(M-file-path [,result-path [,Recmode [,only-double [,verbose-mode [,prettyprint]]]]])

Parameters

  • M-file-path : une chaîne de caractères qui donne le chemin du M-file à traduire
  • result-path : une chaîne de caractères qui donne le répertoire où le résultat sera écrit. La valeur par défault est le répetoire courant.
  • Recmode : Flag booléen, utilisé par translatepaths pour une conversion récursive. Doit être %F pour convertir un seul M-file. Valeur par défaut : %F
  • only-double : Flag booléen, si il vaut %T mfile2sci considère que les fonctions de calcul numériques ont été utilisées uniquement avec des données numériques (Aucune fonction de surcharge Scilab est requise). Valeur par défaut : %F
  • verbose-mode : mode d'affichage des information de conversion
    • 0 : aucune information donnée
    • 1 : les ionformations sont écrites comme commentaires du fichier Scilab
    • 2 : les ionformations sont écrites comme commentaires du fichier Scilab et dans le fichier log
    • 3 : les ionformations sont écrites comme commentaires du fichier Scilab, dans le fichier log et affichées dans la fenêtre Scilab (Valeur par défaut).
  • prettyprint : Flag booléen, si il vaut %T le code généré est réarrangé. Valeur par défaut : %F

Description

M2SCI (et en particulier mfile2sci) est un ensemble d'outils de conversion de M-file vers Scilab. Il essaie à chaque fois que c'est possible de remplacer l'appel à une fonction Matlab par la primitive ou la fonction Scilab équivalente.

Pour convertir un M-file, entrer l'instruction Scilab : mfile2sci(fichier)

où fichier est une chaîne de caractère qui donne le chemin du M-file. mfile2sci va générer trois fichiers dans le même répertoire :

<function-name>.sci: l'équivalent Scilab pour le M-file
<function-name>.cat: le fichier d'aide Scilab associé à la fonction
sci_<function-name>.sci: la fonction Scilab requise pour convertir les appels à ce M-file dans d'autres M-files. Cette fonction peut être améliorée "à la main". Cette fonction est utile uniquement pour la conversion, pas pour utiliser la fonction convertie.

Des fonctions comme eye, ones, size, sum,... se comportent différemment selon la dimension de leurs arguments. Quand mfile2sci ne peut pas inférer les dimensions, il remplace ces fonctions par un appel à une fonction d'émulation nommée mtlb_<function_name>. Pour une meilleure éfficacité, ces fonctions peuvent être remplacées par les instructions Scilab équivalentes. Pour avoir des informations sur le remplacement, entrer : help mtlb_<function_name> dans la fenêtre de commande Scilab.

D'autres fonctions comme plot, n'ont pas d'équivalent direct en Scilab. Elles sont aussi remplacées par des fonctions d'émulation nommées : mtlb_<function_name>.

Quand la conversion peut être incorrecte ou améliorée, mfile2sci ajoute des commentaires qui commencent par "//!" (suivant verbose-mode).

Un appel à mfile2sci() sans rhs lance une interface graphique pour aider à la sélection d'un fichier/répertoire et des options.

Examples

// Création d'une fichier .m simple
write(TMPDIR+'/rot90.m',['function B = rot90(A,k)'
 '[m,n] = size(A);'
 'if nargin == 1'
 '    k = 1;'
 'else'
 '    k = rem(k,4);'
 '    if k < 0'
 '        k = k + 4;'
 '    end'
 'end'
 'if k == 1'
 '    A = A.'';'
 '    B = A(n:-1:1,:);'
 'elseif k == 2'
 '    B = A(m:-1:1,n:-1:1);'
 'elseif k == 3'
 '    B = A(m:-1:1,:);'
 '    B = B.'';'
 'else'
 '    B = A;'
 'end']);
// Conversion en Scilab
mfile2sci(TMPDIR+'/rot90.m',TMPDIR)
// Affichage du code
write(%io(2),read(TMPDIR+'/rot90.sci',-1,1,'(a)'))
// get it into scilab
getf(TMPDIR+'/rot90.sci')
// Exécution du code
m=rand(4,2);rot90(m,1)

See Also

translatepaths ,

Authors

V. Couvert
S. Steer


pol2tex

Scilab Function
Last update : 12/01/2004

pol2tex - convert polynomial to TeX format

Calling Sequence

[y]=pol2tex(x)

Parameters

  • x : polynomial
  • y : list

Description

Latex source code for the polynomial x . (For use with texprint )

Examples

s=poly(0,'s');
p=s^3+2*s-5;
pol2tex(p)

See Also

texprint ,


sci2for

Scilab Function
Last update : 12/01/2004

sci2for - scilab function to Fortran routine conversion

Calling Sequence

txt=sci2for(fun,nam,vtps [,lvtps])

Parameters

  • fun : Scilab function
  • nam : character string, the name of generated subroutine
  • vtps : list
  • lvtps : list
  • txt : string, text of the subroutine Fortran code

Description

The elements of the list vtps give the type and dimensions of the input variables of the calling sequence and lvtps optionally gives the type and dimensions of the output variables. This last parameter is usefull if type and/or dimension inference cannot be able to determine the desired values.

These lists are structured as described below:

vtps(i)=list(typ,row_dim,col_dim)

where :

typ: is a character string giving the type of the variable :
"0": constant,integer vector or matrix
"1": constant,double precision vector or matrix
"10": character string
row_dim: character string (row dimension)
col_dim: character string (column dimension)
txt: Fortran code

Generated code may use routines of scilab libraries and some others whose source code may be found in <SCIDIR>/util/sci2for.f

Remarks

This function is just a try. Only simple function may be translated. Many function calls have not yet Fortran equivalent, to add the translation of a new function call you may define a scilab function. whose name is f_<name of function>. see <SCIDIR>/macros/sci2for/f_*.sci files for examples.

The following keywords :

 work,iwork,ierr
 iw*  iiw*
 ilbN   (N integer)

may not appear in the function code.

See Also

function ,


texprint

Scilab Function
Last update : 12/01/2004

texprint - TeX output of Scilab object

Calling Sequence

[text]= texprint(a)

Parameters

  • a : Scilab object
  • text : list

Description

returns the Tex source code of the Scilab variable a . a is a matrix (constant, polynomial, rational) or a linear system ( syslin list).

Examples

s=poly(0,'s');
texprint([1/s,s^2])

See Also

pol2tex , pol2str ,


translatepaths

Fonction Scilab
Last update : 05/11/2004

translatepaths - convertit un ensemble de répertoires contenant des M-files vers Scilab

Calling Sequence

translatepaths(dirs_path [,res_path])

Parameters

  • dirs_path : un vecteur de chaînes de caractères qui donne les chemins des répertoires à convertir
  • res_path : une chaîne de caractère qui donne le chemin du répertoire où les fonctions Scilab seront écrites. Valeur par défaut : répertoire courant.

Description

translatepaths , convertit tous les M-files contenus dans un ensemble de répertoires en fonctions Scilab. Chaque fonction est convertie par mfile2sci .

Toutes les informations de traduction sont stockées dans un fichier nommé "log" dans le répertoire res_path .

Un appel à translatepaths() sans rhs lance une interface graphique pour aider à la sélection d'un fichier/répertoire et des options.

See Also

mfile2sci ,

Authors

V. Couvert
S. Steer


tree2code

Fonction Scilab
Last update : 12/05/2006

tree2code - genère le code ASCII d'une fonction Scilab

Calling Sequence

txt=tree2code(tree,prettyprint)

Parameters

  • tree : arbre représentant une macro (retourné par macr2tree)
  • prettyprint : booléen optionel
    • %T : le code généré est indenté et réarrangé
    • %F : le code est inchangé (valeur par défaut)
  • txt : vecteur colonne de chaînes de caractère, texte contenant les instructions Scilab

Description

A partir de l'arbre (retourné par macr2tree) d'une fonction Scilab chargée en mémoire, tree2code permet de regénérer le code de la fonction.

Examples

tree=macr2tree(cosh);
txt=tree2code(tree,%T);
write(%io(2),txt,'(a)');

See Also

macr2tree ,

Authors

V.C.


TdCs
artest - arnold dynamical system
bifish - shows a bifurcation diagram in a fish population discrete time model
boucle - phase portrait of a dynamical system with observer
chaintest - a three-species food chain model
gpeche - a fishing program
fusee - a set of Scilab macro for a landing rocket problem
lotest - demo of the Lorenz attractor
mine - a mining problem
obscont1 - a controlled-observed system
portr3d - 3 dimensional phase portrait.
portrait - 2 dimensional phase portrait.
recur - a bilinear recurrent equation
systems - a collection of dynamical system
tangent - linearization of a dynamical system at an equilibrium point
tdinit - interactive initialisation of the tdcs dynamical systems


artest

Scilab Function
Last update : 12/01/2004

artest - arnold dynamical system

Calling Sequence

artest(f_l,[odem,xdim,npts])
arnold(t,x)
iarf([a])

Parameters

  • f_l : can be "arnold" or arnold. It is the name of the external for the arnold system. If f_l is set to "arnold" a Fortran coded version of the arnold system where a(1:6)=1 will be used and if f_l is set to arnold a Scilab coded version will be used . arnold is a Scilab macro coding the Arnold system. This macro is loaded when calling artest .
  • iarf : is used to fix the values of a in the Scilab coded case. a is a vector of size 6.
  • odem,xdim,npts : are optional arguments. Their meaning and syntax can be found in the portr3d help

Description

A call to the function artest() will interactively display a phase portrait of a the following dynamical system :

      ydot(1)=a(1)*cos(y(2)) +a(2)*sin(y(3))
      ydot(2)=a(3)*cos(y(3)) +a(4)*sin(y(1))
      ydot(3)=a(5)*cos(y(1)) +a(6)*sin(y(2))

See Also

portr3d , ode , chaintest , lotest ,


bifish

Scilab Function
Last update : 12/01/2004

bifish - shows a bifurcation diagram in a fish population discrete time model

Calling Sequence

bifish([f_ch])

Parameters

  • f_ch : can be one of fish , fishr and fishr2 . This option selects the population model.

Description

The dynamical system fish is the following :

           y=b*exp(-0.1*(x(k)_1+x(k)_2));
           x(k+1)=[ y 2*y ; s 0.0]*x(k);

and the parameters s evolves to show the bifurcation diagram. fishr and fishr2 are constructed as above but with added white noises.

 fishr
 y=b*exp(-0.1*(xk(1)+xk(2)))
 xkp1=[ y 2*y ; s*(1+0.1*(rand()-0.5)) 0.0]*xk

 fishr2
 z=exp(-0.1*(xk(1)+xk(2)))
 xkp1=[ b*z**(1+0.1*(rand()-0.5)) 2*b*z**(1+0.1*(rand()-0.5)) ; s 0.0]*xk

The three macros fish, fishr, fishr2 are loaded in Scilab when calling bifish .

See Also

ode ,


boucle

Scilab Function
Last update : 12/01/2004

boucle - phase portrait of a dynamical system with observer

Calling Sequence

[]=boucle(fch,[abruit,xdim,npts,farrow])

Parameters

  • fch : Scilab macro. fch is supposed to be an observed-controlled system with noisy output of state dimension 4 ( [x;xchap] is of dimension 4). fch can be created with the macro obscont1 or can be set to one of the two following string which gives pre computed examples
    • "bcomp" : for a non-linear competition model.
    • "lcomp" : for a linear example.
  • abruit : give the noise variance.
  • xdim,npts,farrow : See portrait

Description

Phase portrait of dynamical systems.

See Also

portrait , ode , obscont1 ,


chaintest

Scilab Function
Last update : 12/01/2004

chaintest - a three-species food chain model

Calling Sequence

chaintest([f_l,b1,odem,xdim,npts])
[xdot]=chain(t,x)
[z1]=ch_f1(u)
[z2]=ch_f2(u)

Parameters

  • f_l : the name of the macro which code the three-species food chain model (default value chain ).
  • odem,xdim,npts : are optional arguments. Their meaning and syntax can be found in the portr3d help

Description

A call to the function chaintest() will interactively display a phase portrait of a three-species food chain model given by:

 ff1= f1(x(1))
 ff2= f2(x(2))

 xdot1= x(1)*(1-x(1)) - ff1*x(2)
 xdot2= ff1*x(2) -  ff2*x(3) - 0.4*x(2)
 xdot3= ff2*x(3) - 0.01*x(3)

and

 f1(u)=5*u/(1+b1*u)
 f2(u)z2=0.1*u/(1+2*u)

The default value for b1 is 3.0.

The Scilab macros chain(t,x) , f1(u),f2(u) code the dynamical system

See Also

portr3d , ode ,


gpeche

Scilab Function
Last update : 12/01/2004

gpeche - a fishing program

Calling Sequence

[xk,ukp1]=gpeche(uk,pasg)
[ut]=peche(t)
[pdot]=pechep(t,p)

Description

gpeche Iterates a gradient method on a fishing problem Computes the trajectory associated to the command law uk prints the cost value and computes a new control.


fusee

Scilab Function
Last update : 12/01/2004

fusee - a set of Scilab macro for a landing rocket problem

Description

FUSEE [xdot]=fusee(t,x) gives the dynamical motion equation for the rocket
FINIT finit() Initialises the following parameters for rocket landing.
  • k : The acceleration of the rocket engines
  • gamma : The moon gravity acceleration.
  • umax : the gaz ejection flow out.
  • mcap : the mass of the space capsule.
  • cpen : penalisation in the cost function of the final state.
    • FUSEEGRAD [ukp1]=fuseegrad(niter,ukp1,pasg) Iterate a gradient method and returns the computed control.
  • niter : number of gradient iteration steps.
  • ukp1 : initial control value ( vector of sie 135 )
  • pasg : the gradient step value.
    • FUSEEP [pdot]=fuseep(t,p) adjoint equation for the landing rocket problem.
    POUSSE [ut]=pousse(t) return the value of a piece wise constant control build on the discrete control uk
    UBANG [uk]=ubang(tf,tcom) returns a bang-bang control, 0 form time 0 to tcom and 1 form tcom to tf.
    FCOUT [c,xk,pk,ukp1]=fcout(tf,uk,pasg) optimise the following cost function by gradient iterations. c = -m(tf) + C*( h(tf)**2 + v(tf)**2)
    SFUSEE []=sfusee(tau,h0,v0,m0,Tf) computes the rocket trajectory when a bang-bang control is used tau is the commutation time.
  • h0 : The initial position (high)
  • v0 : The initial speed ( negative if the rocket is landing )
  • m0 : The total initial mass ( capsule and fuel).
  • Tf : Time horizon.
    • EQUAD [xk,pk]=equad(tf,uk) Computes the state and adjoint state of the rocket system for a given control ur .
    TRAJ [xt]=traj(t) returns a piece wise value of the mass evolution.


lotest

Scilab Function
Last update : 12/01/2004

lotest - demo of the Lorenz attractor

Calling Sequence

[]=lotest([f_l,odem,xdim,npts,pinit])
[y]=lorenz(t,x)
[]=ilo(sig,ro,beta)
[]=ilof(sig,ro,beta)

Parameters

  • f_l : can be "loren" or lorenz . it is the name of the external for the Lorenz system. "loren" will use a Fortran coded version of the lorenz system and arnold will and loren will use a Scilab coded version. lorentz is the Scilab macro which code the lorenz system. This macro is loaded when calling lotest .
  • ilof, ilo :are used to fix the parameters of the Fortran and Scilab code version of the Lorenz system.
  • odem,xdim,npts : are optional arguments. Their meaning and syntax can be found in the portr3d help

Description

A call to the function lotest() will interactively display a phase portrait of a the following dynamical system

 y(1)=sig*(x(2)-x(1));
 y(2)=ro*x(1) -x(2)-x(1)*x(3);
 y(3)=-beta*x(3)+x(1)*x(2);

See Also

portr3d , ode , chaintest , lotest ,


mine

Scilab Function
Last update : 12/01/2004

mine - a mining problem

Calling Sequence

[cout,feed]=mine(n1,n2,uvect)
[]=showcost(n1,n2,teta,alpha)

Parameters

  • n1 : Number of discrete point for the state.
  • n2 : Number of time step
  • uvect : a row vector which gives the possible control value ( integer values ). for example u=[-1,0,1] means that at each step we come down one step or stay at the same level or rise one step ).
  • cout(n1,n2) : The Bellman values.
  • feed(n1,n2) : The feedback Law.

Description

Dynamic programming applied to an optimal extraction of ore in an opencast mine. The extraction is done as follows : the steam shovel move forward for (k=1,2,...,n2) at each step it takes the ore, then move up or down (or stay at the same level) according to the control value to reach another level at next step. The extraction process must maximise the following cost :

   -- n2-1
   \
   /        f(x(k),k) + V_F(x,n2)
   -- k=1

with x(k+1)=x(k) + u . x(k) is the trajectory depth at step k ( x=1 is the ground level). The instantaneous cost f(i,k) stands for the benefit of digging at depth i at position k . It must be given as a Scilab macro ff_o

[y]=ff_o(x,k)

and for efficiency ff_o must accept and return column vectors for x and y .

V_F(i,n2) is a final cost which is set so as to impose the steam shovel to be at ground level at position n2

showcost Shows a 3D representation of the instantaneous cost.


obscont1

Scilab Function
Last update : 12/01/2004

obscont1 - a controlled-observed system

Calling Sequence

[macr]=obscont1(sysn)

Parameters

  • sysn : A Scilab string which gives the name of the controlled system.
  • gaincom,gainobs : column vectors giving the requested gains
  • macr : a new Scilab function which simulates the controlled observed system.

[x1dot]=macr(t,x1,abruit,pas,n)
x1=[x;xchap],

Description

This macros return a new function which computes the controlled observed version of a linearised system around the (xe,ue) point.

before calling this function, a noise vector br should be created. the equilibrium point (xe,ue) should be given as a global Scilab. the linearised system $f,g,h$ and the two gain matrices l,k are returned as global Scilab data.


portr3d

Scilab Function
Last update : 12/01/2004

portr3d - 3 dimensional phase portrait.

Calling Sequence

[]=portr3d(f,[odem,xdim,npts,pinit])

Parameters

  • f : a Scilab external which gives the field of the dynamical system. Hence it can be a macro name which computes the field at time t and point x [y]=f(t,x,[u]) or a list list(f1,u1) where f1 is a macro of type [y]=f1(t,x,u) or a character string
  • .I rest : The other parameters are optional. If omitted they will be asked interactively
    • odem : gives the integration method to use. The value "default" can be used, otherwise see ode for a complete set of possibilities
    • npts : a vector of size (2,10) [number-of-points,step] gives the step for integration and the number of requested points. The solution will be calculated and drawn for time=0:step:(step*[number-of-points])
    • xdim : [xmin,xmax,ymin,ymax,zmin,zmax] the boundaries of the graphic frame.
    • pinit : initial values for integration. A set of initial points can be given in a matrix

      pinit = [x0(1), x1(1),...., xn(1)
               x0(2), x1(2),...., xn(2)
               x0(3), x1(3),...., xn(3)].

Description

Interactive integration and display of a 3 dimensional phase portrait of a dynamical system dx/dt=f(t,x,[u]) (where u is an optional parameter )

See Also

ode ,


portrait

Scilab Function
Last update : 12/01/2004

portrait - 2 dimensional phase portrait.

Calling Sequence

[]=portrait(f,[odem,xdim,npts,pinit])

Parameters

  • f : a Scilab external which gives the field of the dynamical system. Hence it can be a macro name which computes the field at time t and point x [y]=f(t,x,[u]) or a list list(f1,u1) where f1 is a macro of type [y]=f1(t,x,u) or a character string. The macro can be used to simulate a continuous or discrete system and in case of discrete system the second parameter must be set to 'discrete'
  • options : The other parameters are optional. If omitted they will be asked interactively
    • odem : gives the integration method to use. The value "default" can be used, otherwise see ode for a complete set of possibilities
    • npts : a vector of size (2,10) [number-of-points,step] gives the step for integration and the number of requested points. The solution will be calculated and drawn for time=0:step:(step*[number-of-points])
    • xdim : [xmin,xmax,ymin,ymax,zmin,zmax] the boundaries of the graphic frame.
    • pinit : initial values for integration. A set of initial points can be given in a matrix

      pinit = [x0(1), x1(1),...., xn(1)
               x0(2), x1(2),...., xn(2)
               x0(3), x1(3),...., xn(3)].

Description

Interactive integration and display of a 2 dimensional phase portrait of a dynamical system dx/dt=f(t,x,[u]) (where u is an optional parameter )

Examples

a=rand(2,2)
deff('[ydot]=l_s(t,y)','ydot=a*y')
portrait(l_s)

See Also

ode ,


recur

Scilab Function
Last update : 12/01/2004

recur - a bilinear recurrent equation

Calling Sequence

[y]=recur(x0,var,k,n)
[integr]=logr(k,var)

Description

computes solutions of a bilinear recurrent equation

x(i+1)=-x(i)*(k + sqrt(var)*br(i))

with initial value x0 and driven by a white noise of variance var .

Trajectories are drawn and the empirical Lyapunov exponent is returned ( x(i) is not to much different from exp(y*i) )

A theoretical computation of the Lyapunov exponent is given by

[integr]=logr(k,var)


systems

Scilab Function
Last update : 12/01/2004

systems - a collection of dynamical system

Calling Sequence

[]=systems()

Description

A call to this function will load into Scilab a set of macros which describes dynamical systems. Their parameters can be initiated by calling the routine tdinit().

Bioreact

[ydot]=biorecat(t,x)

a bioreactor model,

  • x(1) is the biomass concentration
  • x(2) is the sugar concentration
    •
                    xdot(1)=mu_td(x(2))*x(1)- debit*x(1);
                    xdot(2)=-k*mu_td(x(2))*x(1)-debit*x(2)+debit*x2in;

    where mu_td is given by

                    mu_td(x)=x/(1+x);

    Compet

[xdot]=compet(t,x [,u])

    a competition model. x(1),x(2) stands for two populations which grows on a same resource. 1/u is the level of that resource ( 1 is the default value).

xdot=0*ones(2,1);
xdot(1) = ppr*x(1)*(1-x(1)/ppk) - u*ppa*x(1)*x(2) ,
xdot(2) = pps*x(2)*(1-x(2)/ppl) - u*ppb*x(1)*x(2) ,

    "The macro [xe]=equilcom(ue) " computes an equilibrium point of the competition model and a fixed level of the resource ue ( default value is 1)

    "The macro [f,g,h,linsy]=lincomp([ue]) " gives the linearisation of the competition model ( with output y=x) around the equilibrium point xe=equilcom(ue). This macro returns [f,g,h] the three matrices of the linearised system. and linsy which is a Scilab macro [ydot]=linsy(t,x) which computes the dynamics of the linearised system

    Cycllim

[xdot]=cycllim(t,x)

    a model with a limit cycle

  xdot=a*x+qeps(1-||x||**2)x

    Linear

[xdot]=linear(t,x)

    a linear system

    Blinper

[xdot]=linper(t,x)

    a linear system with quadratic perturbations.

    Pop

[xdot]=pop(t,x)

    a fish population model

xdot= 10*x*(1-x/K)- peche(t)*x

    Proie

    a Predator prey model with external insecticide.

[xdot]=p_p(t,x,[u]
  • x(1) The prey ( that we want to kill )
  • x(2) the predator ( that we want to preserve )
  • u mortality rate due to insecticide which destroys both prey and predator ( default value u=0)
    •
xdot(1) = ppr*x(1)*(1-x(1)/ppk) - ppa*x(1)*x(2) - u*x(1);
xdot(2) = -ppm*x(2)             + ppb*x(1)*x(2) - u*x(2);

    The macro [xe]=equilpp([ue]) computes the equilibrium point of the p_p system for the value ue of the command. The default value for ue is 0.

                    xe(1) =  (ppm+ue)/ppb;
                    xe(2) =  (ppr*(1-xe(1)/ppk)-ue)/ppa;

    Lincom

[xdot]=lincom(t,x,k)

    linear system with a feedback

 xdot= a*x +b*(-k*x)

    See Also

    tdinit ,


tangent

Scilab Function
Last update : 31/10/2006

tangent - linearization of a dynamical system at an equilibrium point

Calling Sequence

[f,g,newm]=tangent(ff,xe,[ue])

Parameters

  • ff : a string which gives the name of the Scilab function which codes the system, or the fuunction itself.
  • xe : column vector which gives the equilibrium point for the value ue of the parameter
  • ue : real value.
  • f, g : two matrices for the linearised system dxdot=f.dx + g.du
  • newm : A new macro of type [y]=newm(t,x,u) which computes the field of the linearised system (newm(t,xe,ue)=0)

Description

linearises around the equilibrium point (xe,ue) the vector field of the dynamical system given by a Scilab macro ff , xdot=ff(t,x,[u]) . The dynamical system is supposed to be autonomous.


tdinit

Scilab Function
Last update : 12/01/2004

tdinit - interactive initialisation of the tdcs dynamical systems

Calling Sequence

tdinit()

Description

This macro can be used to interactively define the parameters needed by the dynamical systems described in systems

"bioreactor model"

"competition model"

"system with limit cycle"

"linear system"

"quadratic model"

"linear system with a feedback"

"prey predatory model"

See Also

portrait , systems ,


Statistiques
center - center
wcenter - center and weight
cmoment - central moments of all orders
correl - correlation of two variables
covar - covariance of two variables
ftest - Fischer ratio
ftuneq - Fischer ratio for samples of unequal size.
geomean - geometric mean
harmean - harmonic mean
iqr - interquartile range
labostat - Statistical toolbox for Scilab
mad - mean absolute deviation
mean - mean (row mean, column mean) of vector/matrix entries
meanf - weighted mean of a vector or a matrix
median - médiane des termes d'une matrice
moment - non central moments of all orders
msd - mean squared deviation
mvvacov - computes variance-covariance matrix
nancumsum - Thos function returns the cumulative sum of the values of a matrix
nand2mean - difference of the means of two independent samples
nanmax - max (ignoring Nan's)
nanmean - mean (ignoring Nan's)
nanmeanf - mean (ignoring Nan's) with a given frequency.
nanmedian - median of the values of a numerical vector or matrix
nanmin - min (ignoring Nan's)
nanstdev - standard deviation (ignoring the NANs).
nansum - Sum of values ignoring NAN's
nfreq - frequence of the values in a vector or matrix
pca - Principal components analysis
perctl - computation of percentils
quart - computation of quartiles
regress - regression coefficients of two variables
sample - Sampling with replacement
samplef - sample with replacement from a population and frequences of his values.
samwr - Sampling without replacement
st_deviation - écart-type des termes d'une matrice
stdev - écart-type des termes d'une matrice
stdevf - standard deviation
strange - range
tabul - frequency of values of a matrix or vector
thrownan - eliminates nan values
trimmean - trimmed mean of a vector or a matrix
variance - variance of the values of a vector or matrix
variancef - standard deviation of the values of a vector or matrix


center

Last update : 12/01/2004

center - center

Calling Sequence

s=center(x)
s=center(x,'r') or s=center(x,1)
s=center(x,'c') or s=center(x,2)

Parameters

  • x: real or complex vector or matrix

Description

This function computes s , the centred version of the numerical matrix x . For a vector or a matrix x , s=center(x) returns in the (i,j) coefficient of the matrix s the value (x(i,j)-xbar) , where xbar is the mean of the values of the coefficients of x . s=center(x,'r') (or, equivalently, s=center(x,1) ) is the rowwise center reduction of the values of x . It returns in the entry s(i,j) the value (x(i,j)-xbarv(j))(j) with xbarv(j) the mean of the values of the j column. s=center(x,'c') (or, equivalently, s=center(x,2) ) is the columnwise center reduction of the values of x . It returns in the entry s(i,j) the value (x(i,j)-xbarh(i))) with xbarh(i) the mean of the values of the i row.

Examples

x=[0.2113249  0.0002211 0.6653811;
   0.7560439  0.3303271 0.6283918]
s=center(x)
s=center(x,'r')
s=center(x,'c')

See Also

wcenter ,

Author

Carlos Klimann


wcenter

Last update : 12/01/2004

wcenter - center and weight

Calling Sequence

s=wcenter(x)
s=wcenter(x,'r') or s=wcenter(x,1)
s=wcenter(x,'c') or s=wcenter(x,2)

Parameters

  • x: real or complex vector or matrix

Description

This function computes s , the weigthed and centred version of the numerical matrix x .

For a vector or a matrix x , s=wcenter(x) returns in the (i,j) coefficient of the matrix s the value (x(i,j)-xbar)/sigma , where xbar is the mean of the values of the coefficients of x and sigma his standard deviation.

s=wcenter(x,'r') (or, equivalently, s=wcenter(x,1) ) is the rowwise centre reduction of the values of x . It returns in the entry s(i,j) the value (x(i,j)-xbarv(j))/sigmav(j) with xbarv(j) the mean of the values of the j column and sigmav(j) the standard deviation of the j column of x .

s=wcenter(x,'c') (or, equivalently, s=wcenter(x,2) ) is the columnwise centre reduction of the values of x . It returns in the entry s(i,j) the value (x(i,j)-xbarh(i))/sigmah(i) with xbarh(i) the mean of the values of the i row and sigmah(i) the standard deviation of the i row of x .

Examples

x=[0.2113249 0.0002211 0.6653811;
   0.7560439 0.3303271 0.6283918]
s=wcenter(x)
s=wcenter(x,'r')
s=wcenter(x,'c')

See Also

center ,

Author

Carlos Klimann


cmoment

Last update : 12/01/2004

cmoment - central moments of all orders

Calling Sequence

mom=cmoment(x,ord)
mom=cmoment(x,ord,'r') or mom=cmoment(x,ord,1)
mom=cmoment(x,ord,'c') or mom=cmoment(x,ord,2)

Parameters

  • x : real or complex vector or matrix
  • ord : positive integer

Description

cmoment (x,ord) is the central moment or order ord of the elements of x . If a third argument of type string 'r' (or 1 ) or 'c' (or 2 ) is used, we get in the first case, a row vector mom such that mom(j) contains the central moment of order ord of the j column of x . cmoment(x,ord,'c') is used in the same way for the central moments in the rows.

References

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, J.Wiley & Sons, 1990.

Examples

x=[0.2113249 0.0002211 0.6653811;
   0.7560439 0.3303271 0.6283918]
mom=cmoment(x,3)
mom=cmoment(x,2,'r')
mom=cmoment(x,3,'c')

See Also

sum , median , st_deviation , mean , meanf , moment , nanmean , nanmeanf , stdev , stdevf , variance , variancef , nanstdev ,

Author

Carlos Klimann


correl

Last update : 12/01/2004

correl - correlation of two variables

Calling Sequence

rho=correl(x,y,fre)

Parameters

  • x : real or complex vector
  • y : real or complex vector
  • fre : matrix of type length(x) x length(y)

Description

correl(x,y,fre) computes the correlation of two variables x and y. fre is a matrix of dimensions length(x) x length(y). In fre the element of indices (i,j) corresponds to the value or number or frequences of x_i&y_j.

References

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, J.Wiley & Sons, 1990.

Examples

x=[2.5 7.5 12.5 17.5]
h=[0 1 2]
fre=[.03 .12 .07;.02 .13 .11;.01 .13 .14;.01 .09 .14]
rho=correl(x,h,fre)

See Also

covar ,

Author

Carlos Klimann


covar

Last update : 12/01/2004

covar - covariance of two variables

Calling Sequence

s=covar(x,y,fre)

Parameters

  • x : real or complex vector
  • y : real or complex vector
  • fre : matrix of type length(x) x length(y)

Description

covar(x,y,fre) computes the covariance of two variables x and y. fre is a matrix of dimensions length(x) x length(y). In fre the element of indices (i,j) corresponds to the value or number or frequences of x_i&y_j.

References

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, J.Wiley & Sons, 1990.

Examples

x=[10 20 30 40]
y=[10 20 30 40]
fre=[.20 .04 .01  0;
     .10 .36 .09  0;
       0 .05 .10  0;
       0   0   0 .05]
s=covar(x,y,fre)

Author

Carlos Klimann


ftest

Last update : 12/01/2004

ftest - Fischer ratio

Calling Sequence

f=ftest(samples)
[f,p]=ftest(samples)

Parameters

  • samples : real or complex matrix of type nr X nc

Description

f=ftest(samples) computes the Fischer ratio of the nc samples whose values are in the columns of the matrix samples . Each one of these samples is composed of nr values. (The Fischer ratio is the ratio between nr times the variance of the means of samples and the mean of variances of each sample)

[f,p]=ftest(samples) gives in p the p-value of the computed Fischer ratio f.

References

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, J.Wiley & Sons, 1990.

Examples

samples=[46 55 54;
         53 54 50;
         49 58 51;
         50 61 51;
         46 52 49]
[f,p]=ftest(samples)

See Also

ftuneq ,

Author

Carlos Klimann


ftuneq

Last update : 12/01/2004

ftuneq - Fischer ratio for samples of unequal size.

Calling Sequence

f=ftuneq(sample1[,sample2[,sample3]...]])
[f,p]=ftuneq(sample1[,sample2[,sample3]...]])

Parameters

  • sample1, sample2, sample3,... : real or complex matrix of any type

Description

This function computes the F ratio for samples of unequal size.

"The most efficient design is to make all samples the same size n. However when this is nor feasible, it still is possible to modify the ANOVA calculations." Note that the definition of xbarbar is no longer mean(xbar), but rather a weighted average with weights ni. Additionnally it gives (in p) the p-value of the computed Fischer ratio.

Given a number a of samples each of them composed of n_i (i from 1 to a) observations this fonction computes in f the Fischer ratio (it is the ratio between nr times the variance of the means of samples and the mean of the variances of each sample).

f=ftest(samples) computes the Fischer ratio of the nc samples whose values are in the columns of the matrix samples . Each one of these samples is composed of nr values. (The Fischer ratio is the ratio between nr times the variance of the means of samples and the mean of variances of each sample)

[f,p]=ftest(samples) gives in p the p-value of the computed Fischer ratio f.

References

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, J.Wiley & Sons, 1990.

Examples

samples=[46 55 54;53 54 50; 49 58 51;50 61 51;46 52 49]
[f,p]=ftest(samples)

See Also

ftuneq ,

Author

Carlos Klimann


geomean

Last update : 12/01/2004

geomean - geometric mean

Calling Sequence

gm=geomean(x)
gm=geomean(x,'r')(or, equivalently, gm=geomean(x,1))
gm=geomean(x,'c')(or, equivalently, gm=geomean(x,2))

Parameters

  • x :real or complex vector or matrix

Description

This function computes the geometric mean of a vector or matrix x . For a vector or matrix x , gm=geomean(x) returns in scalar gm the geometric mean of all the entries of x .

gm=geomean(x,'r') (or, equivalently, gm=gmean(x,1) ) returns in each entry of the row vector gm the geometric mean of each column of x .

gm=geomean(x,'c') (or, equivalently, gm=gmean(x,2) ) returns in each entry of the column vector gm the geometric mean of each row of x .

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


harmean

Last update : 12/01/2004

harmean - harmonic mean

Calling Sequence

hm=harmean(x)
hm=harmean(x,'r')(or, equivalently, hm=harmean(x,1))
hm=harmean(x,'c')(or, equivalently, hm=harmean(x,2))

Parameters

  • x : real or complex vector or matrix

Description

This function computes the harmonic mean of a vector or matrix x . For a vector or matrix x , hm=harmean(x) returns in scalar hm the harmonic mean of all the entries of x .

hm=harmean(x,'r') (or, equivalently, hm=harmean(x,1) ) returns in each entry of the row vector hm the harmonic mean of each column of x .

hm=harmean(x,'c') (or, equivalently, hm=harmean(x,2) ) returns in each entry of the column vector hm the harmonic mean of each row of x .

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


iqr

Last update : 12/01/2004

iqr - interquartile range

Calling Sequence

q=iqr(x)
q=iqr(x,'r') (or, equivalently, q=iqr(x,1))
q=iqr(x,'c') (or, equivalently, q=iqr(x,2))

Parameters

  • x : real or complex vector or matrix

Description

This function computes the interquartile range IQR= upper quartile - lower quartile of a vector or a matrix x .

For a vector or a matrix x , q=iqr(x) returns in the scalar q the interquartile range of all the entries of x .

q=iqr(x,'r') (or, equivalently, q=iqr(x,1) ) is the rowwise interquartile range. It returns in each entry of the row vector q the interquartile range of each column of x .

q=iqr(x,'c') (or, equivalently, q=iqr(x,2) ) is the columnwise interquartile range. It returns in each entry of the column vector q the interquartile range of each row of x .

Author

Carlos Klimann

Bibliography

Wonacott, T.H.Wonacott, R.J.; Introductory Statistics, J.Wiley-Sons, 1990.


labostat

Last update : 12/01/2004

labostat - Statistical toolbox for Scilab

Contents

centre: centering variables
centrered: centering and reducing variables
cmoment: central moments of all orders
correl: correlation
covar: covariance
ftest: fischer test and his p-value
geomean: geometric mean
harmean: harmonic mean
iqr: interquartile range
mad: mean absolute deviation
meanf:  arithmetic mean of a vector or matrix with a table of frequences
median: 50th percentile of a sample
mn: arithmetic mean of a vector or matrix
moment: moments of all orders
msd:  mean squared  deviation
mvvacov : multivariable matrix of variance-covariance
nand2mean: estimate of the difference of means of two independent samples
nanmax:  maximum ignoring NaNs
nanmean: mean ignoring NaNs
nanmeanf:  mean with frequency table ignoring NaNs
nanmedian: 50th percentile of a sample ignoring NaNs
nanmin: minimum ignoring NANs
nanstdev:  standard deviation ignoring NaNs
nanstdevf: standard deviation with frequency table ignoring NaNs
nansum: sum ignoring NaNs
nfreq: frequency of the values of a sample
pca: principal component analysys
pctl: vector of  percentiles of a sample in decreasing order
perctl: vector of  percentiles of a sample in decreasing order
quart: quartils
stdev: standard deviation
stdevf: standard deviation with frequences
strange: distance between largest and smallest value
tabul: frequences of values
var: variance
varf: variance with frequence table

References

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, 5th edition, J.Wiley & Sons, 1990.

Saporta, Gilbert, Probabilites, Analyse des Donnees et Statistique, Editions Technip, Paris, 1990.


mad

Last update : 12/01/2004

mad - mean absolute deviation

Calling Sequence

s2=mad(x)
s2=mad(x,'r') or s2=mad(x,1)
s2=mad(x,'c') or s2=mad(x,2)

Parameters

  • x : real or complex vector or matrix

Description

This function computes the mean absolute deviation of a real or complex vector or matrix x .

For a vector or matrix x , s2=mad(x) returns in scalar s2 the mean absolute deviation of all the entries of x .

s2=mad(x,'r') (or, equivalently, s2=mad(x,1) ) returns in each entry of the column vector s2 the mean absolute deviation of each column of x .

s2=mad(x,'c') (or, equivalently, s2=mad(x,2) ) returns in each entry of the column vector s2 the mean absolute deviation of each row of x .

Bibliography

Reference: Wonacott T.H.& Wonacott R.J. .- Introductory Statistics, 5th edition, John Wiley, 1990.


meanf

Last update : 12/01/2004

meanf - weighted mean of a vector or a matrix

Calling Sequence

m=meanf(val,fre)
m=meanf(val,fre,'r') or m=meanf(val,fre,1)
m=meanf(val,fre,'c') or m=meanf(val,fre,2)

Parameters

  • ?

Description

This function computes the mean of a vector or matrix x . For a vector or matrix x , m=mn(x) returns in scalar m the mean of all the entries of x . m=mn(x,'r') (or, equivalently, m=mn(x,1) ) returns in each entry of the row vector m the mean of each column of x . m=mn(x,'c') (or, equivalently, m=mn(x,2) ) returns in each entry of the column vector m the mean of each row of x .

Examples

x=[0.2113249 0.0002211 0.6653811;0.7560439 0.3303271 0.6283918]
m=meanf(x,rand(x))
m=meanf(x,[10 10 10;1 1 1],'r')
m=meanf(x,[10 10 10;1 1 1],'c')

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


mean

Scilab Function
Last update : 12/01/2004

mean - mean (row mean, column mean) of vector/matrix entries

Calling Sequence

y=mean(x)
y=mean(x,'r')
y=mean(x,'c')

Parameters

  • x : real vector or matrix
  • y : scalar or vector

Description

For a vector or a matrix x , y=mean(x) returns in the scalar y the mean of all the entries of x .

y=mean(x,'r') (or, equivalently, y=mean(x,1) ) is the rowwise mean. It returns a row vector: y(j)= mean(x(:,j))

y=mean(x,'c') (or, equivalently, y=mean(x,2) ) is the columnwise mean. It returns a column vector: y(i)= mean(x(i,:))

Examples

A=[1,2,10;7,7.1,7.01];
mean(A)
mean(A,'r')
mean(A,'c')

See Also

sum , median , st_deviation ,


median

Scilab Function
Last update : 09/02/2006

median - médiane des termes d'une matrice

Calling Sequence

y=median(x)
y=median(x,'r')
y=median(x,'c')
y=median(x,'m')
y=median(x,dim)

Parameters

  • x : vecteur ou matrice réelle
  • y : scalaire ou vecteur
  • dim : entier positif

Description

Pour un vecteur ou une matrice x , y=median(x) renvoie un scalaire y égal à la médiane des termes de x .

y=median(x,'r') (ou y=median(x,1) ) est la médiane selon l'indice de lignes. Chaque composante du vecteur ligne y contient la médiane de chaque colonne de x .

y=median(x,'c') (ou y=median(x,2) ) est la médiane selon l'indice de colonne. Chaque composante du vecteur colonne y contient la médiane de chaque ligne de x .

y=median(x,'m') est la médiane suivant la première dimension non_singleton de x . (compatibilité avec matlab)

y=median(x,dim) est la médiane suivant la dimension dim de x . (compatibilité avec matlab)

Examples

A=[1,2,10;7,7.1,7.01];
median(A)
median(A,'r')
median(A,'c')
A=matrix([-9 3 -8 6 74 39 12 -6 -89 23 65 34],[2,3,2]);
median(A,3)
median(A,'m')

See Also

sum , mean , st_deviation ,


moment

Last update : 12/01/2004

moment - non central moments of all orders

Calling Sequence

mom=moment(x,ord)
mom=moment(x,ord,'r') or mom=moment(x,ord,1)
mom=moment(x,ord,'c') or mom=moment(x,ord,2)

Parameters

  • x : real or complex vector or matrix
  • ord : positive integer

Description

moment (x,ord) is the non central moment or order ord of the elements of x .

If a third argument of type string 'r' (or 1 ) or 'c' (or 2 ) is used, we get in the first case, a row vector mom such that mom(j) contains the non central moment of order ord of the j column of x . moment(x,ord,'c') is used in the same way for the non central moments in the rows.

Examples

x=[0.2113249 0.0002211 0.6653811;0.7560439 0.3303271 0.6283918]
mom=moment(x,3)
mom=moment(x,2,'r')
mom=moment(x,3,'c')

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


msd

Last update : 12/01/2004

msd - mean squared deviation

Calling Sequence

y=msd(x)
y=msd(x,'r') or m=msd(x,1)
y=msd(x,'c') or m=msd(x,2)

Parameters

  • x real or complex vector or matrix

Description

This function computes the mean squared deviation of the values of a vector or matrix x .

For a vector or a matrix x , y=msd(x) returns in the scalar y the mean squared deviation of all the entries of V x .

y=msd(x,'r') (or, equivalently, y=msd(x,1) ) is the rowwise mean squared deviation. It returns in each entry of the row vector y the mean squared deviation of each column of x .

y=msd(x,'c') (or, equivalently, m=msd(x,2) ) is the columnwise mean squared deviation. It returns in each entry of the column vector y the mean squared deviation of each row of x .

Examples

x=[0.2113249 0.0002211 0.6653811;0.7560439 0.3303271 0.6283918]
m=msd(x)
m=msd(x,'r')
m=msd(x,'c')

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


mvvacov

Last update : 12/01/2004

mvvacov - computes variance-covariance matrix

Calling Sequence

v=mvvacov(x)

Parameters

  • x : real or complex vector or matrix

Description

This function computes v, the matrix of variance-covariance of the "tableau" x (x is a numerical matrix nxp) who gives the values of p variables for n individuals: the (i,j) coefficient of v is v(i,j)=E(xi-xibar)(xj-xjbar), where E is the first moment of a variable, xi is the i-th variable and xibar the mean of the xi variable.

Examples

x=[0.2113249 0.0002211 0.6653811;0.7560439 0.4453586 0.6283918]
v=mvvacov(x)

Author

Carlos Klimann

Bibliography

Saporta, Gilbert, Probabilites, Analyse des Donnees et Statistique, Editions Technip, Paris, 1990. Mardia, K.V., Kent, J.T. & Bibby, J.M., Multivariate Analysis, Academic Press, 1979.


nancumsum

Scilab Function
Last update : 15/01/2004

nancumsum - Thos function returns the cumulative sum of the values of a matrix

Calling Sequence

s = nancumsum(x,orient)

Parameters

  • x : x is a numerical vector or matrix.
  • orient : is an optional parameter. The possible values are '*', 1, 2, 'r' or 'c'.
  • s : numerical scalar or vector. It contains the cumulative sum of the values of x, ignoring the NAN's.

Description

This function returns in scalar or vector s the cumulative sum of the values (ignoring the NANs) of a vector or matrix (real or complex) x.

This function for a vector or a matrix x, s=nancumsum(x) (or, equivalently s=nancumsum(x,'*') returns in scalar s the cumulative sum (ignoring the NANs) of all the entries of x taken columnwise.

s=nancumsum(x,'r') (or, equivalently, s=nancumsum(x,1)) returns in the cols(x) sized vector s the cumulative sum (ignoring the NANs) of the rows of x: s(:,i)=nancumsum(x(:,i))

s=nancumsum(x,'c') (or, equivalently, s=nancumsum(x,2)) returns in the rows(x) sized vector s the cumulative sum (ignoring NANs) of the columns of x: s(i,:)=nancumsum(x(i,:))

For the last two cases, if a row or column is in whole composed of NAN, the corresponding place of s will contain a NAN.

Examples

a=[1 2 3;4 5 6]
s=nancumsum(a)
s=nancumsum(a,'r')
s=nancumsum(a,'c')

See Also

nansum , cumsum ,

Author

Carlos Klimann


nand2mean

Last update : 12/01/2004

nand2mean - difference of the means of two independent samples

Calling Sequence

[dif]=nand2mean(sample1,sample2)
[dif]=nand2mean(sample1,sample2,conf)

Parameters

  • sample1 real or complex vector or matrix
  • sample2 real or complex vector or matrix
  • conf real scalar between 0 and 1

Description

This function computes an estimate (dif(1)) for the difference of the means of two independent samples (arrays sample1 and sample2) and gives the half amplitude of the range of variability of dif with an indicated confidence level (dif(2)). The choice of the normal or t fonctions as the probability fonction depends on the sizes of sample1 and sample2. We suppose that the underlying variances of both populations are equal. NAN values are not counted.

In Labostat, NAN values stand for missing values in tables.

In absence of the confidence parameter a confidence level of 95% is assumed.

References

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, 5th edition, J.Wiley & Sons, 1990.


nanmax

Last update : 12/01/2004

nanmax - max (ignoring Nan's)

Calling Sequence

[m,index]=nanmax(x)
[m,index]=nanmax(x,'r')
[m,index]=nanmax(x,'c')

Parameters

  • x real or complex vector or matrix

Description

This function gives for a real or a numerical matrix x his largest element m (but ignoring the NANs).

For x , a numerical vector or matrix, m=nanmax(x) returns in scalar m the largest element of x (ignoring the NANs). The form [m,index] =nanmax(x,orient) gives in addition of the value of the largest element of x (ignoring the NANs) in scalar m , the index of this element in x , as a 2-vector.

m=nanmax(x,'r') gives in the 1xsize(x,2) matrix m the largest elements (ignoring the NANs) of each column of x . If the form [m,index]=nanmax(x,'r') is used, the elements of the 1xsize(x,2) matrix index are the indexes of the largest elements (ignoring the NANs) of each column of x in the corresponding column.

m=nanmax(x,'c') gives in the size(x,2)x1 matrix m the largest elements (ignoring the NANs) of each row of x. If the form [m,index]=nanmax(x,'c') is used, the elements of the size(x,2)x1 matrix index are the indexes of the largest elements (ignoring the NANs) of each row of x in the corresponding row.

In Labostat, NAN values stand for missing values in tables.

Examples

x=[0.2113249 %nan 0.6653811;0.7560439 0.3303271 0.6283918]
m=nanmax(x)
m=nanmax(x,'r')
m=nanmax(x,'c')

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


nanmeanf

Last update : 12/01/2004

nanmeanf - mean (ignoring Nan's) with a given frequency.

Calling Sequence

m=nanmean(val,fre)
m=nanmean(val,fre,'r') (or m=nanmean(val,fre,1))
m=nanmean(val,fre,'c') (or m=nanmean(val,fre,2))

Parameters

  • val : real or complex vector or matrix
  • fre : integer vector or matrix with same dimensions than val

Description

This function returns in scalar m the mean of the values (ignoring the NANs) of a vector or matrix val , each counted with a frequency signaled by the corresponding values of the integer vector or matrix fre with the same type of val .

For a vector or matrix val , m=nanmeanf(val,fre) or m=nanmeanf(val,fre,'*') returns in scalar m the mean of all the entries (ignoring the NANs) of val , each value counted with the multiplicity indicated by the corresponding value of fre .

m=nanmeanf(val,fre,'r') (or, equivalently, m=nanmeanf(val,fre,1) ) returns in each entry of the row vector m of type 1xsize(val,'c') the mean of each column of val (ignoring the NANs), each value counted with the multiplicity indicated by the corresponding value of fre .

m=nanmeanf(val,fre,'c') (or, equivalently, m=nanmeanf(val,fre,2) ) returns in each entry of the column vector m of type size(val,'c')x1 the mean of each row of val (ignoring the NANs), each value counted with the multiplicity indicated by the corresponding value of fre.

In Labostat, NAN values stand for missing values in tables.

Examples

x=[0.2113249 %nan 0.6653811;0.7560439 0.3303271 0.6283918]
fre=[34 12 25;12 23 5]
m=nanmeanf(x,fre)
m=nanmeanf(x,fre,1)
m=nanmeanf(x,fre,2)

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


nanmean

Last update : 12/01/2004

nanmean - mean (ignoring Nan's)

Calling Sequence

m=nanmean(val)
m=nanmean(val,'r') (or m=nanmean(val,1))
m=nanmean(val,'c') (or m=nanmean(val,2))

Parameters

  • val : real or complex vector or matrix

Description

This function returns in scalar m the mean of the values (ignoring the NANs) of a vector or matrix val .

For a vector or matrix val , m=nanmean(val) or m=nanmean(val,'*') returns in scalar m the mean of all the entries (ignoring the NANs) of val .

m=nanmean(val,'r') (or, equivalently, m=nanmean(val,1) ) returns in each entry of the row vector m of type 1xsize(val,'c') the mean of each column of val (ignoring the NANs).

m=nanmeanf(val,'c') (or, equivalently, m=nanmean(val,2) ) returns in each entry of the column vector m of type size(val,'c')x1 the mean of each row of val (ignoring the NANs).

In Labostat, NAN values stand for missing values in tables.

Examples

x=[0.2113249 %nan 0.6653811;0.7560439 0.3303271 0.6283918]
m=nanmean(x)
m=nanmean(x,1)
m=nanmean(x,2)

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


nanmedian

Last update : 12/01/2004

nanmedian - median of the values of a numerical vector or matrix

Calling Sequence

m=nanmedian(x)
m=nanmedian(x,'r') (or m=nanmedian(x,1))
m=nanmedian(x,'c') (or m=nanmedian(x,2))

Parameters

  • x : real or complex vector or matrix

Description

For a vector or a matrix x , [m]=nanmedian(x) returns in the vector m the median of the values (ignoring the NANs) of vector x .

[m]=nanmedian(x,'r') (or, equivalently, [m]=nanmedian(x,1) ) are the rowwise medians. It returns in each position of the row vector m the medians of data (ignoring the NANs) in the corresponding column of x .

[m]=nanmedian(x,'c') (or, equivalently, [m]=nanmedian(x,2) ) are the columnwise madians. It returns in each position of the column vector m the medians of data (ignoring the NANs) in the corresponding row of x .

In Labostat, NAN values stand for missing values in tables.

Examples

x=[0.2113249 %nan 0.6653811;0.7560439 0.3303271 0.6283918]
m=nanmedian(x)
m=nanmedian(x,1)
m=nanmedian(x,2)

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


nanmin

Last update : 12/01/2004

nanmin - min (ignoring Nan's)

Calling Sequence

[m,index]=nanmin(x)
[m,index]=nanmin(x,'r')
[m,index]=nanmin(x,'c')

Parameters

  • x : real or complex vector or matrix

Description

This function gives for a real or a numerical matrix x his largest element m (but ignoring the NANs).

For x , a numerical vector or matrix, m=nanmin(x) returns in scalar m the largest element of x (ignoring the NANs). The form [m,index] =nanmin(x,orient) gives in addition of the value of the largest element of x (ignoring the NANs) in scalar m , the index of this element in x , as a 2-vector.

m=nanmin(x,'r') gives in the 1xsize(x,2) matrix m the largest elements (ignoring the NANs) of each column of x . If the form [m,index]=nanmin(x,'r') is used, the elements of the 1xsize(x,2) matrix index are the indexes of the largest elements (ignoring the NANs) of each column of x in the corresponding column.

m=nanmin(x,'c') gives in the size(x,2)x1 matrix m the largest elements (ignoring the NANs) of each row of x. If the form [m,index]=nanmin(x,'c') is used, the elements of the size(x,2)x1 matrix index are the indexes of the largest elements (ignoring the NANs) of each row of x in the corresponding row.

In Labostat, NAN values stand for missing values in tables.

Examples

x=[0.2113249 %nan 0.6653811;0.7560439 0.3303271 0.6283918]
m=nanmin(x)
m=nanmin(x,'r')
m=nanmin(x,'c')

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


nanstdev

Last update : 12/01/2004

nanstdev - standard deviation (ignoring the NANs).

Calling Sequence

s=nanstdev(x)
s=nanstdev(x,'r') or m=nanstdev(x,1)
s=nanstdev(x,'c') or m=nanstdev(x,2)

Parameters

  • x real or complex vector or matrix

Description

This function computes the standard deviation of the values of a vector or matrix x (ignoring the NANs).

For a vector or a matrix x , s=nanstdev(x) returns in the scalar s the standard deviation of all the entries of x (ignoring the NANs).

s=nanstdev(x,'r') (or, equivalently, s=nanstdev(x,1) ) is the rowwise standard deviation. It returns in each entry of the row vector s the standard deviation of each column of x (ignoring the NANs).

s=nanstdev(x,'c') (or, equivalently, s=nanstdev(x,2) ) is the columnwise standard deviation. It returns in each entry of the column vector s the standard deviation of each row of x (ignoring the NANs).

In Labostat, NAN values stand for missing values in tables.

Examples

x=[0.2113249 0.0002211 0.6653811;
   0.7560439 %nan      0.6283918;
   0.3       0.2       0.5      ];
s=nanstdev(x)
s=nanstdev(x,'r')
s=nanstdev(x,'c')

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


nansum

Scilab Function
Last update : 15/01/2004

nansum - Sum of values ignoring NAN's

Calling Sequence

s = nansum(x,orient)

Parameters

  • x : numerical vector or matrix.
  • orient : nothing or '*'. 'r' or 1. 'c' or 2.
  • s : Numerical scalar or vector containig the value of the adding operation.

Description

This function returns in s the sum of the values (ignoring the NAN's) of a numerical vector or matrix x.

For a vector or matrix x, s=nansum(x) (or s=nansum(x,'*')) returns in scalar s the sum of values of all entries (ignoring the NAN's) of a vector or matrix x.

s=nansum(x,'r')(or, equivalently, s=nansum(x,1)) returns in each entry of the row vector s of type 1xsize(x,'c') the sum of each column of x (ignoring the NANs).

s=nansum(x,'c')(or, equivalently, s=nansum(x,2)) returns in each entry of the column vector s of type size(x,'c')x1 the sum of each row of x (ignoring the NANs).

For the last two cases, if a row or column is in whole composed of NAN, the corresponding place of s will contain a NAN.

Examples

    x=[0.2113249 %nan 0.6653811;0.7560439 0.3303271 0.6283918]
    m=nansum(x)
    m=nansum(x,1)
    m=nansum(x,2)

See Also

nancumsum , sum ,

Author

Carlos Klimann

Bibliography

Wonacott, T.H. and Wonacott, R.J.; Introductory Statistics, 5th edition, J.Wiley and Sons, 1990.


nfreq

Last update : 12/01/2004

nfreq - frequence of the values in a vector or matrix

Calling Sequence

m=nfreq(x)

Parameters

  • x real or complex vector or matrix

Description

Frequence of the values in a real or complex vector or a real or complex matrix x .

For a real or complex vector or a real or complex matrix x , m=freq(x) returns in the first column of the size(x,'*')x2 matrix m the values of x and in the second column of this matrix the frequences of the corresponding values.

Note that the tabul function is more efficient, applies also to vector of strings and returns a sorted m .

Examples

x=[2 8 0 3 7 6 8 7 9 1]
m=nfreq(x)

See Also

tabul , dsearch , histplot ,

Author

Carlos Klimann


pca

Scilab Function
Last update : 15/01/2004

pca - Principal components analysis

Calling Sequence

[lambda,facpr,comprinc] = pca(x,N)

Parameters

  • x : is a nxp (n individuals, p variables) real matrix
  • N : is a 2x1 integer vector. Its coefficients point to the eigenvectors corresponding to the eigenvalues of the correlation matrix pxp ordered by decreasing values of eigenvalues. If N is missing, we suppose N=[1 2].
  • lambda : is a px2 numerical matrix. In the first column we find the eigenvalues of V, where V is the correlation pxp matrix and in the second column are the ratios of the corresponding eigenvalue over the sum of eigenvalues.
  • facpr : are the principal factors: eigenvectors of V. Each column is an eigenvector element of the dual of R^p.
  • comprinc : are the principal components. Each column (c_i=Xu_i) of this nxn matrix is the M-orthogonal projection of individuals onto principal axis. Each one of this columns is a linear combination of the variables x1, ...,xp with maximum variance under condition u'_iM^(-1)u_i=1

Description

This function performs several computations known as "principal component analysis". It includes drawing of "correlations circle", i.e. in the horizontal axis the correlation values r(c1;xj) and in the vertical r(c2;xj). It is an extension of the pca function.

The idea behind this method is to represent in an approximative manner a cluster of n individuals in a smaller dimensional subspace. In order to do that, it projects the cluster onto a subspace. The choice of the k-dimensional projection subspace is made in such a way that the distances in the projection have a minimal deformation: we are looking for a k-dimensional subspace such that the squares of the distances in the projection is as big as possible (in fact in a projection, distances can only stretch). In other words, inertia of the projection onto the k dimensional subspace must be maximal.

Author

Carlos Klimann

Bibliography

Saporta, Gilbert, Probabilites, Analyse des Donnees et Statistique, Editions Technip, Paris, 1990.


perctl

Scilab Function
Last update : 12/06/2006

perctl - computation of percentils

Calling Sequence

p=perctl(x,y)

Parameters

  • x : real or complex vector or matrix
  • y : vector of positif values between 0 and 100.

Description

Compute the matrix p of percentils (in increasing order, column first) of the real vector or matrix x indicated by the entries of y, the values of entries of y must be positive integers between 0 and 100. p is a matrix whose type is length(y) x 2 and the content of its first column are the percentils values. The contents of its second column are the places of the computed percentiles in the input matrix x.

The minimum or maximum values in x are assigned to percentiles for percent values outside that range.

Examples

// 1st Example

x=[6 7 0 7 10 4 2 2 7 1;
    6 0 5 5 5 2 0 6 8 10;
    8 6 4 3 5 9 8 3 4 7;
    1 3 2 7 6 1 1 4 8 2;
    6 3 5 1 6 5 9 9 5 5;
    1 6 4 4 5 4 0 8 1 8;
    7 1 3 7 8 0 2 8 10 8;
    3 6 1 9 8 5 5 3 2 1;
    5 7 6 2 10 8 7 4 0 8;
    10 3 3 4 8 6 9 4 8 3]
y=[10 20 30]
p=perctl(x,y)

// 2nd example

A = perctl([500 480 460 453 452 452 451 450 450 431 421 420 420 417 416 414 410 410 405 397 380 360 332],90)

Author

Carlos Klimann

Bibliography

HYNDMAN,Rob J. and FAN Yanan, Sample Quantiles in Statistical Packages, The American Statistician, Nov.1996, Vol 50, No.4


quart

Last update : 12/01/2004

quart - computation of quartiles

Calling Sequence

s=quart(x)
s=quart(x,'r') or m=quart(x,1)
s=quart(x,'c') or m=quart(x,2)

Parameters

  • x : real or complex vector or matrix

Description

For a vector or a matrix x, [q]=quart(x,y) returns in the vector q the quartiles of x. [q]=quart(x,'r') (or, equivalently, [q]=quart(x,1)) are the rowwise percentiles. It returns in each column of the matrix q the quartiles of data in the corresponding column of x.

[q]=quart(x,'c') (or, equivalently, [q]=quart(x,2)) are the columnwise quartiles. It returns in each row of the matrix q the quartiles of data in the corresponding row of x.

Examples

x=[6 7 0 7 10 4 2 2 7 1;
   6 0 5 5 5 2 0 6 8 10;
   8 6 4 3 5 9 8 3 4 7;
   1 3 2 7 6 1 1 4 8 2;
   6 3 5 1 6 5 9 9 5 5;
   1 6 4 4 5 4 0 8 1 8;
   7 1 3 7 8 0 2 8 10 8;
   3 6 1 9 8 5 5 3 2 1;
   5 7 6 2 10 8 7 4 0 8;
   10 3 3 4 8 6 9 4 8 3]
q=quart(x)
q=quart(x,'r')
q=quart(x,'c')

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


regress

Last update : 12/01/2004

regress - regression coefficients of two variables

Calling Sequence

coefs=regress(x,y)

Parameters

  • x,y : real or complex vector

Description

This function computes the regresion coefficients of two variables x and y , both numerical vectors of same number of elements n . coefs=[a b] be a 1x2 matrix such that Y=a+bX will be the equation of the ordinary least square approximation to our data.

References

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, J.Wiley & Sons, 1990.

Examples

x=[0.5608486 0.6623569 0.7263507 0.1985144 0.5442573 0.2320748 0.2312237]
y=[0.3616361 0.2922267 0.5664249 0.4826472 0.3321719 0.5935095 0.5015342]
coefs=regress(x,y)

See Also

covar ,

Author

Carlos Klimann


samplef

Scilab Function
Last update : 17/12/2004

samplef - sample with replacement from a population and frequences of his values.

Calling Sequence

s = samplef(n,X,f,orient)

Parameters

  • n : positive integer (size of sample)
  • X : matrix. Samples will be extracted from this matrix
  • f : positive integer matrix with same type than X. It indicates frequences of corresponding values of X.
  • orient : Optional parameter. Admissible values are 1, 2, 'r' or 'c'
  • s : vector or matrix containing sample

Description

This function gives s, a vector of lenght n. It contains a sample of n extractions, with replacement, from the vector (or matrix) X, each element counted with the frequence given by the corresponding value in vector f.

s=samplef(n,X,f) (or s=samplef(n,X,f,'*')) returns a vector s whose values are a random sample of n values from X, each value with a probability to be sampled proportional to the corresponding value of f, extracted with replacement, from X. f must have same lenght than X.

s=samplef(n,X,f,'r') (or, equivalently, s=samplef(n,X,f,1)) returns a matrix of type size(X,'r')xn. It contains a random sample of n rows from X, each row with a probability to be sampled proportional to the corresponding value of f, extracted with replacement, from the rows of X. The lenght of f must be equal to the number of rows of X.

s=samplef(n,X,f,'c') (or, equivalently, s=samplef(n,X,f,2)) returns a matrix of type nxsize(X,'c'). It contains a random sample of n columns from X, each column with a probability to be sampled proportional to the corresponding value of f, extracted with replacement, from the columns of X. The lenght of f must be equal to the number of columns of X.

Examples

   a=[3 7 9;22 4 2]
   f1=[10 1 1 1 1 1]
   f2=[1 ; 15]
   f3=[10 1 1]
   s=samplef(15,a,f1)
   s=samplef(15,a,f2,'r')
   s=samplef(15,a,f3,'c')

See Also

sample , samwr ,

Author

Carlos Klimann


sample

Scilab Function
Last update : 14/10/2003

sample - Sampling with replacement

Calling Sequence

s = sample(n,X,orient)

Parameters

  • n : positive integer (size of sample)
  • X : matrix. Samples will be extracted from this matrix.
  • orient : Optional parameter. Admissible values are 1, 2, 'r' or 'c'
  • s : vector or matrix containing sample

Description

This function gives a vector (or matrix) nx1. It contains a random sample of n extractions, with replacement, from the matrix X.

s=sample(n,X) (or s=sample(n,X,'*')) returns a vector s whose values are a random sample of n values from X, extracted with replacement, from X .

s=sample(n,X,'r') (or, equivalently, s=sample(n,X,1)) returns a matrix of type size(X,'r')xn. It contains a random sample of n rows, extracted with replacement, from the rows of X.

s=sample(n,X,'c') (or, equivalently, s=sample(n,X,2)) returns a matrix of type nxsize(X,'c'). It contains a random sample of n columns, extracted with replacement from the columns of X.

Examples

X=['a' 'dd' 'arreu'; 'ber' 'car' 'zon']
s=sample(25,X)
s=sample(25,X,'r')
s=sample(25,X,'c')

See Also

samplef , samwr ,

Author

Carlos Klimann


samwr

Scilab Function
Last update : 15/01/2004

samwr - Sampling without replacement

Calling Sequence

s = samwr(sizam,numsamp,X)

Parameters

  • sizam : integer. Size of a sample. It must be less or equal than size of X.
  • numsamp : integer. Number of samples to be extracted.
  • X : column vector. It contains the population.
  • s : matrix of type sizsam x numsamp. It contains numsamp random samples (the columns) each of sizam (size(X,'*')) extractions, without replacement, from the column vector X.

Description

Gives samples without replacement from a column vector.

Examples

    a=[0.33 1.24 2.1 1.03]
    s=samwr(4,12,a)

See Also

sample , samplef ,

Author

Carlos Klimann


stdevf

Last update : 12/01/2004

stdevf - standard deviation

Calling Sequence

s=stdevf(x,fre)
s=stdevf(x,fre,'r') or s=stdevf(x,fre,1)
s=stdevf(x,fre,'c') or s=stdevf(x,fre,2)

Parameters

  • x real or complex vector or matrix

Description

This function computes the standard deviation of the values of a vector or matrix x , each of them counted with a frequency given by the corresponding values of the integer vector or matrix fre who has the same type of x .

For a vector or matrix x , s=stdevf(x,fre) (or s=stdevf(x,fre,'*') returns in scalar s the standard deviation of all the entries of x , each value counted with the multiplicity indicated by the corresponding value of fre .

s=stdevf(x,fre,'r') (or, equivalently, s=stdevf(x,fre,1) ) returns in each entry of the row vector s of type 1xsize(x,'c') the standard deviation of each column of x , each value counted with the multiplicity indicated by the corresponding value of fre .

s=stdevf(x,fre,'c') (or, equivalently, s=stdevf(x,fre,2) ) returns in each entry of the column vector s of type size(x,'c')x1 the standard deviation of each row of x , each value counted with the multiplicity indicated by the corresponding value of fre .

Examples

x=[0.2113249 0.0002211 0.6653811;0.7560439 0.9546254 0.6283918]
fre=[1 2 3;3 4 3]
m=stdevf(x,fre)
m=stdevf(x,fre,'r')
m=stdevf(x,fre,'c')

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


strange

Last update : 12/01/2004

strange - range

Calling Sequence

[r]=strange(x)
[r]=strange(x,'r') (or, equivalently, [r]=strange(x,1))
[r]=strange(x,'c') (or, equivalently, [r]=strange(x,2))

Parameters

  • x : real or complex vector or matrix

Description

The range is the distance between the largest and smaller value, [r]=strange(x) computes the range of vector or matrix x.

[r]=strange(x,'r') (or equivalently [r]=strange(x,1)) give a row vector with the range of each column.

[r]=strange(x,'c') (or equivalently [r]=strange(x,2)) give a column vector with the range of each row.

References

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, J.Wiley & Sons, 1990.

Author

Carlos klimann


st_deviationstdev

Scilab Function
Last update : 16/06/2004

st_deviation - écart-type des termes d'une matrice

stdev - écart-type des termes d'une matrice

Calling Sequence

y=st_deviation(x)
y=st_deviation(x,'r')
y=st_deviation(x,'c')
y=stdev(x)
y=stdev(x,'r')
y=stdev(x,'c')

Parameters

  • x : vecteur ou matrice réelle
  • y : scalaire ou vecteur

Description

st_deviation calcule l'estimateur sans biais de l'écart-type (normalisé par N-1, ou N est le nombre d'échantillons).

Pour un vecteur ou une matrice x , y=st_deviation(x) renvoie dans y l'écart-type des termes de x .

y=st_deviation(x,'r') (ou y=st_deviation(x,1) ) est l'écart-type suivant l'indice de ligne. Chaque composante du vecteur ligne y contient l'écart-type de chaque colonne de x .

y=st_deviation(x,'c') (ou y=st_deviation(x,2) ) est l'écart-type selon l'indice de colonne. Chaque composante du vecteur colonne y contient l'écart-type de chaque ligne de x .

Examples

A=[1,2,10;7,7.1,7.01];
st_deviation(A)
st_deviation(A,'r')
st_deviation(A,'c')

See Also

sum , median , mean , nanstdev , stdevf ,


tabul

Last update : 12/01/2004

tabul - frequency of values of a matrix or vector

Calling Sequence

[m]=tabul(X [,order])

Parameters

  • X : vector or matrix (of real or complex numbers or strings)
  • order : (optionnal) a character equal to "d" or "i" (default value "d")
  • m : a 2 columns matrix (if X is a numerical vector or matrix) or a list with 2 members (if X is a string vector or matrix).

Description

This function computes the frequency of values of the components of a vector or matrix X of numbers or string characters :

if X is a numerical vector or matrixthen m is a two column matrix who contains in the first column the distinct values of X and in the other column the number of occurrences of those values (m(i,2) is the number of occurrences of m(i,1)).
if X is a string vector or matrixthen m is a list whose first member is a string (column) vector composed with the distinct values of X and the second member is a (column) vector whose components are the number of occurrences of those values ( m(i)(2) is the number of occurrences of the string m(i)(1) ).

The optional parameter order must be "d" or "i" (by default order="d") and gives the order (decreasing or increasing) the distinct values of X will be sorted.

Examples

// first example
X = [2 8 0 3 7 6 8 7 9 1 6 7 7 2 5 2 2 2 9 7]
m1 = tabul(X)
m2 = tabul(X, "i")

// second example
X = ["ba" "baba" "a" "A" "AA" "a" "aa" "aa" "aa" "A" "ba"]
m = tabul(X,"i")

// third example
n = 50000;
X = grand(n,1,"bin",70,0.5);
m = tabul(X,"i");
xbasc()
plot2d3(m(:,1), m(:,2)/n)
xtitle("empiral probabilities of B(70,0.5)")

// last example : computes the occurrences of words of the scilab license
text = read(SCI+"/license.txt",-1,1,"(A)"); // read the scilab license
bigstr = strcat(text," ");                  // put all the lines in a big string
sep =  [" " "," "." ";" "*" ":" "-" """"];  // words separators
words = tokens(bigstr, sep);                // cut the big string into words
m = tabul(words);                           // computes occurrences of each word
[occ , p] = sort(m(2));                     // sort by decreasing frequencies
results = [m(1)(p) string(occ)]             // display result

See Also

dsearch , histplot ,

Authors

Carlos Klimann (original author)
J.S. Giet and B. Pincon (new version)

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


thrownan

Last update : 12/01/2004

thrownan - eliminates nan values

Calling Sequence

[nonan,numb]=thrownan(x)

Parameters

  • x : real or complex vector or matrix

Description

This function returns in vector nonan the values (ignoring the NANs) of a vector or matrix x and in the corresponding places of vector numb the indexes of the value.

For a vector or matrix x , [nonan,numb]=thrownan(x) considers x , whatever his dimensions are, like a vector (columns first).

In Labostat, NAN values stand for missing values in tables.

Examples

x=[0.2113249 %nan 0.6653811;0.7560439 0.3303271 0.6283918]
[nonan numb]=thrownan(x)

Author

Carlos Klimann


trimmean

Last update : 12/01/2004

trimmean - trimmed mean of a vector or a matrix

Calling Sequence

m=trimmean(x)
m=trimmean(x,discard,'r') or m=trimmean(x,discard,1)
m=trimmean(x,discard,'c') or m=trimmean(x,discard,2)

Parameters

  • x real or complex vector or matrix
  • discard number: The discarding percentage

Description

A trimmed mean is calculated by discarding a certain percentage of the lowest and the highest scores and then computing the mean of the remaining scores. For example, a mean trimmed 50% is computed by discarding the lower and higher 25% of the scores and taking the mean of the remaining scores.

The median is the mean trimmed 100% and the arithmetic mean is the mean trimmed 0%.

A trimmed mean is obviously less susceptible to the effects of extreme scores than is the arithmetic mean. It is therefore less susceptible to sampling fluctuation than the mean for extremely skewed distributions. It is less efficient (The efficiency of a statistic is the degree to which the statistic is stable from sample to sample. That is, the less subject to sampling fluctuation a statistic is, the more efficient it is. The efficiency of statistics is measured relative to the efficiency of other statistics and is therefore often called the relative efficiency. If statistic A has a smaller standard error than statistic B, then statistic A is more efficient than statistic B. The relative efficiency of two statistics may depend on the distribution involved. For instance, the mean is more efficient than the median for normal distributions but not for some extremely skewed distributions. The efficiency of a statistic can also be thought of as the precision of the estimate: The more efficient the statistic, the more precise the statistic is as an estimator of the parameter.[from http://davidmlane.com/hyperstat/A12977.html]) than the mean for normal distributions.

Trimmed means are often used in Olympic scoring to minimize the effects of extreme ratings possibly caused by biased judges. [from http://davidmlane.com/hyperstat/A11971.html]

For a vector or matrix x , t=trimmean(x,discard) returns in scalar t the mean of all the entries of x , after discarding discard/2 highest values and discard/2 lowest values.

t=trimmean(x,discard,'r') (or, equivalently, t=trimmean(x,discard,1) ) returns in each entry of the row vector t the trimmed mean of each column of x .

t=trimmean(x,discard,'c') (or, equivalently, t=trimmean(x,discard,2) ) returns in each entry of the column vector t the trimmed mean of each row of x .

This function computes the trimmed mean of a vector or matrix x .

For a vector or matrix x , m=trimmean(x) returns in scalar m the trimmedmean of all the entries of x .

m=trimmean(x,'r') (or, equivalently, m=trimmean(x,1) ) returns in each entry of the row vector m the trimmed mean of each column of x .

q m=trimmean(x,'c') (or, equivalently, m=trimmean(x,2) ) returns in each entry of the column vector m the trimmed mean of each row of x .

References

Luis Angel Garcia-Escudero and Alfonso Gordaliza, Robustness Properties of Means and Trimmed Means, JASA, Volume 94, Number 447, Sept 1999, pp956-969

Author

Carlos Klimann


variancef

Last update : 12/01/2004

variancef - standard deviation of the values of a vector or matrix

Calling Sequence

s=variancef(x,fre)
s=variancef(x,fre,'r') or s=variancef(x,fre,1)
s=variancef(x,fre,'c') or s=variancef(x,fre,2)

Parameters

  • x : real or complex vector or matrix

Description

This function computes the variance of the values of a vector or matrix x , each of them counted with a frequency signaled by the corresponding values of the integer vector or matrix fre with the same type of x .

For a vector or matrix x , s=variancef(x,fre) (or s=variancef(x,fre,'*') ) returns in scalar s the variance of all the entries of x , each value counted with the multiplicity indicated by the corresponding value of fre .

s=variancef(x,fre,'r') (or, equivalently, s=variancef(x,fre,1) ) returns in each entry of the row vector s of type 1xsize(x,'c') the variance of each column of x , each value counted with the multiplicity indicated by the corresponding value of fre .

s=variancef(x,fre,'c') (or, equivalently, s=variancef(x,fre,2) ) returns in each entry of the column vector s of type size(x,'c') x1 the variance of each row of x , each value counted with the multiplicity indicated by the corresponding value of fre .

Examples

x=[0.2113249 0.0002211 0.6653811;0.7560439 0.9546254 0.6283918]
fre=[1 2 3;3 4 3]
m=variancef(x,fre)
m=variancef(x,fre,'r')
m=variancef(x,fre,'c')

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


variance

Last update : 12/01/2004

variance - variance of the values of a vector or matrix

Calling Sequence

s=variance(x)
s=variance(x,'r') or m=variance(x,1)
s=variance(x,'c') or m=variance(x,2)

Parameters

  • x : real or complex vector or matrix

Description

This function computes the variance of the values of a vector or matrix x .

For a vector or a matrix x , s=variance(x) returns in the scalar s the variance of all the entries of x .

s=variance(x,'r') (or, equivalently, s=variance(x,1) ) is the rowwise variance. It returns in each entry of the row vector s the variance of each column of x .

s=variance(x,'c') (or, equivalently, s=variance(x,2) ) is the columnwise standard deviation. It returns in each entry of the column vector s the variance of each row of x .

Examples

x=[0.2113249 0.0002211 0.6653811;0.7560439 0.4453586 0.6283918]
s=variance(x)
s=variance(x,'r')
s=variance(x,'c')

Author

Carlos Klimann

Bibliography

Wonacott, T.H. & Wonacott, R.J.; Introductory Statistics, fifth edition, J.Wiley & Sons, 1990.


Fonctions de distributions statistiques
cdfbet - fonction de répartition de la distribution Beta
cdfbin - fonction de répartition de la distribution binomiale
cdfchi - fonction de répartition de la distribution du chi-deux
cdfchn - fonction de répartition de la distribution du chi-deux non centrée
cdff - fonction de répartition de la distribution de Fisher
cdffnc - fonction de répartition de la distribution de Fisher non centrée
cdfgam - fonction de répartition de la distribution gamma
cdfnbn - fonction de répartition de la distribution binomiale négative
cdfnor - fonction de répartition de la distribution normale
cdfpoi - fonction de répartition de la distribution de Poisson
cdft - fonction de répartition de la distribution de Student
grand - Générateur(s) de nombres pseudo-aléatoires


cdfbet

Scilab Function
Last update : 16/06/2004

cdfbet - fonction de répartition de la distribution Beta

Calling Sequence

[P,Q]=cdfbet("PQ",X,Y,A,B)
[X,Y]=cdfbet("XY",A,B,P,Q)
[A]=cdfbet("A",B,P,Q,X,Y)
[B]=cdfbet("B",P,Q,X,Y,A)

Parameters

  • P,Q,X,Y,A,B : cinq vecteurs réels de même taille.
  • P,Q (Q=1-P) : L'intégrale de 0 à X de la distribution beta (En entrée : [0, 1].)
  • Q : 1-P
  • X,Y (Y=1-X) : Borne supérieure d'intégration (En entrée : [0,1], En recherche : [0,1]) A,B : Les deux paramètres de la densité (En entrée: (0,+infini), En recherche : [1D-300,1D300] )

Description

Étant donnés les autres, calcule un paramètre de la distribution beta (la distribution Beta est proportionnelle à t^(A-1) * (1-t)^(B-1) ).

La fonction de répartition (P) est calculée directement par le code associé à la référence

DiDinato, A. R. and Morris, A. H. Algorithm 708: Significant Digit Computation of the Incomplete Beta Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.

Le calcul des autres paramètres implique une recherche d'une valeur conduisant à la valeur désirée pour P. La recherche dépend de la monotonicité de P par rapport aux autres paramètres.

Tiré de la librairie DCDFLIB: Library of Fortran Routines for Cumulative Distribution Functions, Inverses, and Other Parameters (February, 1994) Barry W. Brown, James Lovato and Kathy Russell. The University of Texas.


cdfbin

Scilab Function
Last update : 16/06/2004

cdfbin - fonction de répartition de la distribution binomiale

Calling Sequence

[P,Q]=cdfbin("PQ",S,Xn,Pr,Ompr)
[S]=cdfbin("S",Xn,Pr,Ompr,P,Q)
[Xn]=cdfbin("Xn",Pr,Ompr,P,Q,S)
[Pr,Ompr]=cdfbin("PrOmpr",P,Q,S,Xn)

Parameters

  • P,Q,S,Xn,Pr,Ompr : six vecteurs réels de même taille.
  • P,Q (Q=1-P) : La somme de 0 à S de la distribution (Probabilité de S succès ou moins en XN essais de probabilité de succès PR) En entrée : [0,1].
  • S : Le nombre de succès observés En entrée : [0, XN] En recherche : [0, XN]
  • Xn : Le nombre d'essais binomiaux En entrée : (0, +infini). En recherche : [1E-300, 1E300]
  • Pr,Ompr (Ompr=1-Pr) : La probabilité de succès de chaque essai En entrée : [0,1]. En recherche : [0,1]

Description

Étant donnés les autres, calcule un paramètre de la distribution binomiale

La formule 26.5.24 de Abramowitz et Stegun, Handbook of Mathematical Functions (1966) est utilisée pour réduire le calcul de la fonction de répartition de la distribution à celle d'une loi beta incomplète.

Le calcul des autres paramètres implique une recherche d'une valeur conduisant à la valeur désirée pour P. La recherche dépend de la monotonicité de P par rapport aux autres paramètres.

Tiré de la librairie DCDFLIB: Library of Fortran Routines for Cumulative Distribution Functions, Inverses, and Other Parameters (February, 1994) Barry W. Brown, James Lovato and Kathy Russell. The University of Texas.


cdfchi

Scilab Function
Last update : 16/06/2004

cdfchi - fonction de répartition de la distribution du chi-deux

Calling Sequence

[P,Q]=cdfchi("PQ",X,Df)
[X]=cdfchi("X",Df,P,Q);
[Df]=cdfchi("Df",P,Q,X)

Parameters

  • P,Q,Xn,Df : 4 vecteurs réels de même taille.
  • P,Q (Q=1-P) : L'intégrale de 0 à X de la distribution En entrée : [0, 1].
  • X : Borne supérieure d'intégration En entrée : [0, +infini). En recherche : [0,1E300]
  • Df : degrés de liberté de la distribution. En entrée : (0, +infini). En recherche : [ 1E-300, 1E300]

Description

Étant donnés les autres, calcule un paramètre de la distribution du chi-deux.

La formule 26.4.19 de Abramowitz et Stegun, Handbook of Mathematical Functions (1966) est utilisée pour réduire le calcul de la fonction de répartition de la distribution à celle d'une loi incomplète.

Le calcul des autres paramètres implique une recherche d'une valeur conduisant à la valeur désirée pour P. La recherche dépend de la monotonicité de P par rapport aux autres paramètres.

Tiré de la librairie DCDFLIB: Library of Fortran Routines for Cumulative Distribution Functions, Inverses, and Other Parameters (February, 1994) Barry W. Brown, James Lovato and Kathy Russell. The University of Texas.


cdfchn

Scilab Function
Last update : 16/06/2004

cdfchn - fonction de répartition de la distribution du chi-deux non centrée

Calling Sequence

[P,Q]=cdfchn("PQ",X,Df,Pnonc)
[X]=cdfchn("X",Df,Pnonc,P,Q);
[Df]=cdfchn("Df",Pnonc,P,Q,X)
[Pnonc]=cdfchn("Pnonc",P,Q,X,Df)

Parameters

  • P,Q,X,Df,Pnonc : 5 vecteurs réels de même taille.
  • P,Q (Q=1-P) : L'intégrale de 0 à X de la distribution. En entrée : [0, 1-1E-16).
  • X : Borne supérieure d'intégration En entrée : [0, +infini). En recherche : [0,1E300]
  • Df : Degrés de liberté de la densité En entrée : (0, +infini). En recherche : [ 1E-300, 1E300]
  • Pnonc : paramètre de décentrage En entrée : [0, +infini). En recherche : [0,1E4]

Description

Étant donnés les autres, calcule un paramètre de la distribution du chi-deux non-centré.

La formule 26.4.25 de "Abramowitz and Stegun, Handbook of Mathematical Functions (1966)" est utilisée pour le calcul de la fonction de répartition.

Le calcul des autres paramètres implique une recherche d'une valeur conduisant à la valeur désirée pour P. La recherche dépend de la monotonicité de P par rapport aux autres paramètres.

Le temps de calcul est proportionnel au paramètre de décentrage. La plage de recherche est bornée par 10,000 pour limiter le temps de calcul (pouvant devenir énorme pour des grandes valeurs de Pnonc).

Tiré de la librairie DCDFLIB: Library of Fortran Routines for Cumulative Distribution Functions, Inverses, and Other Parameters (February, 1994) Barry W. Brown, James Lovato and Kathy Russell. The University of Texas.


cdffnc

Scilab Function
Last update : 16/06/2004

cdffnc - fonction de répartition de la distribution de Fisher non centrée

Calling Sequence

[P,Q]=cdffnc("PQ",F,Dfn,Dfd,Pnonc)
[F]=cdffnc("F",Dfn,Dfd,Pnonc,P,Q);
[Dfn]=cdffnc("Dfn",Dfd,Pnonc,P,Q,F);
[Dfd]=cdffnc("Dfd",Pnonc,P,Q,F,Dfn)
[Pnonc]=cdffnc("Pnonc",P,Q,F,Dfn,Dfd);

Parameters

  • P,Q,F,Dfn,Dfd,Pnonc : six vecteurs réels de même taille.
  • P,Q (Q=1-P) Intégrale de 0 à F de la densité En entrée : [0,1-1E-16).
  • F : Borne supérieure d'intégration En entrée : [0, +infini). En recherche : [0,1E300]
  • Dfn : Degrés de liberté de la somme de carrés au numérateur En entrée : (0, +infini). En recherche : [ 1E-300, 1E300]
  • Dfd : Degrés de liberté de la somme de carrés au dénominateur Dans l'intervalle: (0, +infini). En entrée : (0, +infini). En recherche : [ 1E-300, 1E300]
  • Pnonc : Paramètre de décentrage En entrée : [0,infini) En recherche : [0,1E4]

Description

Étant donnés les autres, calcule un paramètre de la distribution de Fisher non-centré

La formule 26.6.20 de Abramowitz and Stegun, Handbook of Mathematical Functions (1966) est utilisée pour le calcul de la fonction de répartition.

Le calcul des autres paramètres implique une recherche d'une valeur conduisant à la valeur désirée pour P. La recherche dépend de la monotonicité de P par rapport aux autres paramètres.

Le temps de calcul est proportionnel au paramètre de décentrage. La plage de recherche est bornée par 10,000 pour limiter le temps de calcul (pouvant devenir énorme pour des grandes valeurs de Pnonc).

La valeur de la fonction de répartition de la distribution de Fisher n'est pas monotone. Il peut y avoir deux valeurs du paramètre donnant une valeur de donnée de la fonction de répartition. Cette fonction suppose qu'elle est monotone et renvoie arbitrairement une des deux valeurs.

Tiré de la librairie DCDFLIB: Library of Fortran Routines for Cumulative Distribution Functions, Inverses, and Other Parameters (February, 1994) Barry W. Brown, James Lovato and Kathy Russell. The University of Texas.


cdff

Scilab Function
Last update : 16/06/2004

cdff - fonction de répartition de la distribution de Fisher

Calling Sequence

[P,Q]=cdff("PQ",F,Dfn,Dfd)
[F]=cdff("F",Dfn,Dfd,P,Q);
[Dfn]=cdff("Dfn",Dfd,P,Q,F);
[Dfd]=cdff("Dfd",P,Q,F,Dfn)

Parameters

  • P,Q,F,Dfn,Dfd : 5 vecteurs réels de même taille.
  • P,Q (Q=1-P) : Intégrale de 0 à F de la densité En entrée : [0,1].
  • F : Borne supérieure d'intégration En entrée : [0, +infini). En recherche : [0,1E300]
  • Dfn : Degrés de liberté de la somme des carrés au numérateur En entrée : (0, +infini). En recherche : [ 1E-300, 1E300]
  • Dfd : Degrés de liberté de la somme des carrés au dénominateur En entrée : (0, +infini). En recherche : [ 1E-300, 1E300]

Description

Étant donnés les autres, calcule un paramètre de la distribution de Fisher.

La formule 26.6.2 de Abramowitz et Stegun, Handbook of Mathematical Functions (1966) est utilisée pour réduire le calcul de la fonction de répartition de la distribution à celle d'une loi beta incomplète.

Le calcul des autres paramètres implique une recherche d'une valeur conduisant à la valeur désirée pour P. La recherche dépend de la monotonicité de P par rapport aux autres paramètres.

La valeur de la fonction de répartition de la distribution de Fisher n'est pas monotone. Il peut y avoir deux valeurs du paramètre donnant une valeur de donnée de la fonction de répartition. Cette fonction suppose qu'elle est monotone et renvoie arbitrairement une des deux valeurs.

Tiré de la librairie DCDFLIB: Library of Fortran Routines for Cumulative Distribution Functions, Inverses, and Other Parameters (February, 1994) Barry W. Brown, James Lovato and Kathy Russell. The University of Texas.


cdfgam

Scilab Function
Last update : 16/06/2004

cdfgam - fonction de répartition de la distribution gamma

Calling Sequence

[P,Q]=cdfgam("PQ",X,Shape,Scale)
[X]=cdfgam("X",Shape,Scale,P,Q)
[Shape]=cdfgam("Shape",Scale,P,Q,X)
[Scale]=cdfgam("Scale",P,Q,X,Shape)

Parameters

  • P,Q,X,Shape,Scale : 5 vecteurs réels de même taille.
  • P,Q (Q=1-P) : L'intégrale de 0 à X de la distribution gamma En entrée : [0,1].
  • X : Borne supérieure d'intégration En entrée : [0, +infini). En recherche : [0,1E300]
  • Shape : Le paramètre de forme de la distribution En entrée : (0, +infini). En recherche : [1E-300,1E300]
  • Scale : le paramètre d'échelle de la distribution En entrée : (0, +infini). En recherche : (1E-300,1E300]

Description

Étant donnés les autres, calcule un paramètre de la distribution gamma.

La fonction de répartition (P) est calculée directement par le code associé à

DiDinato, A. R. and Morris, A. H. Computation of the incomplete gamma function ratios and their inverse. ACM Trans. Math. Softw. 12 (1986), 377-393.

Le calcul des autres paramètres implique une recherche d'une valeur conduisant à la valeur désirée pour P. La recherche dépend de la monotonicité de P par rapport aux autres paramètres.

La distribution gamma est proportionnelle à T**(SHAPE - 1) * EXP(- SCALE * T)

Tiré de la librairie DCDFLIB: Library of Fortran Routines for Cumulative Distribution Functions, Inverses, and Other Parameters (February, 1994) Barry W. Brown, James Lovato and Kathy Russell. The University of Texas.


cdfnbn

Scilab Function
Last update : 16/06/2004

cdfnbn - fonction de répartition de la distribution binomiale négative

Calling Sequence

[P,Q]=cdfnbn("PQ",S,Xn,Pr,Ompr)
[S]=cdfnbn("S",Xn,Pr,Ompr,P,Q)
[Xn]=cdfnbn("Xn",Pr,Ompr,P,Q,S)
[Pr,Ompr]=cdfnbn("PrOmpr",P,Q,S,Xn)

Parameters

  • P,Q,S,Xn,Pr,Ompr : six vecteurs réels de même taille.
  • P,Q (Q=1-P) : La somme de 0 à S de la distribution binomiale négative En entrée : [0,1].
  • S : Borne supérieure de la somme Il y a F (ou moins) échecs avant le Xième succès. En entrée : [0, +infini). En recherche : [0, 1E300]
  • Xn : Le nombre de succès. En entrée : [0, +infini). En recherche : [0, 1E300]
  • Pr : La probabilité de succès pour chaque essai binomial En entrée : [0,1]. En recherche : [0,1].
  • Ompr : 1-PR En entrée : [0,1]. En recherche : [0,1] PR + OMPR = 1.0

Description

Étant donnés les autres, calcule un paramètre de la distribution binomiale négative.

Cette distribution renvoie la probabilité d'avoir F échecs ou moins avant un succès dans des essais binomiaux, où la probabilité de succès est PR.

Les termes individuels sont égaux à la probabilité de S échecs avant XN succès qui est égale à Choisir( S, XN+S-1 ) * PR^(XN) * (1-PR)^S

La formule 26.5.26 de Abramowitz et Stegun, Handbook of Mathematical Functions (1966) est utilisée pour réduire le calcul de la fonction de répartition de la distribution à celle d'une loi beta incomplète.

Le calcul des autres paramètres implique une recherche d'une valeur conduisant à la valeur désirée pour P. La recherche dépend de la monotonicité de P par rapport aux autres paramètres.

Tiré de la librairie DCDFLIB: Library of Fortran Routines for Cumulative Distribution Functions, Inverses, and Other Parameters (February, 1994) Barry W. Brown, James Lovato and Kathy Russell. The University of Texas.


cdfnor

Scilab Function
Last update : 16/06/2004

cdfnor - fonction de répartition de la distribution normale

Calling Sequence

[P,Q]=cdfnor("PQ",X,Mean,Std)
[X]=cdfnor("X",Mean,Std,P,Q)
[Mean]=cdfnor("Mean",Std,P,Q,X)
[Std]=cdfnor("Std",P,Q,X,Mean)

Parameters

  • P,Q,X,Mean,Std : six vecteurs réels de même taille.
  • P,Q (Q=1-P) : L'intégrale de -infini à X de la densité normale En entrée : (0,1].
  • X : Borne supérieure d'intégration En entrée : ( -infini, +infini)
  • Mean : moyenne de la densité En entrée : (-infini, +infini)
  • Sd : écart-type de la densité En entrée : (0, +infini).

Description

Étant donnés les autres, calcule un paramètre de la distribution normale.

Une version légèrement modifiée de ANORM :

Cody, W.D. (1993). "ALGORITHM 715: SPECFUN - A Portable FORTRAN Package of Special Function Routines and Test Drivers" acm Transactions on Mathematical Software. 19, 22-32.

est utilisée.

Les fonctions rationnelles des pages 90-95 de

Kennedy and Gentle, Statistical Computing, Marcel Dekker, NY, 1980

sont utilisées comme valeurs de départ pour les itérations de Newton calculant l'inverse de la distribution. Aucune recherche n'est donc nécessaire pour aucun des paramètres.

Pour X < -15, le développement asymptotique de la loi normale est utilisé comme valeur de départ pour trouver l'inverse. Il s'agit de la formule 26.2.12 de Abramowitz et Stegun.

La densité normale est proportionnelle à exp( - 0.5 * (( X - MEAN)/SD)**2)

Tiré de la librairie DCDFLIB: Library of Fortran Routines for Cumulative Distribution Functions, Inverses, and Other Parameters (February, 1994) Barry W. Brown, James Lovato and Kathy Russell. The University of Texas.


cdfpoi

Scilab Function
Last update : 16/06/2004

cdfpoi - fonction de répartition de la distribution de Poisson

Calling Sequence

[P,Q]=cdfpoi("PQ",S,Xlam)
[S]=cdfpoi("S",Xlam,P,Q)
[Xlam]=cdfpoi("Xlam",P,Q,S);

Parameters

  • P,Q,S,Xlam : 4 vecteurs réels de même taille.
  • P,Q (Q=1-P) : La somme de 0 à S de la densité de Poisson. En entrée : [0,1].
  • S : Borne supérieure de la somme. En entrée : [0, +infini). En recherche : [0,1E300]
  • Xlam : Moyenne de la distribution. En entrée : [0, +infini). En recherche : [0,1E300]

Description

Étant donnés les autres, calcule un paramètre de la distribution de Poisson.

La formule 26.4.21 de Abramowitz et Stegun, Handbook of Mathematical Functions (1966) est utilisée pour réduire le calcul de la fonction de répartition de la distribution à celle d'une loi gamma incomplète.

Tiré de la librairie DCDFLIB: Library of Fortran Routines for Cumulative Distribution Functions, Inverses, and Other Parameters (February, 1994) Barry W. Brown, James Lovato and Kathy Russell. The University of Texas.


cdft

Scilab Function
Last update : 16/06/2004

cdft - fonction de répartition de la distribution de Student

Calling Sequence

[P,Q]=cdft("PQ",T,Df)
[T]=cdft("T",Df,P,Q)
[Df]=cdft("Df",P,Q,T)

Parameters

  • P,Q,T,Df : six vecteurs réels de même taille.
  • P,Q (Q=1-P) : l'intégrale de -infini à T de la densité de Student. comprise entre : (0,1].
  • T : borne d'intégration supérieure. En entrée : ( -infini, +infini). En recherche : [ -1E150, 1E150 ]
  • DF: Degrés de libertés de la distribution. En entrée : (0 , +infini). En recherche : [1e-300, 1E10]

Description

Étant donnés les autres, calcule un paramètre de la distribution de Student.

La formule 26.5.27 de Abramowitz et Stegun, Handbook of Mathematical Functions (1966) est utilisée pour réduire le calcul de la fonction de répartition de la distribution à celle d'une loi beta incomplète.

Le calcul des autres paramètres implique une recherche d'une valeur conduisant à la valeur désirée pour P. La recherche dépend de la monotonicité de P par rapport aux autres paramètres.


grand

Scilab Function
Last update : 11/04/2005

grand - Générateur(s) de nombres pseudo-aléatoires

Calling Sequence

Y=grand(m, n, dist_type [,p1,...,pk])
Y=grand(X, dist_type [,p1,...,pk])
Y=grand(n, dist_type [,p1,...,pk])
S=grand(action [,q1,....,ql])

Parameters

  • m, n : entiers, dimensions de la matrice de nombres aléatoires à obtenir Y
  • X : une matrice (ou un vecteur) dont seules les dimensions ( m x n ) sont utilisées
  • dist_type : chaîne de caractères donnant la loi de distribution des nombres aléatoires ('bin', 'nor', 'poi', etc ...)
  • p1, ..., pk : les (éventuels) paramètres de la distribution dist_type
  • Y : la matrice de nombres aléatoires m x n
  • action : chaîne de caractères spécifiant l'action à entreprendre sur le générateur de base ('setgen' pour changer le générateur courant, 'getgen' pour obtenir le nom du générateur courant, 'getsd' pour obtenir l'état du générateur courant, etc...).
  • q1, ..., ql : les paramètres (éventuels) de l'action à effectuer sur le générateur de base.
  • S : résultat de l'action (en général une chaîne ou un vecteur colonne)

Description

Cette fonction peut être utilisée pour générer des nombres pseudo-aléatoires à partir d'une loi de distribution donnée (binomiale, uniforme, normale,...) : ces nombres peuvent être considérés comme des réalisations de variables aléatoires indépendantes qui suivent la loi donnée. Dans ce cas vous devez appliquer l'une des trois premières séquences d'appel pour obtenir une matrice m x n de tels nombres. La deuxième séquence est équivalente à la première si X est une matrice m x n et la troisième forme s'applique lorsque la loi est vectorielle (comme la loi multinomiale) : une réalisation correspond alors à un vecteur colonne (de dimension m ) et l'on obtient ainsi n réalisations sous la forme d'une matrice m x n .

La dernière forme d'appel s'utilise pour entreprendre diverses actions sur le générateur de base (depuis la version 2.7 vous pouvez choisir parmi plusieurs générateurs comme Mersenne-Twister, KISS, clcg4, ...). Ces générateurs fournissent des entiers selon une loi uniforme sur un intervalle très grand (distribution lgi), les autres types de lois s'obtenant à partir de ces générateurs de base (en général suivant un schéma lgi -> U([0,1)) -> distribution cherchée).

Générer des nombres aléatoires selon une loi donnée

  • beta : Y=grand(m,n,'bet',A,B) génère des nombres aléatoires suivant la loi beta de paramètres A and B . La densité de cette loi est ( 0 < x < 1 ) :
              A-1    B-1
         x   (1-x)   / beta(A,B)  ( beta(A,B) = gamma(A+B) / (gamma(A) gamma(B)) )
    A et B devant être des réels > 10^(-37). Fonction(s) associée(s) : cdfbet .
  • binomiale : Y=grand(m,n,'bin',N,p) génère des nombres aléatoires suivant la loi binomiale de paramètres N (entier str. positif) et p (réel de [0,1]) : nombre de succès au cours de N épreuves de Bernouilli de probabilité de succès p . Fonction(s) associée(s) : binomial , cdfbin .
  • binomiale négative : Y=grand(m,n,'nbn',N,p) génère des nombres aléatoires suivant la loi binomiale négative de paramètres N (entier str. positif) et p (réel de ]0,1[) : nombre d'échecs avant d'obtenir N succès dans des épreuves de Bernouilli de probabilité de succès p . Fonction(s) associée(s) : cdfnbn .
  • chi 2 : Y=grand(m,n,'chi', Df) génère des nombres aléatoires suivant la loi du chi 2 à Df (réel > 0.0) degrés de liberté. Fonction(s) associée(s) : cdfchi .
  • chi 2 non centrée : Y=grand(m,n,'nch',Df,Xnon) génère des nombres aléatoires suivant la loi du chi 2 non centrée à Df degrés de liberté (réel >= 1.0) le paramètre de décentrage étant Xnonc (réel >= 0.0). Fonction(s) associée(s) : cdfchn .
  • exponentielle : Y=grand(m,n,'exp',Av) génère des nombres aléatoires suivant la loi exponentielle de moyenne Av (réel >= 0.0).
  • F variance ratio : Y=grand(m,n,'f',Dfn,Dfd) génère des nombres aléatoires suivant la loi F (variance ratio) à Dfn (réel > 0.0) degrés de liberté au numérateur et Dfd (réel > 0.0) degrés de liberté au dénominateur. Fonction(s) associée(s) : cdff .
  • non central F variance ratio : Y=grand(m,n,'nf',Dfn,Dfd,Xnon) génère des nombres aléatoires suivant la loi F (variance ratio) non centrée à Dfn (réel >= 1) degrés de liberté au numérateur, et Dfd (réel > 0) degrés de liberté au dénominateur, Xnonc (réel >= 0) étant le paramètre de décentrage. Fonction(s) associée(s) : cdffnc .
  • gamma : Y=grand(m,n,'gam',shape,scale) génère des nombres aléatoires suivant la loi gamma de paramètres shape (réel > 0) et scale (réel > 0). La densité est :
                   shape  (shape-1)   -scale x
          scale       x          e          /  gamma(shape)
    Fonction(s) associée(s) : gamma , cdfgam .
  • Gauss Laplace (normale) : Y=grand(m,n,'nor',Av,Sd) génère des nombres aléatoires suivant la loi normale de moyenne Av (réel) et d'écart type Sd (réel >= 0). Fonction(s) associée(s) : cdfnor , erf .
  • multi normale : Y=grand(n,'mn',Mean,Cov) génère n réalisations indépendantes de la loi multi-normale ; Mean doit être un vecteur m x 1 et Cov une matrice m x m symétrique et définie positive, ( Y est alors une matrice m x n ).
  • geometrique : Y=grand(m,n,'geom', p) génère des nombres aléatoires suivant la loi geométrique de paramètre p : nombre d'épreuves de Bernouilli (de probabilité de succès p ) jusqu'à obtenir un succès ( p doit appartenir à l'intervalle [pmin,1] (avec pmin = 1.3 10^(-307) ).
  • markov : Y=grand(n,'markov',P,x0) génère n états successifs d'une chaîne de Markov décrite par la matrice de transition P . L'état initial est donné par x0 . Si x0 est une matrice de taille m=size(x0,'*') alors Y est une matrice de taille m x n . Y(i,:) étant le chemin à partir de l'état initial x0(i) .
  • multinomiale : Y=grand(n,'mul',nb,P) génère n réalisations indépendantes de la loi Multinomiale : classer nb éventualités dans m catégories (mettre nb "boules" dans m "boites"). P(i) étant la probabilité qu'une éventualité soit de categorie i. P le vecteur des probabilités est de taille m-1 (la probabilté de la catégorie m étant 1-sum(P) ). Y est alors de dimensions m x n , chaque colonne Y(:,j) étant une réalisation de cette loi : Y(i,j) est le nombre d'éventualités classées en catégorie i pour la j ème réalisation ( sum(Y(:,j)) = nb ).
  • Poisson : Y=grand(m,n,'poi',mu) génère des nombres aléatoires suivant la loi de Poisson de moyenne mu (réel >= 0.0) .
  • permutations aléatoires : Y=grand(n,'prm',vect) génère n permutations aléatoire du vecteur colonne ( m x 1 ) vect .
  • uniforme (def) : Y=grand(m,n,'def') génère des nombres aléatoires suivant la loi uniforme sur [0,1[ (1 n'est jamais retourné).
  • uniforme (unf) : Y=grand(m,n,'unf',Low,High) génère des nombres aléatoires suivant la loi uniforme sur [Low, High[ .
  • uniforme (uin) : Y=grand(m,n,'uin',Low,High) génère des entiers aléatoires suivant la loi uniforme sur [Low, High] . High et Low doivent être des entiers tels que (High-Low+1) < 2147483561 .
  • uniforme (lgi) : Y=grand(m,n,'lgi') retourne la sortie du générateur de base courant : des entiers aléatoires suivant une loi uniforme sur :
  • [0, 2^32 - 1] for mt, kiss and fsultra
  • [0, 2147483561] for clcg2
  • [0, 2^31 - 2] for clcg4
  • [0, 2^31 - 1] for urand.

    • Actions sur le(s) générateur(s) de base

    Depuis Scilab-2.7 vous avez la possibilité de choisir parmi plusieurs générateurs de base (donnant des entiers aléatoires suivant la loi 'lgi') :

  • mt : le Mersenne-Twister de M. Matsumoto and T. Nishimura, période d'environ 2^19937 , état interne donné par 624 entiers (plus un index); c'est le générateur par défaut.
  • kiss : Le Keep It Simple Stupid de G. Marsaglia, période d'environ 2^123 , état interne donné par 4 entiers.
  • clcg2 : une combinaison de 2 générateurs linéaires congruentiels de P. L'Ecuyer, période d'environ 2^61 , état interne donné par 2 entiers ; c'était le seul générateur de base utilisé auparavent par grand (cette version est cependant légèrement différente de l'ancienne).
  • clcg4 : une combinaison de 4 générateurs linéaires congruentiels de P. L'Ecuyer, période d'environ 2^121 , état interne donné par 4 entiers ; ce générateur peut être partagé en 101 générateur virtuels (en fait la suite de longueur 2^121 peut être découpée en 101 sous-suites) ce qui peut être utile dans certains cas (voir 'Actions specifiques à clcg4' et 'Exemple d'utilisation de clcg4').
  • urand : le générateur de base (congruentiel affine...) utilisé par la fonction rand , état interne constitué d'un seul entier, période de 2^31 (basé sur le vol 2 du Art of Computer Science de Knuth). C'est le plus rapide de cette liste mais il est maintenant dépassé : il est préférable de ne pas l'utiliser pour une simulation sérieuse consommant beaucoup de nombres aléatoires (en particulier ce générateur ne passe pas certains tests statistiques classiques).
  • fsultra : un générateur SWB (subtract-with-borrow) mixé avec un générator congruentiel concu par Arif Zaman et George Marsaglia. Sa période est supérieure à 10^356 , et son état interne est constitué d'un tableau de 37 entiers, d'un index sur ce tableau et d'un drapeau (0 ou 1) ainsi qu'un autre entier donnant l'état interne du générateur congruentiel.

    • Actions

  • action= 'getgen' : S=grand('getgen') retourne le nom du générateur de base actuel ( S est l'une des chaînes de caractères 'mt', 'kiss', 'clcg2', 'clcg4', 'urand', 'fsultra').
  • action= 'setgen' : grand('setgen',gen) permet de changer le générateur de base : gen doit être l'une des chaînes de caractères 'mt', 'kiss', 'clcg2', 'clcg4', 'urand', 'fsultra'. En cas de succès la fonction retourne cette même chaîne.
  • action= 'getsd' : S=grand('getsd') retourne l'état interne actuel (les 'germes' dans l'ancienne appelation quoique ce terme désigne plutôt l'état initial) du générateur de base courant ; S est un vecteur colonne (d'entiers) de dimension 625 pour mt (la première composante étant un 'index' sur l'état, c-a-d un entier de l'intervalle [1,624] ), 4 pour kiss, 2 pour clcg2 , 40 pour fsultra, 4 pour clcg4 (pour ce dernier vous obtenez l'état interne du générateur virtuel courant), et 1 pour urand.
  • action= 'setsd' : grand('setsd',S), grand('setsd',s1[,s2,s3,s4]) impose l'état interne du générateur de base courant :
  • pour mt S est un vecteur d'entiers de dimension 625 (la première composante étant un index sur [1,624] ), les 624 dernières composantes doivent être dans [0,2^32[ ) (mais ne doivent pas être toutes nulles) ; une initialisation plus simple est possible (et recommandée) en donnant un seul entier s1 ( s1 appartenant à [0,2^32[ ) ;
  • pour kiss 4 entiers s1,s2, s3,s4 dans [0,2^32[ doivent être fournis ;
  • pour clcg2 2 entiers s1 dans [1,2147483562] et s2 dans [1,2147483398] doivent être fournis ;
  • pour clcg4 4 entiers s1 dans [1,2147483646] , s2 dans [1,2147483542] , s3 dans [1,2147483422] , s4 dans [1,2147483322] sont requis ; ATTENTION : avec clcg4 vous positionnez l'état interne du générateur virtuel courant mais vous perdez alors la synchronisation avec les autres générateurs virtuels. (=> si vous utilisez clcg4 avec différents générateurs virtuels, il faut utiliser l'option 'setall' qui permet de changer l'état interne (du générateur numéro 0) tout en recalculant l'état initial des 100 autres générateurs virtuels).
  • pour urand 1 entier s1 appartenant à [0,2^31 [ est requis.
  • for fsultra : S est un vecteur de 40 entiers (son premier élément doit être dans l'intervalle [0,37] , son deuxième (drapeau) doit être 0 ou 1, le troisième un entier de [1,2^32[ et les 37 composantes suivantes, des entiers de [0,2^32[) ; il est recommandé d'utiliser l'autre procédure d'initialisation (plus simple) avec deux entiers s1 et s2 de [0,2^32[ .
  • action= 'phr2sd' : Sd=grand('phr2sd', phrase) étant donnée une chaîne de caractères phrase cet appel retourne un vecteur 1 x 2 qui peut être utilisé comme état interne pour un générateur de base (initialement adapté pour clcg2).

    • Options specifiques à clcg4

    Le générateur clcg4 peut être utilisé comme les autres mais il offre l'avantage de pouvoir être découpé en ( 101 ) générateurs virtuels différents, c-a-d avec des séquences sans intersection (quand vous utilisez un générateur classique vous pouvez changer l'état initial de façon à obtenir une autre séquence mais vous n'êtes pas complètement sûr d'obtenir une séquence complètement différente). Chaque générateur virtuel correspond à une séquence de longueur 2^72 qui est de plus découpée en V=2^31 segments de longueur W=2^41 . Pour un générateur virtuel donné vous pouvez retourner au début de la séquence ou au début du segment ou bien au début du segment suivant. Vous pouvez aussi changer l'état initial du générateur 0 avec l'option 'setall' qui recalcule l'état initial des autres générateurs virtuels de sorte à obtenir la synchronisation entre les générateurs (c-a-d qu'en fonction du nouvel état initial du générateur 0 l'état initial des générateurs 1..100 sont recalculés de façon à obtenir 101 séquences qui ne s'intersectent pas).

  • action= 'setcgn' : grand('setcgn',G) sélectionne le générateur virtuel numéro G : lorsque le générateur de base courant est clcg4, c'est le générateur virtuel G qui sera alors utilisé ; les 101 générateurs virtuels sont numérotés 0,1,..,100 (ainsi G doit être un entier de l'intervalle [0,100] ) ; par défaut le générateur virtuel courant est celui de numéro 0 .
  • action= 'getcgn' : S=grand('getcgn') retourne le numéro du générateur virtuel courant.
  • action= 'initgn' : grand('initgn',I) réinitialise l'état du générateur virtuel courant :
  • I = -1 : remet l'état à sa valeur initiale
  • I = 0 : remet l'état au début du segment courant
  • I = 1 : positionne l'état au début du segment suivant et met à jour les valeurs définissant le segment courant (vous ne pouvez pas revenir au début du segment précédent).
  • action= 'setall' : grand('setall',s1,s2,s3,s4) impose l'état interne du générateur virtuel de numéro 0 à s1,s2,s3,s4 . L'état initial des autres générateurs est alors reconstruit (de façon à obtenir 101 séquences qui ne s'intersectent pas). Voir l'action 'setsd' pour les contraintes sur s1, s2, s3, s4 .
  • action= 'advnst' : grand('advnst',K) avance l'état du générateur virtuel courant de 2^K valeurs et réinitialise l'état initial (du générateur virtuel courant) à ce nouvel état.

    • Exemple d'utilisation de clcg4

    On cherche à comparer deux techniques statistiques sur des données de tailles différentes. La première, utilisant le 'bootstrapping' est supposée a priori aussi précise que la deuxième technique (utilisant uniquement la force brute) tout en utilisant moins de données. Pour la première méthode, un ensemble de données de taille n1, uniformément distribuée entre 25 et 50 devra être généré puis analysé par la méthode. Pour la seconde méthode, on procède de même avec une taille n2 à choisir entre 100 et 200. Ce processus est répété 1000 fois. Pour la réduction de la variance, on veut que les nombres aléatoires utilisés dans les deux méthodes soient les mêmes pour chacune des 1000 comparaisons. Comme la deuxième méthode utilise plus de nombres aléatoires, la synchronisation peut être difficile si l'on utilise un générateur classique. Avec un générateur comme clcg4 c'est par contre très simple : utilisez le générateur 0 pour obtenir la taille n1 du jeux de données et le générateur 1 pour obtenir les données. Avec le générateur 0 tirer la taille n2 puis resélectionner le générateur 1 et revenez au début du segment courant pour obtenir les n2 données pour la deuxième méthode : ainsi les données initiales (les n1 premieres) sont les mêmes pour les deux méthodes. Pour la comparaison suivante, il suffit d'avancer le générateur 1 au segment suivant, etc, etc.

    See Also

    rand ,

    Authors

    randlib Les codes qui permettent de générer les lois autres que def, unf, lgi, uin et geom proviennent de "Library of Fortran Routines for Random Number Generation", de Barry W. Brown et James Lovato, Department of Biomathematics, The University of Texas, Houston.
    mt Le code est le mt19937int.c par M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator", ACM Trans. on Modeling and Computer Simulation Vol. 8, No. 1, January, pp.3-30 1998.
    kiss Ce code a été donné par G. Marsaglia lors d'une discussion concernant la génération de nombres aléatoires en langage C dans plusieurs forums usenet (dont sci.math.num-analysis) "My offer of RNG's for C was an invitation to dance..." seul kiss a été inclus dans Scilab (kiss est construit à partir de plusieurs générateurs mais qui ne sont accessibles à l'interpréteur scilab).
    clcg2 Cette méthode est de P. L'Ecuyer mais le code C code provient de la page personnelle de Luc Devroye (http://cgm.cs.mcgill.ca/~luc/rng.html).
    clcg4 Ce code est de P. L'Ecuyer et Terry H.Andres et est distribué avec un article à partir de la page personnelle de P. L'Ecuyer ( http://www.iro.umontreal.ca/~lecuyer/papers.html). Ce paquetage est le successeur logique d'un plus ancien utilisant le générateur clcg2 (muni d'un mécanisme équivalent de générateurs virtuels) : P. L'Ecuyer and S. Cote. Implementing a Random Number Package with Splitting Facilities. ACM Transactions on Mathematical Software 17:1,pp 98-111.
    fsultra un code d' Arif Zaman (arif@stat.fsu.edu) et de George Marsaglia (geo@stat.fsu.edu)
    scilab packaging Par Jean-Philippe Chancelier et Bruno Pinçon


Identification
findABCD - discrete-time system subspace identification
findAC - discrete-time system subspace identification
findBD - initial state and system matrices B and D of a discrete-time system
findBDK - Kalman gain and B D system matrices of a discrete-time system
findR - Preprocessor for estimating the matrices of a linear time-invariant dynamical system
findx0BD - Estimates state and B and D matrices of a discrete-time linear system
inistate - Estimates the initial state of a discrete-time system
sident - discrete-time state-space realization and Kalman gain
sorder - computing the order of a discrete-time system


findx0BD

Scilab Function
Last update : 12/01/2004

findx0BD - Estimates state and B and D matrices of a discrete-time linear system

Calling Sequence

[X0,B,D] = findx0BD(A,C,Y,U,WITHX0,WITHD,TOL,PRINTW)
[x0,B,D,V,rcnd] = findx0BD(A,C,Y,U)

Parameters

  • A : state matrix of the system
  • C : C matrix of the system
  • Y : system output
  • U : system input
  • WITHX0 : a switch for estimating the initial state x0.
    • = 1: estimate x0;
    • = 0: do not estimate x0.

    Default: WITHX0 = 1.

  • WITHD : a switch for estimating the matrix D.
    • = 1: estimate the matrix D;
    • = 0: do not estimate the matrix D.

    Default: WITHD = 1.

  • TOL : the tolerance used for estimating the rank of matrices. If TOL > 0, then the given value of TOL is used as a lower bound for the reciprocal condition number. Default: prod(size(matrix))*epsilon_machine where epsilon_machine is the relative machine precision.
  • PRINTW : a switch for printing the warning messages.
    • = 1: print warning messages;
    • = 0: do not print warning messages.

    Default: PRINTW = 0.

  • X0 : intial state of the estimated linear system.
  • B : B matrix of the estimated linear system.
  • D : D matrix of the estimated linear system.
  • V : orthogonal matrix which reduces the system state matrix A to a real Schur form
  • rcnd : estimates of the reciprocal condition numbers of the matrices involved in rank decisions.

Description

findx0BD Estimates the initial state and/or the matrices B and D of a discrete-time linear system, given the (estimated) system matrices A, C, and a set of input/output data.

[X0,B,D] = findx0BD(A,C,Y,U,WITHX0,WITHD,TOL,PRINTW) estimates the initial state X0 and the matrices B and D of a discrete-time system using the system matrices A, C, output data Y and the input data U. The model structure is :

     x(k+1) = Ax(k) + Bu(k),   k >= 1,
     y(k)   = Cx(k) + Du(k),

The vectors y(k) and u(k) are transposes of the k-th rows of Y and U, respectively.

[x0,B,D,V,rcnd] = findx0BD(A,C,Y,U) also returns the orthogonal matrix V which reduces the system state matrix A to a real Schur form, as well as some estimates of the reciprocal condition numbers of the matrices involved in rank decisions.

    B = findx0BD(A,C,Y,U,0,0)  returns B only, and
[B,D] = findx0BD(A,C,Y,U,0)    returns B and D only.

Examples

//generate data from a given linear system
A = [ 0.5, 0.1,-0.1, 0.2;
      0.1, 0,  -0.1,-0.1;
     -0.4,-0.6,-0.7,-0.1;
      0.8, 0,  -0.6,-0.6];
B = [0.8;0.1;1;-1];
C = [1 2 -1 0];
SYS=syslin(0.1,A,B,C);
nsmp=100;
U=prbs_a(nsmp,nsmp/5);
Y=(flts(U,SYS)+0.3*rand(1,nsmp,'normal'));

// Compute R
S=15;L=1;
[R,N,SVAL] = findR(S,Y',U');

N=3;
METH=3;TOL=-1;
[A,C] = findAC(S,N,L,R,METH,TOL);

[X0,B,D,V,rcnd] = findx0BD(A,C,Y',U');
SYS1=syslin(1,A,B,C,D,X0);

Y1=flts(U,SYS1);
xbasc();plot2d((1:nsmp)',[Y',Y1'])

See Also

findBD , inistate ,


findABCD

Scilab Function
Last update : 12/01/2004

findABCD - discrete-time system subspace identification

Calling Sequence

[SYS,K] = findABCD(S,N,L,R,METH,NSMPL,TOL,PRINTW)
SYS = findABCD(S,N,L,R,METH)
[SYS,K,Q,Ry,S,RCND] = findABCD(S,N,L,R,METH,NSMPL,TOL,PRINTW)
[SYS,RCND] = findABCD(S,N,L,R,METH)

Parameters

  • S : integer, the number of block rows in the block-Hankel matrices
  • N : integer, the system order
  • L : integer, the number of output
  • R : matrix, relevant part of the R factor of the concatenated block-Hankel matrices computed by a call to findr.
  • METH : integer, an option for the method to use
    • = 1 : MOESP method with past inputs and outputs;
    • = 2 : N4SID method;
    • = 3 : combined method: A and C via MOESP, B and D via N4SID.

    Default: METH = 3.

  • NSMPL : integer, the total number of samples used for calculating the covariance matrices and the Kalman predictor gain. This parameter is not needed if the covariance matrices and/or the Kalman predictor gain matrix are not desired. If NSMPL = 0, then K, Q, Ry, and S are not computed. Default: NSMPL = 0.
  • TOL : the tolerance used for estimating the rank of matrices. If TOL > 0, then the given value of TOL is used as a lower bound for the reciprocal condition number. Default: prod(size(matrix))*epsilon_machine where epsilon_machine is the relative machine precision.
  • PRINTW : integer, switch for printing the warning messages.
    • PRINTW = 1: print warning messages;
    • PRINTW = 0: do not print warning messages.

    Default: PRINTW = 0.

  • SYS : computes a state-space realization SYS = (A,B,C,D) (an syslin object)
  • K : the Kalman predictor gain K (if NSMPL > 0)
  • Q : state covariance
  • Ry : output covariance
  • S : state-output cross-covariance
  • RCND : vector, reciprocal condition numbers of the matrices involved in rank decisions, least squares or Riccati equation solutions

Description

Finds the system matrices and the Kalman gain of a discrete-time system, given the system order and the relevant part of the R factor of the concatenated block-Hankel matrices, using subspace identification techniques (MOESP and/or N4SID).

*[SYS,K] = findABCD(S,N,L,R,METH,NSMPL,TOL,PRINTW) computes a state- space realization SYS = (A,B,C,D) (an ss object), and the Kalman predictor gain K (if NSMPL > 0). The model structure is:

     x(k+1) = Ax(k) + Bu(k) + Ke(k),   k >= 1,
     y(k)   = Cx(k) + Du(k) + e(k),

where x(k) and y(k) are vectors of length N and L, respectively.

*[SYS,K,Q,Ry,S,RCND] = findABCD(S,N,L,R,METH,NSMPL,TOL,PRINTW) also returns the state, output, and state-output (cross-)covariance matrices Q, Ry, and S (used for computing the Kalman gain), as well as the vector RCND of length lr containing the reciprocal condition numbers of the matrices involved in rank decisions, least squares or Riccati equation solutions, where

   lr = 4,  if Kalman gain matrix K is not required, and
   lr = 12, if Kalman gain matrix K is required.

Matrix R, computed by findR, should be determined with suitable arguments METH and JOBD. METH = 1 and JOBD = 1 must be used in findR, for METH = 1 in findABCD; METH = 1 must be used in findR, for METH = 3 in findABCD.

Examples

//generate data from a given linear system
A = [ 0.5, 0.1,-0.1, 0.2;
      0.1, 0,  -0.1,-0.1;
     -0.4,-0.6,-0.7,-0.1;
      0.8, 0,  -0.6,-0.6];
B = [0.8;0.1;1;-1];
C = [1 2 -1 0];
SYS=syslin(0.1,A,B,C);
nsmp=100;
U=prbs_a(nsmp,nsmp/5);
Y=(flts(U,SYS)+0.3*rand(1,nsmp,'normal'));

// Compute R
S=15;
[R,N1,SVAL] = findR(S,Y',U');
N=3;
SYS1 = findABCD(S,N,1,R) ;SYS1.dt=0.1;

SYS1.X0 = inistate(SYS1,Y',U');

Y1=flts(U,SYS1);
xbasc();plot2d((1:nsmp)',[Y',Y1'])

See Also

findAC , findBD , findBDK , findR , sorder , sident ,


findAC

Scilab Function
Last update : 12/01/2004

findAC - discrete-time system subspace identification

Calling Sequence

[A,C] = findAC(S,N,L,R,METH,TOL,PRINTW)
[A,C,RCND] = findAC(S,N,L,R,METH,TOL,PRINTW)

Parameters

  • S : integer, the number of block rows in the block-Hankel matrices
  • N : integer
  • L : integer
  • R : matrix, relevant part of the R factor of the concatenated block-Hankel matrices computed by a call to findr.
  • METH : integer, an option for the method to use
    • = 1 : MOESP method with past inputs and outputs;
    • = 2 : N4SID method;

    Default: METH = 3.

  • TOL : the tolerance used for estimating the rank of matrices. If TOL > 0, then the given value of TOL is used as a lower bound for the reciprocal condition number. Default: prod(size(matrix))*epsilon_machine where epsilon_machine is the relative machine precision.
  • PRINTW : integer, switch for printing the warning messages.
    • PRINTW = 1: print warning messages;
    • = 0 : do not print warning messages.

    Default: PRINTW = 0.

  • A : matrix, state system matrix
  • C : matrix, output system matrix
  • RCND : vector of length 4, condition numbers of the matrices involved in rank decision

Description

finds the system matrices A and C of a discrete-time system, given the system order and the relevant part of the R factor of the concatenated block-Hankel matrices, using subspace identification techniques (MOESP or N4SID).

*[A,C] = findAC(S,N,L,R,METH,TOL,PRINTW) computes the system matrices A and C. The model structure is: x(k+1) = Ax(k) + Bu(k) + Ke(k), k >= 1, y(k) = Cx(k) + Du(k) + e(k), where x(k) and y(k) are vectors of length N and L, respectively.
*[A,C,RCND] = findAC(S,N,L,R,METH,TOL,PRINTW) also returns the vector RCND of length 4 containing the condition numbers of the matrices involved in rank decisions.

Matrix R, computed by findR, should be determined with suitable arguments METH and JOBD.

Examples

//generate data from a given linear system
A = [ 0.5, 0.1,-0.1, 0.2;
      0.1, 0,  -0.1,-0.1;
     -0.4,-0.6,-0.7,-0.1;
      0.8, 0,  -0.6,-0.6];
B = [0.8;0.1;1;-1];
C = [1 2 -1 0];
SYS=syslin(0.1,A,B,C);
nsmp=100;
U=prbs_a(nsmp,nsmp/5);
Y=(flts(U,SYS)+0.3*rand(1,nsmp,'normal'));

// Compute R
S=15;L=1;
[R,N,SVAL] = findR(S,Y',U');

N=3;
METH=3;TOL=-1;
[A,C] = findAC(S,N,L,R,METH,TOL);

See Also

findABCD , findBD , findBDK , findR , sorder , sident ,


findBD

Scilab Function
Last update : 12/01/2004

findBD - initial state and system matrices B and D of a discrete-time system

Calling Sequence

[(x0) (,B (,D)) (,V) (,rcnd)] = findBD(jobx0,comuse (,job),A (,B),C (,D),Y
(,U,tol,printw,ldwork))

Parameters

  • jobx0 : integer option to specify whether or not the initial state should be computed:
    • = 1 : compute the initial state x0;
    • = 2 : do not compute the initial state (possibly, because x0 is known to be zero).
  • comuse : integer option to specify whether the system matrices B and D should be computed or used:
    • = 1 : compute the matrices B and D, as specified by job;
    • = 2 : use the matrices B and D, as specified by job;
    • = 3 : do not compute/use the matrices B and D.
  • job : integer option to determine which of the system matrices B and D should be computed or used:
    • = 1 : compute/use the matrix B only (D is known to be zero);
    • = 2 : compute/use the matrices B and D.

    job must not be specified if jobx0 = 2 and comuse = 2, or if comuse = 3.

  • A : state matrix of the given system
  • B : optionnal, input matrix of the given system
  • C : output matrix of the given system
  • D : optionnal, direct feedthrough of the given system
  • Y : the t-by-l output-data sequence matrix. Column j of Y contains the t values of the j-th output component for consecutive time increments.
  • U : the t-by-m input-data sequence matrix (input when jobx0 = 1 and comuse = 2, or comuse = 1). Column j of U contains the t values of the j-th input component for consecutive time increments.
  • tol : optionnal, tolerance used for estimating the rank of matrices. If tol > 0, then the given value of tol is used as a lower bound for the reciprocal condition number; an m-by-n matrix whose estimated condition number is less than 1/tol is considered to be of full rank. Default: m*n*epsilon_machine where epsilon_machine is the relative machine precision.
  • printw :optionnal, switch for printing the warning messages.
    • = 1: print warning messages;
    • = 0: do not print warning messages.

    Default: printw = 0.

  • ldwork : (optional) the workspace size. Default : computed by the formula LDWORK = MAX( minimum workspace size needed, 2*CSIZE/3, CSIZE - ( m + l )*t - 2*n*( n + m + l ) - l*m ) where CSIZE is the cache size in double precision words.
  • x0 : initial state vector
  • Br : system input matrix
  • Dr : system direct feedthrough matrix
  • V : the n-by-n orthogonal matrix which reduces A to a real Schur form (output when jobx0 = 1 or comuse = 1).
  • rcnd : (optional) the reciprocal condition numbers of the matrices involved in rank decisions.

Description

findBD function for estimating the initial state and the system matrices B and D of a discrete-time system, using SLICOT routine IB01CD.

     [x0,Br,V,rcnd] = findBD(1,1,1,A,C,Y,U)
   [x0,Br,Dr,V,rcnd] = findBD(1,1,2,A,C,Y,U)
        [Br,V,rcnd] = findBD(2,1,1,A,C,Y,U)
      [B,Dr,V,rcnd] = findBD(2,1,2,A,C,Y,U)
       [x0,V,rcnd] = findBD(1,2,1,A,B,C,Y,U)
       [x0,V,rcnd] = findBD(1,2,2,A,B,C,D,Y,U)
         [x0,rcnd] = findBD(2,2)      // (Set x0 = 0, rcnd = 1)
       [x0,V,rcnd] = findBD(1,3,A,C,Y)

Note: the example lines above may contain at the end the parameters tol, printw, ldwork.

FINDBD estimates the initial state and/or the system matrices Br and Dr of a discrete-time system, given the system matrices A, C, and possibly B, D, and the input and output trajectories of the system.

The model structure is :

         x(k+1) = Ax(k) + Bu(k),   k >= 1,
         y(k)   = Cx(k) + Du(k),

where x(k) is the n-dimensional state vector (at time k),

u(k) is the m-dimensional input vector,

y(k) is the l-dimensional output vector,

and A, B, C, and D are real matrices of appropriate dimensions.

Comments

  • 1. The n-by-m system input matrix B is an input parameter when jobx0 = 1 and comuse = 2, and it is an output parameter when comuse = 1.
  • 2. The l-by-m system matrix D is an input parameter when jobx0 = 1, comuse = 2 and job = 2, and it is an output parameter when comuse = 1 and job = 2.
  • 3. The n-vector of estimated initial state x(0) is an output parameter when jobx0 = 1, but also when jobx0 = 2 and comuse <= 2, in which case it is set to 0.
  • 4. If ldwork is specified, but it is less than the minimum workspace size needed, that minimum value is used instead.

    • Examples

//generate data from a given linear system
A = [ 0.5, 0.1,-0.1, 0.2;
      0.1, 0,  -0.1,-0.1;
     -0.4,-0.6,-0.7,-0.1;
      0.8, 0,  -0.6,-0.6];
B = [0.8;0.1;1;-1];
C = [1 2 -1 0];
SYS=syslin(0.1,A,B,C);
nsmp=100;
U=prbs_a(nsmp,nsmp/5);
Y=(flts(U,SYS)+0.3*rand(1,nsmp,'normal'));

// Compute R
S=15;L=1;
[R,N,SVAL] = findR(S,Y',U');

N=3;
METH=3;TOL=-1;
[A,C] = findAC(S,N,L,R,METH,TOL);
[X0,B,D] = findBD(1,1,2,A,C,Y',U')
SYS1=syslin(1,A,B,C,D,X0);

Y1=flts(U,SYS1);
xbasc();plot2d((1:nsmp)',[Y',Y1'])

    See Also

    inistate , findx0BD , findABCD , findAC , findBD ,

    Author

    V. Sima, Katholieke Univ. Leuven, Belgium, May 2000. (Revisions: V. Sima, July 2000)


findBDK

Scilab Function
Last update : 12/01/2004

findBDK - Kalman gain and B D system matrices of a discrete-time system

Calling Sequence

[B,D,K] = findBDK(S,N,L,R,A,C,METH,JOB,NSMPL,TOL,PRINTW)
[B,D,RCND] = findBDK(S,N,L,R,A,C,METH,JOB)
[B,D,K,Q,Ry,S,RCND] = findBDK(S,N,L,R,A,C,METH,JOB,NSMPL,TOL,PRINTW)

Parameters

  • S : integer, the number of block rows in the block-Hankel matrices
  • N : integer
  • L : integer
  • R : matrix, relevant part of the R factor of the concatenated block-Hankel matrices computed by a call to findR.
  • A : square matrix
  • C : matrix
  • METH : integer, an option for the method to use
    • = 1 : MOESP method with past inputs and outputs;
    • = 2 : N4SID method;

    Default: METH = 2.

  • JOB : an option specifying which system matrices should be computed:
    • = 1 : compute the matrix B;
    • = 2 : compute the matrices B and D.

    Default: JOB = 2.

  • NSMPL : integer, the total number of samples used for calculating the covariance matrices and the Kalman predictor gain. This parameter is not needed if the covariance matrices and/or the Kalman predictor gain matrix are not desired. If NSMPL = 0, then K, Q, Ry, and S are not computed. Default: NSMPL = 0.
  • TOL : the tolerance used for estimating the rank of matrices. If TOL > 0, then the given value of TOL is used as a lower bound for the reciprocal condition number. Default: prod(size(matrix))*epsilon_machine where epsilon_machine is the relative machine precision.
  • PRINTW : integer, switch for printing the warning messages.
    • PRINTW = 1: print warning messages;
    • PRINTW = 0: do not print warning messages.

    Default: PRINTW = 0.

  • SYS : computes a state-space realization SYS = (A,B,C,D) (an syslin object)
  • K : the Kalman predictor gain K (if NSMPL > 0)
  • Q : state covariance
  • Ry : output covariance
  • S : state-output cross-covariance
  • RCND : he vector of length 12 containing the reciprocal condition numbers of the matrices involved in rank decisions, least squares or Riccati equation solutions.

Description

finds the system matrices B and D and the Kalman gain of a discrete-time system, given the system order, the matrices A and C, and the relevant part of the R factor of the concatenated block-Hankel matrices, using subspace identification techniques (MOESP or N4SID).

*[B,D,K] = findBDK(S,N,L,R,A,C,METH,JOB,NSMPL,TOL,PRINTW) computes the system matrices B (if JOB = 1), B and D (if JOB = 2), and the Kalman predictor gain K (if NSMPL > 0). The model structure is:

     x(k+1) = Ax(k) + Bu(k) + Ke(k),   k >= 1,
     y(k)   = Cx(k) + Du(k) + e(k),

where x(k) and y(k) are vectors of length N and L, respectively.

*[B,D,RCND] = findBDK(S,N,L,R,A,C,METH,JOB) also returns the vector RCND of length 4 containing the reciprocal condition numbers of the matrices involved in rank decisions.
*[B,D,K,Q,Ry,S,RCND] = findBDK(S,N,L,R,A,C,METH,JOB,NSMPL,TOL,PRINTW) also returns the state, output, and state-output (cross-)covariance matrices Q, Ry, and S (used for computing the Kalman gain), as well as the vector RCND of length 12 containing the reciprocal condition numbers of the matrices involved in rank decisions, least squares or Riccati equation solutions.

Matrix R, computed by findR, should be determined with suitable arguments METH and JOBD. METH = 1 and JOBD = 1 must be used in findR, for METH = 1 in findBDK. Using METH = 1 in FINDR and METH = 2 in findBDK is allowed.

The number of output arguments may vary, but should correspond to the input arguments, e.g.,

            B = findBDK(S,N,L,R,A,C,METH,1)  or
        [B,D] = findBDK(S,N,L,R,A,C,METH,2)  or
   [B,D,RCND] = findBDK(S,N,L,R,A,C,METH,2)

Examples

//generate data from a given linear system
A = [ 0.5, 0.1,-0.1, 0.2;
      0.1, 0,  -0.1,-0.1;
     -0.4,-0.6,-0.7,-0.1;
      0.8, 0,  -0.6,-0.6];
B = [0.8;0.1;1;-1];
C = [1 2 -1 0];
SYS=syslin(0.1,A,B,C);
nsmp=100;
U=prbs_a(nsmp,nsmp/5);
Y=(flts(U,SYS)+0.3*rand(1,nsmp,'normal'));

// Compute R
S=15;L=1;
[R,N,SVAL] = findR(S,Y',U');

N=3;
METH=3;TOL=-1;
[A,C] = findAC(S,N,L,R,METH,TOL);
[B,D,K] = findBDK(S,N,L,R,A,C);
SYS1=syslin(1,A,B,C,D);

SYS1.X0 = inistate(SYS1,Y',U');

Y1=flts(U,SYS1);
xbasc();plot2d((1:nsmp)',[Y',Y1'])

See Also

findABCD , findAC , findBD , findR , sorder , sident ,


findR

Scilab Function
Last update : 12/01/2004

findR - Preprocessor for estimating the matrices of a linear time-invariant dynamical system

Calling Sequence

[R,N [,SVAL,RCND]] = findR(S,Y,U,METH,ALG,JOBD,TOL,PRINTW)
[R,N] = findR(S,Y)

Parameters

  • S : the number of block rows in the block-Hankel matrices.
  • Y :
  • U :
  • METH : an option for the method to use:
    • 1 : MOESP method with past inputs and outputs;
    • 2 : N4SI15 0 1 1 1000D method.

    Default: METH = 1.

  • ALG : an option for the algorithm to compute the triangular factor of the concatenated block-Hankel matrices built from the input-output data:
    • 1 : Cholesky algorithm on the correlation matrix;
    • 2 : fast QR algorithm;
    • 3 : standard QR algorithm.

    Default: ALG = 1.

  • JOBD : an option to specify if the matrices B and D should later be computed using the MOESP approach:
    • = 1 : the matrices B and D should later be computed using the MOESP approach;
    • = 2 : the matrices B and D should not be computed using the MOESP approach.

    Default: JOBD = 2. This parameter is not relevant for METH = 2.

  • TOL : a vector of length 2 containing tolerances:
    • TOL (1) is the tolerance for estimating the rank of matrices. If TOL(1) > 0, the given value of TOL(1) is used as a lower bound for the reciprocal condition number.

      Default: TOL(1) = prod(size(matrix))*epsilon_machine where epsilon_machine is the relative machine precision.

    • TOL (2) is the tolerance for estimating the system order. If TOL(2) >= 0, the estimate is indicated by the index of the last singular value greater than or equal to TOL(2). (Singular values less than TOL(2) are considered as zero.)

      When TOL(2) = 0, then S*epsilon_machine*sval(1) is used instead TOL(2), where sval(1) is the maximal singular value. When TOL(2) < 0, the estimate is indicated by the index of the singular value that has the largest logarithmic gap to its successor. Default: TOL(2) = -1.

  • PRINTW : a switch for printing the warning messages.
    • = 1: print warning messages;
    • = 0: do not print warning messages.

    Default: PRINTW = 0.

  • R :
  • N : the order of the discrete-time realization
  • SVAL : singular values SVAL, used for estimating the order.
  • RCND : vector of length 2 containing the reciprocal condition numbers of the matrices involved in rank decisions or least squares solutions.

Description

findR Preprocesses the input-output data for estimating the matrices of a linear time-invariant dynamical system, using Cholesky or (fast) QR factorization and subspace identification techniques (MOESP or N4SID), and estimates the system order.

[R,N] = findR(S,Y,U,METH,ALG,JOBD,TOL,PRINTW) returns the processed upper triangular factor R of the concatenated block-Hankel matrices built from the input-output data, and the order N of a discrete-time realization. The model structure is:

     x(k+1) = Ax(k) + Bu(k) + w(k),   k >= 1,
     y(k)   = Cx(k) + Du(k) + e(k).

The vectors y(k) and u(k) are transposes of the k-th rows of Y and U, respectively.

[R,N,SVAL,RCND] = findR(S,Y,U,METH,ALG,JOBD,TOL,PRINTW) also returns the singular values SVAL, used for estimating the order, as well as, if meth = 2, the vector RCND of length 2 containing the reciprocal condition numbers of the matrices involved in rank decisions or least squares solutions.

[R,N] = findR(S,Y) assumes U = [] and default values for the remaining input arguments.

Examples

//generate data from a given linear system
A = [ 0.5, 0.1,-0.1, 0.2;
      0.1, 0,  -0.1,-0.1;
     -0.4,-0.6,-0.7,-0.1;
      0.8, 0,  -0.6,-0.6];
B = [0.8;0.1;1;-1];
C = [1 2 -1 0];
SYS=syslin(0.1,A,B,C);
U=(ones(1,1000)+rand(1,1000,'normal'));
Y=(flts(U,SYS)+0.5*rand(1,1000,'normal'));
// Compute R

[R,N,SVAL] = findR(15,Y',U');
SVAL
N

See Also

findABCD , findAC , findBD , findBDK , sorder , sident ,


inistate

Scilab Function
Last update : 12/01/2004

inistate - Estimates the initial state of a discrete-time system

Calling Sequence

X0 = inistate(SYS,Y,U,TOL,PRINTW)
X0 = inistate(A,B,C,Y,U);
X0 = inistate(A,C,Y);
[x0,V,rcnd] = inistate(SYS,Y,U,TOL,PRINTW)

Parameters

  • SYS : given system, syslin(dt,A,B,C,D)
  • Y : the output of the system
  • U : the input of the system
  • TOL : TOL is the tolerance used for estimating the rank of matrices. If TOL > 0, then the given value of TOL is used as a lower bound for the reciprocal condition number.

    Default: prod(size(matrix))*epsilon_machine where epsilon_machine is the relative machine precision.

  • PRINTW : PRINTW is a switch for printing the warning messages.
    • = 1: print warning messages;
    • = 0: do not print warning messages.

    Default: PRINTW = 0.

  • X0 : the estimated initial state vector
  • V : orthogonal matrix which reduces the system state matrix A to a real Schur form
  • rcnd : estimate of the reciprocal condition number of the coefficient matrix of the least squares problem solved.

Description

inistate Estimates the initial state of a discrete-time system, given the (estimated) system matrices, and a set of input/output data.

X0 = inistate(SYS,Y,U,TOL,PRINTW) estimates the initial state X0 of the discrete-time system SYS = (A,B,C,D), using the output data Y and the input data U. The model structure is :

     x(k+1) = Ax(k) + Bu(k),   k >= 1,
     y(k)   = Cx(k) + Du(k),

The vectors y(k) and u(k) are transposes of the k-th rows of Y and U, respectively.

Instead of the first input parameter SYS (an syslin object), equivalent information may be specified using matrix parameters, for instance, X0 = inistate(A,B,C,Y,U); or X0 = inistate(A,C,Y);

[x0,V,rcnd] = inistate(SYS,Y,U,TOL,PRINTW) returns, besides x0, the orthogonal matrix V which reduces the system state matrix A to a real Schur form, as well as an estimate of the reciprocal condition number of the coefficient matrix of the least squares problem solved.

See Also

findBD , findx0BD ,


sident

Scilab Function
Last update : 12/01/2004

sident - discrete-time state-space realization and Kalman gain

Calling Sequence

[(A,C)(,B(,D))(,K,Q,Ry,S)(,rcnd)] = sident(meth,job,s,n,l,R(,tol,t,Ai,
Ci,printw))

Parameters

  • meth : integer option to determine the method to use:
    • = 1 : MOESP method with past inputs and outputs;
    • = 2 : N4SID method;
    • = 3 : combined method: A and C via MOESP, B and D via N4SID.
  • job : integer option to determine the calculation to be performed:
    • = 1 : compute all system matrices, A, B, C, D;
    • = 2 : compute the matrices A and C only;
    • = 3 : compute the matrix B only;
    • = 4 : compute the matrices B and D only.
  • s : the number of block rows in the processed input and output block Hankel matrices. s > 0.
  • n : integer, the order of the system
  • l : integer, the number of the system outputs
  • R : the 2*(m+l)*s-by-2*(m+l)*s part of R contains the processed upper triangular factor R from the QR factorization of the concatenated block-Hankel matrices, and further details needed for computing system matrices.
  • tol : (optional) tolerance used for estimating the rank of matrices. If tol > 0, then the given value of tol is used as a lower bound for the reciprocal condition number; an m-by-n matrix whose estimated condition number is less than 1/tol is considered to be of full rank. Default: m*n*epsilon_machine where epsilon_machine is the relative machine precision.
  • t : (optional) the total number of samples used for calculating the covariance matrices. Either t = 0, or t >= 2*(m+l)*s. This parameter is not needed if the covariance matrices and/or the Kalman predictor gain matrix are not desired. If t = 0, then K, Q, Ry, and S are not computed. Default: t = 0.
  • Ai : real matrix
  • Ci : real matrix
  • printw : (optional) switch for printing the warning messages.
    • = 1: print warning messages;
    • = 0: do not print warning messages.

    Default: printw = 0.

  • A : real matrix
  • C : real matrix
  • B : real matrix
  • D : real matrix
  • K : real matrix, kalman gain
  • Q : (optional) the n-by-n positive semidefinite state covariance matrix used as state weighting matrix when computing the Kalman gain.
  • RY : (optional) the l-by-l positive (semi)definite output covariance matrix used as output weighting matrix when computing the Kalman gain.
  • S : (optional) the n-by-l state-output cross-covariance matrix used as cross-weighting matrix when computing the Kalman gain.
  • rcnd : (optional) vector of length lr, containing estimates of the reciprocal condition numbers of the matrices involved in rank decisions, least squares, or Riccati equation solutions, where lr = 4, if Kalman gain matrix K is not required, and lr = 12, if Kalman gain matrix K is required.

Description

SIDENT function for computing a discrete-time state-space realization (A,B,C,D) and Kalman gain K using SLICOT routine IB01BD.

                 [A,C,B,D] = sident(meth,1,s,n,l,R)
   [A,C,B,D,K,Q,Ry,S,rcnd] = sident(meth,1,s,n,l,R,tol,t)
                     [A,C] = sident(meth,2,s,n,l,R)
                         B = sident(meth,3,s,n,l,R,tol,0,Ai,Ci)
         [B,K,Q,Ry,S,rcnd] = sident(meth,3,s,n,l,R,tol,t,Ai,Ci)
                     [B,D] = sident(meth,4,s,n,l,R,tol,0,Ai,Ci)
       [B,D,K,Q,Ry,S,rcnd] = sident(meth,4,s,n,l,R,tol,t,Ai,Ci)

SIDENT computes a state-space realization (A,B,C,D) and the Kalman predictor gain K of a discrete-time system, given the system order and the relevant part of the R factor of the concatenated block-Hankel matrices, using subspace identification techniques (MOESP, N4SID, or their combination).

The model structure is :

         x(k+1) = Ax(k) + Bu(k) + Ke(k),   k >= 1,
         y(k)   = Cx(k) + Du(k) + e(k),

where x(k) is the n-dimensional state vector (at time k),

u(k) is the m-dimensional input vector,

y(k) is the l-dimensional output vector,

e(k) is the l-dimensional disturbance vector,

and A, B, C, D, and K are real matrices of appropriate dimensions.

Comments

1. The n-by-n system state matrix A, and the p-by-n system output matrix C are computed for job <= 2.

2. The n-by-m system input matrix B is computed for job <> 2.

3. The l-by-m system matrix D is computed for job = 1 or 4.

4. The n-by-l Kalman predictor gain matrix K and the covariance matrices Q, Ry, and S are computed for t > 0.

Examples

//generate data from a given linear system
A = [ 0.5, 0.1,-0.1, 0.2;
      0.1, 0,  -0.1,-0.1;
     -0.4,-0.6,-0.7,-0.1;
      0.8, 0,  -0.6,-0.6];
B = [0.8;0.1;1;-1];
C = [1 2 -1 0];
SYS=syslin(0.1,A,B,C);
nsmp=100;
U=prbs_a(nsmp,nsmp/5);
Y=(flts(U,SYS)+0.3*rand(1,nsmp,'normal'));

S = 15;
N = 3;
METH=1;
[R,N1] = findR(S,Y',U',METH);
[A,C,B,D,K] = sident(METH,1,S,N,1,R);
SYS1=syslin(1,A,B,C,D);
SYS1.X0 = inistate(SYS1,Y',U');

Y1=flts(U,SYS1);
xbasc();plot2d((1:nsmp)',[Y',Y1'])

METH = 2;
[R,N1,SVAL] = findR(S,Y',U',METH);
tol = 0;
t = size(U',1)-2*S+1;

[A,C,B,D,K] = sident(METH,1,S,N,1,R,tol,t)
SYS1=syslin(1,A,B,C,D)
SYS1.X0 = inistate(SYS1,Y',U');

Y1=flts(U,SYS1);
xbasc();plot2d((1:nsmp)',[Y',Y1'])

See Also

findBD , sorder ,

Author

V. Sima, Research Institute for Informatics, Bucharest, Oct. 1999. Revisions: May 2000, July 2000.


sorder

Scilab Function
Last update : 12/01/2004

sorder - computing the order of a discrete-time system

Calling Sequence

[Ro(,n,sval,rcnd)] = sorder(meth,alg,jobd,batch,conct,s,Y(,U,tol,
printw,ldwork,Ri))

Parameters

  • meth : integer option to determine the method to use:
    • = 1 : MOESP method with past inputs and outputs;
    • = 2 : N4SID method.
  • alg : integer option to determine the algorithm for computing the triangular factor of the concatenated block-Hankel matrices built from the input-output data:
    • = 1 : Cholesky algorithm on the correlation matrix;
    • = 2 : fast QR algorithm;
    • = 3 : standard QR algorithm.
  • jobd : integer option to specify if the matrices B and D should later be computed using the MOESP approach:
    • = 1 : the matrices B and D should later be computed using the MOESP approach;
    • = 2 : the matrices B and D should not be computed using the MOESP approach.

      This parameter is not relevant for meth = 2.

  • batch : integer option to specify whether or not sequential data processing is to be used, and, for sequential processing, whether or not the current data block is the first block, an intermediate block, or the last block, as follows:
    • = 1 : the first block in sequential data processing;
    • = 2 : an intermediate block in sequential data processing;
    • = 3 : the last block in sequential data processing;
    • = 4 : one block only (non-sequential data processing).
  • conct : integer option to specify whether or not the successive data blocks in sequential data processing belong to a single experiment, as follows:
    • = 1 : the current data block is a continuation of the previous data block and/or it will be continued by the next data block;
    • = 2 : there is no connection between the current data block and the previous and/or the next ones.

      This parameter is not used if batch = 4.

  • s : the number of block rows in the input and output block Hankel matrices to be processed. s > 0
  • Y : the t-by-l output-data sequence matrix. Column j of Y contains the t values of the j-th output component for consecutive time increments.
  • U : (optional) the t-by-m input-data sequence matrix. Column j of U contains the t values of the j-th input component for consecutive time increments. Default: U = [].
  • tol : (optional) vector of length 2 containing tolerances: tol(1) - tolerance used for estimating the rank of matrices. If tol(1) > 0, then the given value of tol(1) is used as a lower bound for the reciprocal condition number; an m-by-n matrix whose estimated condition number is less than 1/tol(1) is considered to be of full rank. If tol(1) <= 0, then a default value m*n*epsilon_machine is used, where epsilon_machine is the relative machine precision.

    tol(2) - tolerance used for determining an estimate of the system order. If tol(2) >= 0, the estimate is indicated by the index of the last singular value greater than or equal to tol(2). (Singular values less than tol(2) are considered as zero.) When tol(2) = 0, an internally computed default value, tol(2) = s*epsilon_machine*sval(1), is used, where sval(1) is the maximal singular value, and epsilon_machine the relative machine precision. When tol(2) < 0, the estimate is indicated by the index of the singular value that has the largest logarithmic gap to its successor.

    Default: tol(1:2) = [0,-1].

  • printw :(optional) switch for printing the warning messages.
    • = 1: print warning messages;
    • = 0: do not print warning messages.

    Default: printw = 0.

  • ldwork : (optional) the workspace size. Default : computed by the formulas

nr = 2*( m + l )*s
LDWORK = ( t - 2*s + 3 + 64 )*nr
if ( CSIZE > MAX( nr*nr + t*( m + l ) + 16, 2*nr ) ) then
   LDWORK = MIN( LDWORK, CSIZE - nr*nr - t*( m + l ) - 16 )
else
   LDWORK = MIN( LDWORK, MAX( 2*nr, CSIZE/2 ) )
end if

    LDWORK = MAX( minimum workspace size needed, LDWORK ) where CSIZE is the cache size in double precision words.

    If LDWORK is specified less than the minimum workspace size needed, that minimum value is used instead.

  • Ri : (optional) if batch = 2 or 3, the 2*(m+l)*s-by-2*(m+l)*s (upper triangular, if alg <> 2) part of R must contain the (upper triangular) matrix R computed at the previous call of this mexfile in sequential data processing. If conct = 1, R has an additional column, also set at the previous call.

    If alg = 2, R has m+l+1 additional columns, set at the previous call.

    This parameter is not used for batch = 1 or batch = 4.

  • Ro : if batch = 3 or 4, the 2*(m+l)*s-by-2*(m+l)*s part of R contains the processed upper triangular factor R from the QR factorization of the concatenated block-Hankel matrices, and further details needed for computing system matrices. If batch = 1 or 2, then R contains intermediate results needed at the next call of this mexfile. If batch = 1 or 2 and conct = 1, R has an additional column, also set before return. If batch = 1 or 2 and alg = 2, R has m+l+1 additional columns, set before return.
  • n : the order of the system.
  • sval : (optional) the singular values used for estimating the order of the system.
  • rcnd : (optional) if meth = 2, vector of length 2 containing the reciprocal condition numbers of the matrices involved in rank decisions or least squares solutions.

Description

sorder - function for computing the order of a discrete-time system using SLICOT routine IB01AD.

For one block (data sequences Y, U): [R,n,sval,rcnd] = sorder(meth,alg,jobd,4,conct,s,Y,U);

For f blocks (data sequences Yj, Uj, j = 1 : f):

R = sorder(meth,alg,jobd,1,conct,s,Y1,U1);
for j = 2 : f - 1
   R = sorder(meth,alg,jobd,2,conct,s,Yj,Uj,tol,printw,ldwork,R)
end
[R,n,sval,rcnd] = sorder(meth,alg,jobd,3,conct,s,Yf,Uf,tol);

sorder preprocesses the input-output data for estimating the matrices of a linear time-invariant dynamical system, using Cholesky or (fast) QR factorization and subspace identification techniques (MOESP and N4SID), and then estimates the order of a discrete-time realization.

The model structure is :

      x(k+1) = Ax(k) + Bu(k) + w(k),   k >= 1,
      y(k)   = Cx(k) + Du(k) + e(k),

where x(k) is the n-dimensional state vector (at time k),

u(k) is the m-dimensional input vector,

y(k) is the l-dimensional output vector,

w(k) is the n-dimensional state disturbance vector,

e(k) is the l-dimensional output disturbance vector,

and A, B, C, and D are real matrices of appropriate dimensions.

Comments

1. The Cholesy or fast QR algorithms can be much faster (for large data blocks) than QR algorithm, but they cannot be used if the correlation matrix, H'*H, is not positive definite. In such a case, the code automatically switches to the QR algorithm, if sufficient workspace is provided and batch = 4.

2. If ldwork is specified, but it is less than the minimum workspace size needed, that minimum value is used instead.

See Also

findBD , sident ,

Author

V. Sima, Research Institute for Informatics, Bucharest, Oct. 1999.; ; Revisions:; V. Sima, May 2000, July 2000.


Aide à la conversion Matlab vers Scilab
Chaines_de_caracteres_Matlab-Scilab - Généralités...
Contents - Créé un arbre contenant les données d'inférence du contenu d'une variable
Cste - Créé un arbre représentant une constante
Equal - Créé un arbre représentant une instruction
Funcall - Créé un arbre représentant l'appel à une fonction
Infer - Créé un arbre contenant les données d'inférence
Matlab-Scilab_character_strings - Generally speaking about...
Operation - Créé un arbre représentant une opération
Type - Créé un arbre contenant les données d'inférence de type
Variable - Créé un arbre représentant une variable
asciimat - conversion d'une matrice de chaînes ASCII
cell - create an empty cell
firstnonsingleton - Trouve la première dimension qui n'est pas 1
get_contents_infer - Cherche des informations dans le contenu d'une "tlist M2SCI"
m2scideclare - Donner des indices pour aider M2SCI...
makecell - creer une cell
mstr2sci - conversion d'une matrice de chaînes en matrice de caractères
mtlb_0 - Fonction d'émulation de la transposition non-conjuguée de Matlab
mtlb_a - Fonction d'émulation de l'addition Matlab
mtlb_all - Fonction d'émulation de la fonction Matlab all
mtlb_any - Fonction d'émulation de la fonction Matlab any
mtlb_axis - Fonction d'émulation de la fonction Matlab axis
mtlb_legendre - Fonction d'émulation de la fonction Matlab legendre
mtlb_box - Fonction d'émulation de la fonction Matlab box
mtlb_close - Fonction d'émulation de la fonction Matlab close
mtlb_colordef - Fonction d'émulation de la fonction Matlab colordef
mtlb_conv - Fonction d'émulation de la fonction Matlab conv
mtlb_cumprod - Fonction d'émulation de la fonction Matlab cumprod
mtlb_cumsum - Fonction d'émulation de la fonction Matlab cumsum
mtlb_dec2hex - Fonction d'émulation de la fonction Matlab dec2hex
mtlb_delete - Fonction d'émulation de la fonction Matlab delete
mtlb_diag - Fonction d'émulation de la fonction Matlab diag
mtlb_diff - Fonction d'émulation de la fonction Matlab diff
mtlb_dir - Fonction d'émulation de la fonction Matlab dir
mtlb_double - Fonction d'émulation de la fonction Matlab double
mtlb_e - Fonction d'émulation de l'extraction Matlab
mtlb_echo - Fonction d'émulation de la fonction Matlab echo
mtlb_eig - Fonction d'émulation de la fonction Matlab eig
mtlb_eval - Fonction d'émulation de la fonction Matlab eval
mtlb_exist - Fonction d'émulation de la fonction Matlab exist
mtlb_eye - Fonction d'émulation de la fonction Matlab eye
mtlb_false - Fonction d'émulation de la fonction Matlab false
mtlb_fft - Fonction d'émulation de la fonction Matlab fft
mtlb_fftshift - Fonction d'émulation de la fonction Matlab fftshift
mtlb_find - Fonction d'émulation de la fonction Matlab find
mtlb_findstr - Fonction d'émulation de la fonction Matlab findstr
mtlb_fliplr - Fonction d'émulation de la fonction Matlab fliplr
mtlb_fopen - Fonction d'émulation de la fonction Matlab fopen
mtlb_format - Fonction d'émulation de la fonction Matlab format
mtlb_fprintf - Fonction d'émulation de la fonction Matlab fprintf
mtlb_fread - Fonction d'émulation de la fonction Matlab fread
mtlb_fscanf - Fonction d'émulation de la fonction Matlab fscanf
mtlb_full - Fonction d'émulation de la fonction Matlab full
mtlb_write - Fonction d'émulation de la fonction Matlab write
mtlb_grid - Fonction d'émulation de la fonction Matlab grid
mtlb_hold - Fonction d'émulation de la fonction Matlab hold
mtlb_i - Fonction d'émulation de l'insertion de Matlab
mtlb_fft - Fonction d'émulation de la fonction Matlab ifft
mtlb_imp - Fonction d'émulation de l'opérateur "deux points" de Matlab
mtlb_int16 - Fonction d'émulation de la fonction Matlab int16
mtlb_int32 - Fonction d'émulation de la fonction Matlab int32
mtlb_int8 - Fonction d'émulation de la fonction Matlab int8
mtlb_is - Fonction d'émulation de l'insertion dans une chaîne de caractères de Matlab
mtlb_isa - Fonction d'émulation de la fonction Matlab isa
mtlb_isfield - Fonction d'émulation de la fonction Matlab isfield
mtlb_isletter - Fonction d'émulation de la fonction Matlab isletter
mtlb_isspace - Fonction d'émulation de la fonction Matlab isspace
mtlb_l - Fonction d'émulation de la division à gauche de Matlab
mtlb_legendre - Fonction d'émulation de la fonction Matlab legendre
mtlb_linspace - Fonction d'émulation de la fonction Matlab linspace
mtlb_load - Fonction d'émulation de la fonction Matlab load
mtlb_logic - Fonction d'émulation des opérateurs logiques de Matlab
mtlb_logical - Fonction d'émulation de la fonction Matlab logical
mtlb_lower - Fonction d'émulation de la fonction Matlab lower
mtlb_max - Fonction d'émulation de la fonction Matlab max
mtlb_min - Fonction d'émulation de la fonction Matlab min
mtlb_more - Fonction d'émulation de la fonction Matlab more
mtlb_num2str - Fonction d'émulation de la fonction Matlab num2str
mtlb_ones - Fonction d'émulation de la fonction Matlab ones
mtlb_plot - Fonction d'émulation de la fonction Matlab plot
mtlb_prod - Fonction d'émulation de la fonction Matlab prod
mtlb_rand - Fonction d'émulation de la fonction Matlab rand
mtlb_randn - Fonction d'émulation de la fonction Matlab randn
mtlb_rcond - Fonction d'émulation de la fonction Matlab rcond
mtlb_realmax - Fonction d'émulation de la fonction Matlab realmax
mtlb_realmin - Fonction d'émulation de la fonction Matlab realmin
mtlb_repmat - Fonction d'émulation de la fonction Matlab repmat
mtlb_s - Fonction d'émulation de la soustraction Matlab
mtlb_save - Fonction d'émulation de la fonction Matlab save
mtlb_setstr - Fonction d'émulation de la fonction Matlab setstr
mtlb_size - Fonction d'émulation de la fonction Matlab size
mtlb_sort - Fonction d'émulation de la fonction Matlab sort
mtlb_strcmp - Fonction d'émulation de la fonction Matlab strcmp
mtlb_strcmpi - Fonction d'émulation de la fonction Matlab strcmpi
mtlb_strfind - Fonction d'émulation de la fonction Matlab strfind
mtlb_strrep - Fonction d'émulation de la fonction Matlab strrep
mtlb_sum - Fonction d'émulation de la fonction Matlab sum
mtlb_t - Fonction d'émulation de la transposition de Matlab
mtlb_toeplitz - Fonction d'émulation de la fonction Matlab toeplitz
mtlb_tril - Fonction d'émulation de la fonction Matlab tril
mtlb_triu - Fonction d'émulation de la fonction Matlab triu
mtlb_true - Fonction d'émulation de la fonction Matlab true
mtlb_uint16 - Fonction d'émulation de la fonction Matlab uint16
mtlb_uint32 - Fonction d'émulation de la fonction Matlab uint32
mtlb_uint8 - Fonction d'émulation de la fonction Matlab uint8
mtlb_upper - Fonction d'émulation de la fonction Matlab upper
mtlb_zeros - Fonction d'émulation de la fonction Matlab zeros
sci_files - Comment écrire des fonctions de conversion
struct - creer une struct


asciimat

Fonction M2SCI
Last update : 13/08/2004

asciimat - conversion d'une matrice de chaînes ASCII

Calling Sequence

a=asciimat(txt)
txt=asciimat(a)

Parameters

  • txt : chaîne de caractères ou matrice de chaînes
  • a : vecteur ou matrice de codes ASCII

Description

Cette fonction convertit une chaîne de caractères Scilab en codes ASCII ou une matrice de codes ASCII en chaîne de caractères Scilab. La valeur retournée est une matrice ayant le même nombre de lignes que l'entrée, ce qui n'est pas le cas de la fonction ascii .

See Also

ascii ,

Authors

V.C.


cell

Scilab Function
Last update : 29/05/2006

cell - create an empty cell

Calling Sequence

c=cell(m1,m2,...)
c=cell(x)
c=cell()

Parameters

  • x : integers vector
  • m1, m2,.. : integers

Description

Returns an empty cell.

cell(m1) returns an empty (m1,m1) cell
cell(m1,m2) returns an empty (m1,m2) cell
cell(m1,m2,..,mn) : creates an empty (m1,m2,..,mn) cell.
cell(x) returns an empty cell array with : the first dimension of the cell array is x(1) , the second dimension is x(2), ...

Note that cell(x) is not the same size that x

cell() is eqivalent to cell(0)

Examples

cell(3)
cell(3,3)
cell([2,3,4])

// assigning cell entries
b=cell(3,1);
// assigning a single entry
b(1).entries=1:3
b(2).entries='Scilab'
b(3).entries=poly(1:3,'s')

// assigning sub-cells
X=cell(3,2);
X(:,1)=b

//sub-cell reference
b(1) // result is a cell
b(1:2)

b(1).entries //result is an array

See Also

eye , ones , zeros ,


firstnonsingleton

Fonction M2SCI
Last update : 30/03/2004

firstnonsingleton - Trouve la première dimension qui n'est pas 1

Calling Sequence

[dim]=firstnonsingleton(A[,opt])

Parameters

  • dim : première dimension de A qui n'est pas 1
  • A : une variable de n'importe quel type de donnée Scilab
  • opt : une chaîne de caractères qui précise le type de la variable de sortie que l'on veut
    • "num" : la valeur retournée est une valeur numérique
    • "str" : la valeur retournée est une chaîne de caractères si possible ("r" au lieu de 1 et "c" au lieu de 2)

Description

Cette fonction est utilisée par mfile2sci pour émuler le comportement de Matlab sous Scilab, en particulier pour les fonctions qui traitent les valeurs suivant la première dimension de A qui n'est pas 1 en Matlab alors que dans Scilab elles traitent toutes les valeurs de A.

Examples

A = [1 2 3;4 5 6];
// max Scilab
M = max(A)
// Emulation du max Matlab
M = max(A,firstnonsingleton(A))

Authors

V.C.


get_contents_infer

Fonction M2SCI
Last update : 05/10/2004

get_contents_infer - Cherche des informations dans le contenu d'une "tlist M2SCI"

Calling Sequence

[infer,pos]=get_contents_infer(m2scitlist,index)

Parameters

  • m2scitlist : une "tlist M2SCI"
  • index : un index tel que ceux retournés par macr2tree .
  • infer : une tlist de type "infer"
  • pos : position des informations dans la liste

Description

Cette fonction recherche les informations d'inférence pour un index donné dans le contenu d'une Cell ou d'une Struct en tenant compte des * . Si aucune information correspond à cet index, les valeurs retournées sont infer=Infer() et pos=0.

See Also

Infer , Contents ,

Authors

V.C.


m2scideclare

Fonction M2SCI
Last update : 05/10/2004

m2scideclare - Donner des indices pour aider M2SCI...

Description

La principale difficulté de M2SCI ( mfile2sci ) est de trouver ce que sont les variables : dimensions, type...

Pour aider cet outil, il suffit d'ajouter des commentaires commencant par %m2scideclare dans le fichier Matlab à convertir, ( %m2sciassume était utilisée dans les versions précédentes de Scilab mais est maintenant obsolète).

La syntaxe de cette commande est :

%m2scideclare nom_de_variable|dimensions|type_de_données|propriété

avec :

  • nom_de_variable : nom de la variable déclarée. Ce nom peut être un champ de Struct (e.g. x(1,2).nom ) ou décrire le contenu d'une Cell en utilisant la syntaxe x(1,2).entries . NOTEZ que pour les Cells et les Structs * peut être utilisé comme index.
  • dimensions : dimensions de la variable déclarée séparées par des espaces, si une dimension est inconnue, remplacez la par ? . NOTEZ que les dimensions des chaînes de caractère doivent être identiques aux dimensions Matlab e.g. 1 6 pour la chaîne de caractères 'chaine'.
  • type_de_données: le type de donnée de la variable qui peut être :
    Type de donnée m2scideclare | Type Scilab "équivalent"
    Double | 1
    Boolean | 4
    Sparse | 5
    Int | 8
    Handle | 9
    String | 10
    Struct | Struct Matlab (16)
    Cell | Cell Matlab (17)
    Void | Sans type (0)
    ? Type inconnu
  • propriété : propriété de la variable qui peut être :
    Propriété m2scideclare | "Equivalent" Scilab
    Real | Donnée réelle
    Complex | Donnée complexe
    ? Property inconnue
    Ce champ est ignoré pour les types de données suivants : Cell , Struct , String et Boolean .

    • Toutes les informations données par m2scideclare sont comparées avec les données inférées, en cas de conflit, les données inférées sont conservées et un warning est affiché. Si vous êtes sûrs de vos informations, rapportez ce bug.

    Voici quelques exemples :

  • %m2scideclare var1|2 3|Double|Real : var1 est déclarée comme une matrice de Doubles de taille 2x3 et contenant des données réelles
  • %m2scideclare var2|2 3 10|Double|Complex : var2 est déclarée comme une hypermatrice de Doubles de taille 2x3x10 et contenant des données complexes
  • %m2scideclare var3(1,2).name|1 10|String|? : var3 est déclarée comme un tableau de Structs contenant une chaîne de caractères de taille 1x10 dans le champ 'name' de la Struct à l'indice (1,2)
  • %m2scideclare var4(1,5).entries|1 ?|Boolean|? : var4 est déclarée comme un tableau de Cells contenant un vecteur ligne de booléens à l'indice (1,5)
  • %m2scideclare var4(1,6).entries|? ?|Int|? : var4 est déclarée comme un tableau de Cells contenant un vecteur ligne de booléens à l'indice (1,5) et des données entières à l'indice (1,6)
  • %m2scideclare var5(*,*).name|1 ?|String|? : var5 est déclarée comme un tableau de Structs contenant une chaîne de caractères de taille 1xn dans chaque champ 'name'
  • %m2scideclare var6(2,*).entries|1 3|Double|Real : var6 est déclarée comme un tableau de Cells contenant un veteur de Doubles de taille 1x3 dans chaque élement de sa seconde ligne.

    • Authors

    V.C.


makecell

Scilab Function
Last update : 09/11/2006

makecell - creer une cell

Calling Sequence

y=makecell([dim1,dim2],cpnt1,cpnt2, ...)

Parameters

  • [dim1,dim2] : dimensions de la cell (dim1: nombre de ligne, dim2: nombre de colonnes)
  • cpnt1, cpnt2, ... : composantes de la cell (des strings, des doubles, des vecteurs, ...)

Description

La fonction makecell retourne une cell de taille dim1 x dim2 . Ces composantes sont cpnt1 , cpnt2 , ... (ils sont rangés par ligne).

Examples

y=makecell([2,3],10,'foo1',[1 2;3 4],'foo2',[6 7 8],'foo3');

See Also

cell ,


mstr2sci

Fonction M2SCI
Last update : 02/04/2004

mstr2sci - conversion d'une matrice de chaînes en matrice de caractères

Calling Sequence

a=mstr2sci(txt)

Parameters

  • txt : chaîne de caractères ou matrice de chaînes
  • a : vecteur ou matrice de caractères

Description

Cette fonction convertit une chaîne de caractères Scilab en vecteur de caractères. Le résultat est l'équivalent pour Scilab d'une chaîne de caractères Matlab.

Attention : mstr2sci ne doit pas être utilisée pour une programmation manuelle.

See Also

Chaines_de_caracteres_Matlab-Scilab ,

Authors

V.C.


mtlb_0

Fonction M2SCI
Last update : 30/03/2004

mtlb_0 - Fonction d'émulation de la transposition non-conjuguée de Matlab

Description

Dans plusieurs cas particuliers, la transposition non-conjuguée se comporte différemment dans Matlab et dans Scilab :

  • Avec des opérandes de type chaîne de caractère : L'opérateur .' est utilisé dans Scilab pour transposer des chaînes de caractères entières alors que Matlab fait la transposition caractère par caractère.

    • La fonction mtlb_0(A) est utilisée par mfile2sci pour remplacer A.' quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_0 :

  • Si A n'est pas une matrice de chaînes de caractères mtlb_0(A) peut être remplacé par A.'

    • Attention : mtlb_0 ne doit pas être utilisée pour une programmation manuelle.

    See Also

    Chaines_de_caracteres_Matlab-Scilab ,

    Authors

    V.C.


mtlb_all

Fonction M2SCI
Last update : 07/04/2004

mtlb_all - Fonction d'émulation de la fonction Matlab all

Description

Dans plusieurs cas particuliers, les fonctions all de Matlab et and de Scilab se comportent différemment :

  • Avec un argument d'entrée ( all(A) ), la fonction all de Matlab traite les valeurs selon la première dimension de A qui n'est pas 1 comme un vecteur alors que Scilab traite toutes les valeurs de A.
  • Avec deux arguments d'entrée ( all(A,dim) ), Matlab tolère une valeur de dim supérieure au nombre de dimensions de A alors que Scilab renvoie un message d'erreur dans ce cas.

    • La fonction mtlb_all(A[,dim]) est utilisée par mfile2sci pour remplacer all(A[,dim]) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_all :

  • Si A est un scalaire ou un vecteur R = mtlb_all(A) peut être remplacé par R = and(A)
  • Si A est une matrice R = mtlb_all(A) peut être remplacé par R = and(A,1)
  • Si A est une hypermatrice R = mtlb_all(A) peut être remplacé par R = and(A,firstnonsingleton(A)) ou par R = and(A,user_defined_value) si la première dimension non-égale à 1 de A est connue.
  • Si dim est inférieur ou égal au nombre de dimensions de A R = mtlb_all(A,dim) peut être remplacé par R = and(A,dim)
  • Si dim est supérieur au nombre de dimensions de A R = mtlb_all(A,dim) peut être remplacé par R = A<>0 si A n'est pas une matrice vide ou par R = A si A est une matrice vide.

    • Attention: mtlb_all ne doit pas être utilisée pour une programmation manuelle.

    See Also

    firstnonsingleton ,

    Authors

    V.C.


mtlb_any

Fonction M2SCI
Last update : 07/04/2004

mtlb_any - Fonction d'émulation de la fonction Matlab any

Description

Dans plusieurs cas particuliers, les fonctions any de Matlab et or de Scilab se comportent différemment :

  • Avec un argument d'entrée ( any(A) ), la fonction any de Matlab traite les valeurs selon la première dimension de A qui n'est pas 1 comme un vecteur alors que Scilab traite toutes les valeurs de A.
  • Avec deux arguments d'entrée ( any(A,dim) ), Matlab tolère une valeur de dim supérieure au nombre de dimensions de A alors que Scilab renvoie un message d'erreur dans ce cas.

    • La fonction mtlb_any(A[,dim]) est utilisée par mfile2sci pour remplacer any(A[,dim]) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_any :

  • Si A est un scalaire ou un vecteur R = mtlb_any(A) peut être remplacé par R = or(A)
  • Si A est une matrice R = mtlb_any(A) peut être remplacé par R = o(A,1)
  • Si A est une hypermatrice R = mtlb_any(A) peut être remplacé par R = or(A,firstnonsingleton(A)) ou par R = or(A,user_defined_value) si la première dimension non-égale à 1 de A est connue.
  • Si dim est inférieur ou égal au nombre de dimensions de A R = mtlb_any(A,dim) peut être remplacé par R = or(A,dim)
  • Si dim est supérieur au nombre de dimensions de A R = mtlb_any(A,dim) peut être remplacé par R = A<>0 si A n'est pas une matrice vide ou par R = A si A est une matrice vide.

    • Attention: mtlb_any ne doit pas être utilisée pour une programmation manuelle.

    See Also

    firstnonsingleton ,

    Authors

    V.C.


mtlb_axis

Fonction M2SCI
Last update : 13/10/2006

mtlb_axis - Fonction d'émulation de la fonction Matlab axis

Calling Sequence

mtlb_axis(X)
mtlb_axis(st)
mtlb_axis(axeshandle, ...)
[mode,visibility,direction]=mtlb_axis('state')

Parameters

  • X : un vecteur de réels ([xmin xmax ymin ymax] ou [xmin xmax ymin ymax zmin zmax])
  • st : une chaine de caractères ('auto', 'manual', 'tight', 'ij', 'xy', 'equal', 'square', 'vis3d', 'off', 'on')
  • axeshandle :handle sur l'axe courant

Description

La fonction Matlab axis n'a pas de fonction Scilab équivalente :

La fonction mtlb_axis(n,X[,normflag]) est utilisée par mfile2sci pour remplacer axis(...) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. ( 'fill' , 'image' et 'normal' ne sont pas implémentés).Pour obtenir un code plus performant on peut remplacer les appels à mtlb_axis par les appels à get(axeshandle,prop), ou prop est une propriété des axes (see axis_properties )

Attention : mtlb_axis ne doit pas être utilisée pour une programmation manuelle.

Authors

F.B.


mtlb_a

Fonction M2SCI
Last update : 30/03/2004

mtlb_a - Fonction d'émulation de l'addition Matlab

Description

Dans plusieurs cas particuliers, l'addition se comporte différemment dans Matlab et dans Scilab :

  • Avec des opérandes de type chaîne de caractères : L'opérateur + est utilisé dans Scilab pour concaténer des chaînes de caractères alors que Matlab calcule la somme des codes ASCII des opérandes.
  • Avec une matrice vide : Dans Scilab, si une des opérandes est une matrice vide alors le résultat de l'addition est l'autre opérande. Dans Matlab si une des opérandes est une matrice vide alors le résultat de l'addition est soit une erreur (la seconde opérande n'est pas un scalaire) soit une matrice vide.

    • La fonction mtlb_a(A,B) est utilisée par mfile2sci pour remplacer A+B quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_a :

  • Si A et B sont des chaînes de caractères, mtlb_a(A,B) peut être remplacé par asciimat(A)+asciimat(B)
  • Si A et B ne sont pas des matrices vides mtlb_a(A,B) peut être remplacé par A+B , sinon mtlb_a(A,B) peut être remplacé par [] .
  • Si mtlb_mode()==%T, alors mtlb_a(A,B) peut être remplacé par A+B dans tous les cas où A et B ne sont pas des chaînes de caractères.

    • Attention : mtlb_a ne doit pas être utilisée pour une programmation manuelle.

    See Also

    mtlb_mode ,

    Authors

    V.C.


mtlb_legendre

Fonction M2SCI
Last update : 13/10/2006

mtlb_legendre - Fonction d'émulation de la fonction Matlab legendre

Calling Sequence

P=mtlb_legendre(n,X)
P=mtlb_legendre(n,X[,normflag])

Parameters

  • X : un scalaire, un vecteur, une matrice ou hypermatrice d'elements compris dans [-1 1]
  • n : un entier positif
  • normflag : une chaine de caracteres ( 'sch' ou 'norm' )

Description

Dans plusieurs cas particuliers, la fonction legendre se comporte différemment dans Matlab et dans Scilab :

  • L'appel de fonction Scilab legendre(m,n,X) évalue la fonction de legendre de degré n et d'ordre m pour tous les éléments de X . Par contre l'appel de fonction Scilab legendre(m,n,X) évalue la fonction de legendre de degré n et d'ordre m=0,1,...,n pour tous les éléments de X .
  • Le mode normflag='sch' n'est pas implémenté avec Scilab
  • La fonction legendre de Scilab ne fonctionne pas si X est une hypermatrice

    • La fonction mtlb_legendre(n,X[,normflag]) est utilisée par mfile2sci pour remplacer legendre(n,X[,normflag]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_legendre :

  • If X is a scalar, a vector or a matrix mtlb_legendre(n,X[,'norm']) may be replaced by legendre(n,0:n,X[,'norm'])

    • Attention : mtlb_legendre ne doit pas être utilisée pour une programmation manuelle.

    Authors

    F.B.


mtlb_box

Fonction M2SCI
Last update : 08/06/2004

mtlb_box - Fonction d'émulation de la fonction Matlab box

Description

Il n'y a pas de fonction Scilab équivalente à la fonction Matlab box mais elle peut facilement être remplacée.

La fonction mtlb_box([axes_handle[,val]]) est utilisée par mfile2sci pour remplacer box([axes_handle[,val]]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_box :

  • Pour un appel sans paramètre d'entrée, mtlb_box() peut être remplacé par a=gca();if a.box=="on" then a.box="off";else a.box="on";end;
  • Si axes_handle est une chaîne de caractères, mtlb_box(axes_handle) peut être remplacé par a=gca();a.box=convstr(axes_handle,"l");
  • Si axes_handle est un handle graphique, mtlb_box(axes_handle) peut être remplacé par if axes_handle.box=="on" then axes_handle.box="off";else axes_handle.box="on";end;
  • Si axes_handle est un handle graphique et val est une chaîne de caractères, mtlb_box(axes_handle,val) peut être remplacé par axes_handle.box=convstr(val,"l");

    • Attention : mtlb_box ne doit pas être utilisée pour une programmation manuelle.

    See Also

    axes_properties ,

    Authors

    V.C.


mtlb_close

Fonction M2SCI
Last update : 01/07/2004

mtlb_close - Fonction d'émulation de la fonction Matlab close

Description

Suivant le type de la figure courante (uicontrol ou graphique), l'équivalent Scilab pour la fonction Matlab close est différent :

  • Si la figure courante est de type uicontrol : l'équivalent Scilab pour la fonction Matlab close est close
  • Si la fenêtre courante est une fenêtre graphique : l'équivalent Scilab pour la fonction Matlab close est xdel ou delete
  • Dans Scilab on ne récupère pas de statut d'erreur.

    • La fonction mtlb_close([h]) est utilisée par mfile2sci pour remplacer close([h]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_close :

  • Si h est une figure de type uicontrol, mtlb_close(h) peut être remplacé par close(h)
  • Si h est une figure graphique, mtlb_close(h) peut être remplacé par delete(h)

    • Attention : mtlb_close ne doit pas être utilisée pour une programmation manuelle.

    See Also

    xdel , delete , winsid , close ,

    Authors

    V.C.


mtlb_colordef

Fonction M2SCI
Last update : 08/06/2004

mtlb_colordef - Fonction d'émulation de la fonction Matlab colordef

Description

Il n'y a pas de fonction Scilab équivalente à la fonction Matlab colordef mais il existe des instructions équivalentes.

La fonction h = mtlb_colordef(color_option) ou h = mtlb_colordef(fig,color_option) est utilisée par mfile2sci pour remplacer colordef(color_option) ou colordef(fig,color_option) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_colordef :

  • Pour les appels avec un paramètre d'entrée, si color_option est égal à "black" ou "none" mtlb_colordef(color_option) peut être remplacé par fig = gcf();fig.background = -1;
  • Pour les appels avec un paramètre d'entrée, si color_option est égal à "white" mtlb_colordef(color_option) peut être remplacé par fig = gcf();fig.background = -2;
  • Pour les appels avec deux paramètres d'entrée, si fig est un handle graphique et color_option est égal à "black" ou "none" mtlb_colordef(color_option) peut être remplacé par fig.background = -1;
  • Pour les appels avec deux paramètres d'entrée, si fig est un handle graphique et color_option est égal à "white" mtlb_colordef(color_option) peut être remplacé par fig.background = -2;
  • Pour les appels avec deux paramètres d'entrée, si fig est égal à "new" et color_option est égal à "black" ou "none" mtlb_colordef(color_option) peut être remplacé par fig = scf(max(winsid())+1);fig.background = -1;
  • Pour les appels avec deux paramètres d'entrée, si fig est égal à "new" et color_option est égal à "white" mtlb_colordef(color_option) peut être remplacé par fig = scf(max(winsid())+1);fig.background = -2;
  • Pour les appels avec un paramètre de sortie h , ajouter h = fig; à la suite des instructions équivalentes.

    • Attention : mtlb_colordef ne doit pas être utilisée pour une programmation manuelle.

    See Also

    figure_properties ,

    Authors

    V.C.


mtlb_conv

Fonction M2SCI
Last update : 15/06/2004

mtlb_conv - Fonction d'émulation de la fonction Matlab conv

Description

Dans plusieurs cas particuliers, la fonction Matlab conv et la fonction Scilab convol se comportent différemment :

  • Avec des vecteurs colonne comme paramètres d'entrées : Si au moins l'un des deux paramètres d'entrée de la fonction Matlab conv est un vecteur colonne alors la valeur retournée sera un vecteur colonne mais la fonction Scilab convol retourne toujours un vecteur ligne.

    • La fonction mtlb_conv(u,v) est utilisée par mfile2sci pour remplacer conv(u,v) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_conv :

  • Si u et v sont des vecteurs ligne, mtlb_conv(u,v) peut être remplacé par convol(u,v)
  • Si u ou v est un vecteur colonne, mtlb_conv(u,v) peut être remplacé par convol(u,v).'
  • Si u et v sont des vecteurs colonne, mtlb_conv(u,v) peut être remplacé par convol(u,v).'

    • La fonction Scilab convol retourne parfois des valeurs qui peuvent être arrondies en utilisant clean pour avoir un résultat plus proche de Matlab.

    Attention : mtlb_conv ne doit pas être utilisée pour une programmation manuelle.

    See Also

    clean ,

    Authors

    V.C.


mtlb_cumprod

Fonction M2SCI
Last update : 07/04/2004

mtlb_cumprod - Fonction d'émulation de la fonction Matlab cumprod

Description

Dans plusieurs cas particuliers, la fonction cumprod se comporte différemment dans Matlab et dans Scilab :

  • Avec un argument d'entrée ( cumsum(A) ) : La fonction cumprod de Matlab traite les valeurs suivant la première dimension qui n'est pas 1 comme des vecteurs alors que Scilab traite toutes les valeurs de A.
  • Avec deux arguments d'entrée ( cumprod(A,dim) ) : Matlab tolère une valeur de dim supérieure au nombre de dimensions de A alors que Scilab renvoie un message d'erreur dans ce cas.

    • La fonction R = mtlb_cumprod(A,[,dim]) est utilisée par mfile2sci pour remplacer cumprod(A,[,dim]) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_cumprod :

  • Si dim est inférieure ou égale au nombre de dimensiopns de A R = mtlb_cumprod(A,dim) peut être remplacé par R = cumprod(A,dim)
  • Si dim est supérieure au nombre de dimensiopns de A R = mtlb_cumprod(A,dim) peut être remplacé par R = A

    • Attention : mtlb_cumprod ne doit pas être utilisée pour une programmation manuelle.

    See Also

    firstnonsingleton ,

    Authors

    V.C.


mtlb_cumsum

Fonction M2SCI
Last update : 07/04/2004

mtlb_cumsum - Fonction d'émulation de la fonction Matlab cumsum

Description

Dans plusieurs cas particuliers, la fonction cumsum se comporte différemment dans Matlab et dans Scilab :

  • Avec un argument d'entrée ( cumsum(A) ) : La fonction cumsum de Matlab traite les valeurs suivant la première dimension qui n'est pas 1 comme des vecteurs alors que Scilab traite toutes les valeurs de A.
  • Avec deux arguments d'entrée ( cumsum(A,dim) ) : Matlab tolère une valeur de dim supérieure au nombre de dimensions de A alors que Scilab renvoie un message d'erreur dans ce cas.

    • La fonction R = mtlb_cumsum(A,[,dim]) est utilisée par mfile2sci pour remplacer cumsum(A,[,dim]) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_cumsum :

  • Si dim est inférieure ou égale au nombre de dimensiopns de A R = mtlb_cumsum(A,dim) peut être remplacé par R = cumsum(A,dim)
  • Si dim est supérieure au nombre de dimensiopns de A R = mtlb_cumsum(A,dim) peut être remplacé par R = A

    • Attention : mtlb_cumsum ne doit pas être utilisée pour une programmation manuelle.

    See Also

    firstnonsingleton ,

    Authors

    V.C.


mtlb_dec2hex

Fonction M2SCI
Last update : 16/06/2004

mtlb_dec2hex - Fonction d'émulation de la fonction Matlab dec2hex

Description

Dans plusieurs cas particuliers, la fonction dec2hex se comporte différemment dans Matlab et dans Scilab :

  • Avec la matrice vide : La fonction Matlab dec2hex retourne "" mais la fonction Scilab renvoie [].
  • Avec des paramètres d'entrée complexes : La fonction Matlab dec2hex enlève automatiquement la partie imaginaire mais pas la fonction Scilab.
  • La fonction Matlab dec2hex renvoie toujours un vecteur colonne mais la fonction Scilab renvoie un matrice de la même taille que le paramètre d'entrée.
  • La fonction Matlab dec2hex peut avoir deux paramètres d'entrée mais pas dans Scilab.

    • La fonction mtlb_dec2hex(D[,N]) est utilisée par mfile2sci pour remplacer dec2hex(D[,N]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_dec2hex :

  • Si D n'est pas une matrice vide, mtlb_dec2hex(D) peut être remplacé par matrix(dec2hex(real(D)),-1,1) si D est complexe et par matrix(dec2hex(D),-1,1) dans les autres cas.

    • Attention : mtlb_dec2hex ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_delete

Fonction M2SCI
Last update : 07/05/2004

mtlb_delete - Fonction d'émulation de la fonction Matlab delete

Description

La fonction mtlb_delete(A) est utilisée par mfile2sci pour remplacer delete(A) quand il n'était pas possible de savoir ce qu'était le paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_delete :

  • Si A est une chaîne de caractères mtlb_delete(A) peut être remplacé par mdelete(A)
  • Si A est un handle graphique mtlb_delete(A) peut être remplacé par delete(A)

    • Attention : mtlb_delete ne doit pas être utilisée pour une programmation manuelle.

    See Also

    mdelete ,

    Authors

    V.C.


mtlb_diag

Fonction M2SCI
Last update : 07/04/2004

mtlb_diag - Fonction d'émulation de la fonction Matlab diag

Description

Dans plusieurs cas particuliers, la fonction diag se comporte différemment dans Matlab et dans Scilab :

  • Avec des matrices de chaînes de caractères : La fonction diag de Scilab considère les chaînes comme des objets alors que Matlab considère chaque caractère séparément.

    • La fonction y = mtlb_diag(x[,dim]) est utilisée par mfile2sci pour remplacer y = diag(x[,dim]) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_diag :

  • Si x n'est pas une matrice de chaînes de caractères y = mtlb_diag(x,dim) peut être remplacé par y = diag(x[,dim])

    • Attention : mtlb_diag ne doit pas être utilisée pour une programmation manuelle.

    See Also

    Chaines_de_caracteres_Matlab-Scilab ,

    Authors

    V.C.


mtlb_diff

Fonction M2SCI
Last update : 07/04/2004

mtlb_diff - Fonction d'émulation de la fonction Matlab diff

Description

Dans plusieurs cas particuliers, la fonction diff se comporte différemment dans Matlab et dans Scilab :

  • Avec deux paramètres d'entrée : la fonction diff de Scilab considère toutes les valeurs du premier paramètre comm un vecteur ce que Matlab ne fait pas.
  • Avec trois paramètres d'entrée : si la dimension du premier paramètre suivant la dimension donnée par le troisième paramètre atteint 1 avant que la fin des n itérations, Matlab passe à la dimension suivante n'étant pas un 1 ce que Scilab ne fait pas.

    • La fonction mtlb_diff(A[,n[,dim]]) est utilisée par mfile2sci pour remplacer diff(A[,n[,dim]]) quand il n'était pas possible de savoir ce qu'étaient les entrées pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_diff :

  • Avec deux entrées, si A est un scalaire ou un vecteur mtlb_diff(A,n) peut être remplacé par diff(A,n)
  • Avec deux entrées, si la taille de A suivant la dimension donnée par dim ne peut pas atteindre 1 mtlb_diff(A,n,dim) peut être remplacé par diff(A,n,dim)

    • Attention : mtlb_diff ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_dir

Fonction M2SCI
Last update : 28/06/2004

mtlb_dir - Fonction d'émulation de la fonction Matlab dir

Description

La fonction dir se comporte différemment dans Matlab et dans Scilab :

  • Quand le résultat est stocké dans une variable: La fonction Matlab dir renvoie une structure mais la fonction Scilab retourne une tlist de type 'dir', ce qui fait que les données ne peuvent être extraites de la même manière.

    • La fonction mtlb_dir([path]) est utilisée par mfile2sci pour remplacer dir([path]) quand la sortie est stockée dans une variable. Il n'est pas possible de remplacer cette fonction, sinon (si on la remplace par dir ) les données ne pourront pas être extraites comme dans Matlab. Par exemple, l'équivalent Scilab pour l'instruction Matlab L=dir;file_name=L(1).name; est L=dir();file_name=L.name(1); .

    Attention : mtlb_dir ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_double

Fonction M2SCI
Last update : 07/04/2004

mtlb_double - Fonction d'émulation de la fonction Matlab double

Description

Dans plusieurs cas particuliers, la fonction double se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée de type chaîne de caractère : La fonction double de Scilab ne tolère pas ce type d'entrée alors que la fonction double de Matlab retourne une matrice de codes ASCII.
  • Avec un paramètre d'entrée de type booléen : La fonction double de Scilab ne tolère pas ce type d'entrée alors que la fonction double de Matlab retourne une matrice de doubles.

    • La fonction mtlb_double(A) est utilisée par mfile2sci pour remplacer double(A) quand il n'était pas possible de savoir ce qu'était A pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_double :

  • Si A est une chaîne de caractère mtlb_double(A) peut être remplacé par asciimat(A)
  • Si A est une matrice de booléens mtlb_double(A) peut être remplacé par bool2s(A)
  • Si A est une matrice de doubles mtlb_double(A) peut être remplacé par A

    • Attention : mtlb_double ne doit pas être utilisée pour une programmation manuelle.

    See Also

    asciimat , bool2s ,

    Authors

    V.C.


mtlb_echo

Fonction M2SCI
Last update : 28/10/2004

mtlb_echo - Fonction d'émulation de la fonction Matlab echo

Description

Il n'y a pas d'équivalent Scilab pour la fonction Matlab echo mais quelques cas particuliers peuvent être remplacés par des appels à la fonction Scilab mode :

  • echo : est équivalent à mode(abs(mode()-1)) dans Scilab pour les scripts et les fonctions non-compilées
  • echo on : est équivalent à mode(1) dans Scilab pour les scripts et les fonctions non-compilées
  • echo off : est équivalent à mode(0)

    • La fonction mtlb_echo(arg1[,arg2]) est utilisée par mfile2sci pour remplacer echo arg1 [arg2] quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_echo :

  • Si arg1 est égal à "on" mtlb_echo(arg1) peut être remplacé par mode(1)
  • Si arg1 est égal à "off" mtlb_echo(arg1) peut être remplacé par mode(0)

    • Attention : mtlb_echo ne doit pas être utilisée pour une programmation manuelle.

    See Also

    mode ,

    Authors

    V.C.


mtlb_eig

Fonction M2SCI
Last update : 07/04/2004

mtlb_eig - Fonction d'émulation de la fonction Matlab eig

Description

Dans plusieurs cas particuliers, les fonctions eig de Matlab et spec de Scilab se comportent différemment :

  • Avec un argument d'entrée ( A ) et deux arguments de sortie ( V , D ), les valeurs obtenues dans Scilab et dans Matlab sont de signe opposé.

    • La fonction [V,D] = mtlb_eig(A,B) est utilisée par mfile2sci pour remplacer [V,D] = eig(A) . Cette fonction va déterminer la sémantique correcte pendant l'exécution. Elle ne peut être remplacée.

    Attention : mtlb_eig ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_eval

Fonction M2SCI
Last update : 07/04/2004

mtlb_eval - Fonction d'émulation de la fonction Matlab eval

Description

L'équivalent Scilab pour la fonction Matlab eval est différent suivant ses entrées et sorties.

La fonction mtlb_eval(str1,str2) est utilisée par mfile2sci pour remplacer eval parce qu'il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_eval :

  • Pour les appels avec une entrée et pas de sortie, mtlb_eval(str1) peut être remplacé par evstr(str1) si str1 est une expression Scilab valid ou par execstr(str1) si str1 est une instruction Scilab valid.
  • Pour les appels avec une entrée et une sortie, val=mtlb_eval(str1) peut être remplacé par val=evstr(str1) si str1 est une instruction Scilab valid.
  • Pour les appels avec deux entrées et une sortie, mtlb_eval(str1,str2) peut être remplacé par: if execstr(str1,"errcatch")<>0 then execstr(str2); end si str1 et str2 sont des instructions Scilab valides.
  • Pour les appels avec une entrée et plus d'une sortie, [val1,val2,...]=mtlb_eval(str1) peut être remplacé par: execstr("[val1,val2,...]"+str1) si str1 est une instruction Scilab valide.
  • Pour les appels avec deux entrées et plus d'une sortie, [val1,val2,...]=mtlb_eval(str1,str2) peut être remplacé par: if execstr("[val1,val2,...]"+str1,"errcatch")<>0 then execstr("[val1,val2,...]"+str2); end si str1 et str2 sont des instructions Scilab valides.

    • Attention : mtlb_eval ne doit pas être utilisée pour une programmation manuelle.

    See Also

    evstr , execstr ,

    Authors

    V.C.


mtlb_exist

Fonction M2SCI
Last update : 07/04/2004

mtlb_exist - Fonction d'émulation de la fonction Matlab exist

Description

Il n'y a pas d'équivalent Scilab pour la fonction Matlab exist sauf si l'entrée est une variable. La fonction Scilab mtlb_exist est une émulation partielle de cette fonction.

La fonction r = mtlb_exist(nam[,tp]) est utilisée par mfile2sci pour remplacer exist(nam[,tp]) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_exist :

  • Avec une entrée et si nam est un nom de variable, mtlb_exist(nam) peut être remplacé par exists(nam)

    • Attention : mtlb_exist ne doit pas être utilisée pour une programmation manuelle.

    See Also

    exists ,

    Authors

    V.C.


mtlb_eye

Fonction M2SCI
Last update : 07/04/2004

mtlb_eye - Fonction d'émulation de la fonction Matlab eye

Description

Dans plusieurs cas particuliers, la fonction eye se comporte différemment dans Matlab et dans Scilab :

  • Avec une entrée qui est un scalaire : La fonction Matlab eye retourne une matrice n x n alors que Scilab retourne 1.

    • La fonction mtlb_eye(A) est utilisée par mfile2sci pour remplacer eye(A) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_eye :

  • Si A est un scalaire mtlb_eye(A) peut être remplacé par eye(A,A)
  • Si A n'est pas un scalaire mtlb_eye(A) peut être remplacé par eye(A)

    • Attention : mtlb_eye ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_e

Fonction M2SCI
Last update : 30/03/2004

mtlb_e - Fonction d'émulation de l'extraction Matlab

Description

Dans plusieurs cas particuliers, l'extraction se comporte différemment dans Matlab et dans Scilab :

  • Lors de l'extraction de données d'une matrice avec comme indice un vecteur : Matlab retourne un vecteur ligne alors que Scilab retourne un vecteur colonne.
  • Lors de l'extraction de données d'une matrice d'une chaîne de caractères : étant donné que les matrices de chaînes de caractères peuvent être adressées comme tout autre type de matrice dans Matlab (chaque caractère peut être adressé), l'extraction à partir d'une telle matrice ne change pas des autres types. Mais dans Scilab ceci ne peut être fait de la même manière et la fonction part doit être utilisée.

    • La fonction mtlb_e(B,k) est utilisée par mfile2sci pour remplacer A=B(k) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_e :

  • Si B est un vecteur A=mtlb_e(B,k) peut être remplacé par A=B(k)
  • Si B est une matrice A=mtlb_e(B,k) peut être remplacé par A=B(k).'
  • Si B est une chaîne de caractères et k est une scalaire ou un vecteur A=mtlb_e(B,k) peut être remplacé par A=part(B,k)

    • Attention : mtlb_e ne doit pas être utilisée pour une programmation manuelle.

    See Also

    Chaines_de_caracteres_Matlab-Scilab , part ,

    Authors

    V.C.


mtlb_false

Fonction M2SCI
Last update : 07/04/2004

mtlb_false - Fonction d'émulation de la fonction Matlab false

Description

Il n'y a pas d'équivalent Scilab pour la fonction Matlab false , cependant la fonction Scilab zeros retourne un résultat interprété de la même façon pour Scilab.

Dans plusieurs cas particuliers, la fonction Matlab false et la fonction Scilab zeros se comporte différemment :

  • Avec une entrée qui est un scalaire : La fonction Matlab false retourne une matrice n x n alors que la fonction Scilab zeros retourne 0.

    • La fonction mtlb_false(A) est utilisée par mfile2sci pour remplacer false(A) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_false :

  • Si A est un scalaire mtlb_false(A) peut être remplacé par zeros(A,A)
  • Si A n'est pas un scalaire mtlb_false(A) peut être remplacé par zeros(A)

    • Attention : mtlb_false ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_fftshift

Fonction M2SCI
Last update : 28/07/2004

mtlb_fftshift - Fonction d'émulation de la fonction Matlab fftshift

Description

Dans plusieurs cas particuliers, la fonction fftshift se comporte différemment dans Matlab et dans Scilab :

  • Avec les chaînes de caractère : étant donné que les chaînes de caractères sont vues différemment par Matlab et Scilab, le résulat peut être différent pour ce type d'entrée.
  • Avec deux paramètres d'entrée : Matlab autorise dim a être supérieur au nombre de dimension de A mais pas Scilab (message d'erreur).

    • La fonction mtlb_fftshift(A,[dim]) est utilisée par mfile2sci pour remplacer fftshift(A,[dim]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_fftshift :

  • Si A n'est pas une matrice de chaînes de caractères, mtlb_fftshift(A) peut être remplacé par fftshift(A)
  • Si A n'est pas une matrice de chaînes de caractères et dim est inférieur ou égal au nombre de dimension de A , mtlb_fftshift(A,dim) peut être remplacé par fftshift(A,dim)

    • Attention : mtlb_fftshift ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_fft

Fonction M2SCI
Last update : 07/04/2004

mtlb_fft - Fonction d'émulation de la fonction Matlab fft

Description

Dans plusieurs cas particuliers, la fonction fft se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée : si ce paramètre est un scalaire ou un vecteur l'équivalent Scilab pour la fonction Matlab fft est fft(...,-1) et si ce paramètre est une matrice l'équivalent Scilab pour l'appel Matlab à fft est fft(...,-1,2,1)

    • La fonction mtlb_fft(X[,n,[job]]) est utilisée par mfile2sci pour remplacer fft(X[,n,[job]]) quand il n'était pas possible de savoir ce qu'étaient les entrées pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_fft :

  • Si X est un scalaire ou un vecteur mtlb_fft(X,-1) peut être remplacé par fft(X,-1)
  • Si X est une matrice mtlb_fft(X,-1) peut être remplacé par fft(X,-1,2,1)

    • Attention : mtlb_fft ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_findstr

Fonction M2SCI
Last update : 28/07/2004

mtlb_findstr - Fonction d'émulation de la fonction Matlab findstr

Description

Il n'y a pas de fonction Scilab équivalente à la fonction Matlab findstr .

La fonction mtlb_findstr(A,B) est utilisée par mfile2sci pour remplacer findstr(A,B) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_findstr :

  • Si A est toujours plus longue que B (i.e. strfind peut remplacer findstr en Matlab), mtlb_findstr(A,B) peut être remplacé par strindex(A,B)

    • Attention : mtlb_findstr ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_find

Fonction M2SCI
Last update : 08/04/2004

mtlb_find - Fonction d'émulation de la fonction Matlab find

Description

Dans plusieurs cas particuliers, la fonction find se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée qui est un vecteur colonne ou une matrice : La fonction Matlab find retourne un(des) vecteur(s) colonne alors que Scilab retourne un(des) vecteur(s) ligne.
  • Avec trois paramètres de sortie : La fonction Matlab find peut retourner trois valeurs mais pas la fonction Scilab.

    • La fonction [i[,j[,v]]] = mtlb_find(B) est utilisée par mfile2sci pour remplacer [i[,j[,v]]] = find(B) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_find :

  • Pour un appel avec un seul paramètre de sortie, si B est un vecteur ligne, i = mtlb_find(B) peut être remplacé par i = find(B)
  • Pour un appel avec un seul paramètre de sortie, si B n'est pas un vecteur ligne, i = mtlb_find(B) peut être remplacé par i = matrix(find(B),-1,1)
  • Pour un appel avec deux paramètres de sortie, si B est un vecteur ligne, [i,j] = mtlb_find(B) peut être remplacé par [i,j] = find(B)
  • Pour un appel avec un seul paramètre de sortie, si B n'est pas un vecteur ligne, [i,j] = mtlb_find(B) peut être remplacé par [i,j] = find(B);i = matrix(i,-1,1);j = matrix(j,-1,1);

    • Attention : mtlb_find ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_fliplr

Fonction M2SCI
Last update : 28/07/2004

mtlb_fliplr - Fonction d'émulation de la fonction Matlab fliplr

Description

Dans plusieurs cas particuliers, la fonction fliplr se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée de type chaîne de caractère : étant donné que Scilab et Matlab ne considèrent pas les chaînes de caractère de la même façon, le résultat pout être différent pour une entrée de ce type.

    • La fonction mtlb_fliplr(A) est utilisée par mfile2sci pour remplacer fliplr(A) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_fliplr :

  • Si A n'est pas une matrice de chaînes de caractères, mtlb_fliplr(A) peut être remplacé par fliplr(A)

    • Attention : mtlb_fliplr ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_fopen

Fonction M2SCI
Last update : 28/07/2004

mtlb_fopen - Fonction d'émulation de la fonction Matlab fopen

Description

Dans plusieurs cas particuliers, la fonction Matlab fopen et la fonction Scilab mopen se comportent différemment :

  • La fonction Scilab ne renvoie pas de pessage d'erreur utilisable
  • L'indentifieur de fichier n'est pas initialisé dans Scilab en cas d'erreur alors que Matlab lui fixe la valeur -1
  • La fonction Matlab peut fonctionner avec des arguments qui n'existent pas en Scilab : options de permission...

    • La fonction mtlb_fopen(filename,permission) est utilisée par mfile2sci pour remplacer fopen(filename,permission) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_fopen :

  • Si le message d'erreur n'est pas utilisé et si aucune erreur ne peut avoir lieu, mtlb_fopen(filename,permission) peut être remplacé par mopen(filename,permission,0)

    • Attention : mtlb_fopen ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_format

Fonction M2SCI
Last update : 28/07/2004

mtlb_format - Fonction d'émulation de la fonction Matlab format

Description

Dans plusieurs cas particuliers, la fonction format se comporte différemment dans Matlab et dans Scilab :

  • Certains formats Matlab n'existent pas en Scilab.
  • La séquence d'appel de format est différente en Scilab et Matlab.

    • La fonction mtlb_format(type,prec) est utilisée par mfile2sci pour remplacer format([type prec]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_format :

  • Si type="" et prec="" mtlb_format("","") peut être remplacé par format("v",6)
  • Si type="+" et prec="" mtlb_format("+","") peut être remplacé par format(6)
  • Si type="long" et prec="" mtlb_format("long","") peut être remplacé par format(16)
  • Si type="long" et prec="e" mtlb_format("long","e") peut être remplacé par format("e"16)
  • Si type="long" et prec="g" mtlb_format("long","g") peut être remplacé par format("e"16)
  • Si type="short" et prec="" mtlb_format("short","") peut être remplacé par format(6)
  • Si type="short" et prec="e" mtlb_format("short","e") peut être remplacé par format("e"6)
  • Si type="short" et prec="g" mtlb_format("short","g") peut être remplacé par format("e"6)

    • Attention : mtlb_format ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_fprintf

Fonction M2SCI
Last update : 28/07/2004

mtlb_fprintf - Fonction d'émulation de la fonction Matlab fprintf

Description

Il n'y a pas d'équivalent Scilab exact pour la fonction Matlab fprintf . La fonction Scilab mfprintf et la fonction Matlab fprintf se comportent différemment dans beaucoup de cas mais sont équivalentes dans plusieurs cas.

La fonction mtlb_fprintf(varargin) est utilisée par mfile2sci pour remplacer fprintf . Cette fonction va déterminer la sémantique correcte pendant l'exécution. Il est quelquefois possible de remplacer les appels à mtlb_fprintf par des appels à mfprintf .

Attention : mtlb_fprintf ne doit pas être utilisée pour une programmation manuelle.

See Also

mfprintf ,

Authors

V.C.


mtlb_fread

Fonction M2SCI
Last update : 28/07/2004

mtlb_fread - Fonction d'émulation de la fonction Matlab fread

Description

Il n'y a pas d'équivalent Scilab pour la fonction Matlab fread . La fonction Scilab mget et la fonction Matlab fread se comportent différemment dans beaucoup de cas mais sont équivalentes dans plusieurs cas.

La fonction mtlb_fread(varargin) est utilisée par mfile2sci pour remplacer fread . Cette fonction va déterminer la sémantique correcte pendant l'exécution. Il est quelquefois possible de remplacer les appels à mtlb_fread par des appels à mget .

Attention : mtlb_fread ne doit pas être utilisée pour une programmation manuelle.

See Also

mget ,

Authors

V.C.


mtlb_fscanf

Fonction M2SCI
Last update : 28/07/2004

mtlb_fscanf - Fonction d'émulation de la fonction Matlab fscanf

Description

Il n'y a pas d'équivalent Scilab exact pour la fonction Matlab fscanf . La fonction Scilab mfscanf et la fonction Matlab fscanf se comportent différemment dans beaucoup de cas mais sont équivalentes dans plusieurs cas.

La fonction mtlb_fscanf(varargin) est utilisée par mfile2sci pour remplacer fscanf . Cette fonction va déterminer la sémantique correcte pendant l'exécution. Il est quelquefois possible de remplacer les appels à mtlb_fscanf par des appels à mfscanf .

Attention : mtlb_fscanf ne doit pas être utilisée pour une programmation manuelle.

See Also

mfscanf ,

Authors

V.C.


mtlb_full

Fonction M2SCI
Last update : 08/04/2004

mtlb_full - Fonction d'émulation de la fonction Matlab full

Description

Dans plusieurs cas particuliers, la fonction full se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée de type chaîne de caractère : La fonction Matlab full peut être utilisée avec des chaînes de caractères ce qui n'est pas possible dans Scilab.
  • Avec un paramètre d'entrée de type booléen : La fonction Matlab full peut être utilisée avec des booléens ce qui n'est pas possible dans Scilab.

    • La fonction mtlb_full(A) est utilisée par mfile2sci pour remplacer full(A) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_full :

  • Si A est une matrice de doubles mtlb_full(A) peut être remplacé par full(A)
  • Si A est une matrice de booléens mtlb_full(A) peut être remplacé par full(bool2s(A))

    • Attention : mtlb_full ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_write

Fonction M2SCI
Last update : 28/07/2004

mtlb_write - Fonction d'émulation de la fonction Matlab write

Description

Il n'y a pas d'équivalent Scilab pour la fonction Matlab write . La fonction Scilab mput et la fonction Matlab write se comportent différemment dans beaucoup de cas mais sont équivalentes dans plusieurs cas.

La fonction mtlb_write(varargin) est utilisée par mfile2sci pour remplacer write . Cette fonction va déterminer la sémantique correcte pendant l'exécution. Il est quelquefois possible de remplacer les appels à mtlb_write par des appels à mput .

Attention : mtlb_write ne doit pas être utilisée pour une programmation manuelle.

See Also

mput ,

Authors

V.C.


mtlb_grid

Fonction M2SCI
Last update : 28/07/2004

mtlb_grid - Fonction d'émulation de la fonction Matlab grid

Description

Il n'y a pas de fonction Scilab equivalente à la fonction Matlab grid mais il existe des instructions équivalentes

La fonction mtlb_grid(flag_or_handle[,flag]) est utilisée par mfile2sci pour remplacer grid(flag_or_handle[,flag]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_grid :

  • Avec un paramètre d'entrée, si flag est égal à "on" mtlb_grid(flag) peut être remplacé par set(gca(),"grid",[1 1])
  • Avec un paramètre d'entrée, si flag est égal à "off" mtlb_grid(flag) peut être remplacé par set(gca(),"grid",[-1 -1])
  • Avec deux paramètres d'entrée, si flag est égal à "on" mtlb_grid(axes_handle,flag) peut être remplacé par axes_handle.grid=[1 1]
  • Avec un paramètre d'entrée, si flag est égal à "off" mtlb_grid(axes_handle,flag) peut être remplacé par axes_handle.grid=[-1 -1]

    • Attention : mtlb_grid ne doit pas être utilisée pour une programmation manuelle.

    See Also

    axes_properties ,

    Authors

    V.C.


mtlb_hold

Fonction M2SCI
Last update : 01/07/2004

mtlb_hold - Fonction d'émulation de la fonction Matlab hold

Description

Il n'y a pas de fonction Scilab equivalente à la fonction Matlab hold mais il existe des instructions équivalentes

La fonction mtlb_hold(flag) est utilisée par mfile2sci pour remplacer hold flag quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_hold :

  • Si flag est égal à "on" mtlb_hold(flag) peut être remplacé par set(gca(),"auto_clear","off")
  • Si flag est égal à "off" mtlb_hold(flag) peut être remplacé par set(gca(),"auto_clear","on")

    • Attention : mtlb_hold ne doit pas être utilisée pour une programmation manuelle.

    See Also

    axes_properties ,

    Authors

    V.C.


mtlb_fft

Fonction M2SCI
Last update : 29/07/2004

mtlb_fft - Fonction d'émulation de la fonction Matlab ifft

Description

Dans plusieurs cas particuliers, la fonction Matlab ifft et la fonction Scilab fft se comportent différemment :

  • Avec un paramètre d'entrée : si ce paramètre est un scalaire ou un vecteur l'équivalent Scilab pour la fonction Matlab ifft(A) est fft(A,1) et si ce paramètre est une matrice l'équivalent Scilab pour l'appel Matlab à ifft est fft(A,1,2,1)

    • La fonction mtlb_ifft(X[,n,[job]]) est utilisée par mfile2sci pour remplacer ifft(X[,n,[job]]) quand il n'était pas possible de savoir ce qu'étaient les entrées pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_ifft :

  • Si X est un scalaire ou un vecteur mtlb_ifft(X,1) peut être remplacé par fft(X,1)
  • Si X est une matrice mtlb_ifft(X,1) peut être remplacé par fft(X,1,2,1)

    • Attention : mtlb_ifft ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_imp

Fonction M2SCI
Last update : 30/03/2004

mtlb_imp - Fonction d'émulation de l'opérateur "deux points" de Matlab

Description

Dans plusieurs cas particuliers, l'opérateur "deux points" se comporte différemment dans Matlab et dans Scilab :

  • Avec des matrices vides : L'opérateur : doit être utilisé avec des scalaires dans Scilab et retourne un message d'erreur quand on l'utilise avec des matrices vides alors que Matlab renvoie [] dans tous ces cas.

    • La fonction mtlb_imp(A,B[,C]) est utilisée par mfile2sci pour remplacer A:B[:C] quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_imp :

  • Si A , B et C ne sont pas des matrices vides mtlb_imp(A,B[,C]) peut être remplacé par A:B[:C]

    • Attention : mtlb_imp ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_int16

Fonction M2SCI
Last update : 08/04/2004

mtlb_int16 - Fonction d'émulation de la fonction Matlab int16

Description

Dans plusieurs cas particuliers, la fonction int16 se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée complexe : La fonction Matlab int16 peut être utilisée avec des complexes mais pas la fonction Scilab.
  • Avec la valeur %inf : Matlab retourne 32767 alors que Scilab retourne -32768.
  • Avec la valeur %nan : Matlab retourne 0 alors que Scilab retourne -32768.
  • Avec la valeur -%nan : Matlab retourne 0 alors que Scilab retourne -32768.

    • La fonction mtlb_int16(A) est utilisée par mfile2sci pour remplacer int16(A) quand il n'était pas possible de savoir ce qu'était le paramètre d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_int16 :

  • Si A ne contient pas de valeur %inf , %nan ou -%nan mtlb_int16(A) peut être remplacé par int16(A)

    • Attention : mtlb_int16 ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_int32

Fonction M2SCI
Last update : 08/04/2004

mtlb_int32 - Fonction d'émulation de la fonction Matlab int32

Description

Dans plusieurs cas particuliers, la fonction int32 se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée complexe : La fonction Matlab int32 peut être utilisée avec des complexes mais pas la fonction Scilab.
  • Avec la valeur %inf : Matlab retourne 2147483647 alors que Scilab retourne -2147483648.
  • Avec la valeur %nan : Matlab retourne 0 alors que Scilab retourne -2147483648.
  • Avec la valeur -%nan : Matlab retourne 0 alors que Scilab retourne -2147483648.

    • La fonction mtlb_int32(A) est utilisée par mfile2sci pour remplacer int32(A) quand il n'était pas possible de savoir ce qu'était le paramètre d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_int32 :

  • Si A ne contient pas de valeur %inf , %nan ou -%nan mtlb_int32(A) peut être remplacé par int32(A)

    • Attention : mtlb_int32 ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_int8

Fonction M2SCI
Last update : 08/04/2004

mtlb_int8 - Fonction d'émulation de la fonction Matlab int8

Description

Dans plusieurs cas particuliers, la fonction int8 se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée complexe : La fonction Matlab int8 peut être utilisée avec des complexes mais pas la fonction Scilab.
  • Avec la valeur %inf : Matlab retourne 127 alors que Scilab retourne 0.
  • Avec la valeur -%inf : Matlab retourne -128 alors que Scilab retourne 0.

    • La fonction mtlb_int8(A) est utilisée par mfile2sci pour remplacer int8(A) quand il n'était pas possible de savoir ce qu'était le paramètre d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_int8 :

  • Si A ne contient pas de valeur %inf ou -%inf mtlb_int8(A) peut être remplacé par int8(A)

    • Attention : mtlb_int8 ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_isa

Fonction M2SCI
Last update : 07/05/2004

mtlb_isa - Fonction d'émulation de la fonction Matlab isa

Description

Il n'y a pas de fonction Scilab équivalente à la fonction Matlab isa mais quand la "classe" d'objet recherchée existe dans Scilab, des expressions équivalentes existent.

La fonction mtlb_isa(OBJ,class) est utilisée par mfile2sci pour remplacer isa(OBJ,class) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_isa :

  • Si class est égal à "logical", mtlb_isa(OBJ,class) peut être remplacé par type(OBJ)==4
  • Si class est égal à "char", mtlb_isa(OBJ,class) peut être remplacé par type(OBJ)==10
  • Si class est égal à "numeric", mtlb_isa(OBJ,class) peut être remplacé par or(type(OBJ)==[1,5,8])
  • Si class est égal à "intX" (X valant 8, 16 ou 32), mtlb_isa(OBJ,class) peut être remplacé par typeof(OBJ)=="intX"
  • Si class est égal à "uintX" (X valant 8, 16 ou 32), mtlb_isa(OBJ,class) peut être remplacé par typeof(OBJ)=="uintX"
  • Si class est égal à "single", mtlb_isa(OBJ,class) peut être remplacé par type(OBJ)==1
  • Si class est égal à "double", mtlb_isa(OBJ,class) peut être remplacé par type(OBJ)==1
  • Si class est égal à "cell", mtlb_isa(OBJ,class) peut être remplacé par typeof(OBJ)=="ce"
  • Si class est égal à "struct", mtlb_isa(OBJ,class) peut être remplacé par typeof(OBJ)=="st"
  • Si class est égal à "function_handle", mtlb_isa(OBJ,class) peut être remplacé par type(OBJ)==13
  • Si class est égal à "sparse", mtlb_isa(OBJ,class) peut être remplacé par type(OBJ)==5
  • Si class est égal à "lti", mtlb_isa(OBJ,class) peut être remplacé par typeof(OBJ)=="state-space"

    • Attention : mtlb_isa ne doit pas être utilisée pour une programmation manuelle.

    See Also

    type , typeof ,

    Authors

    V.C.


mtlb_isfield

Fonction M2SCI
Last update : 29/07/2004

mtlb_isfield - Fonction d'émulation de la fonction Matlab isfield

Description

Il n'y a pas de fonction Scilab equivalente à la fonctions Matlab isfield(st,f) et l'expression équivalente se comporte différemment dans certains cas particuliers:

  • Si st n'est pas une structure : l'équivalent Scilab retourne une erreur alors que Matlab renvoie 0 .

    • La fonction mtlb_isfield(st,f) est utilisée par mfile2sci pour remplacer isfield(st,f) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_isfield :

  • Si st est une structure tf = mtlb_isfield(st,f) peut être remplacé par allf=getfield(1,st);tf=or(allf(3:$)==f);
  • Si st n'est pas une structure tf = mtlb_isfield(st,f) peut être remplacé par tf=%F;

    • Attention : mtlb_isfield ne doit pas être utilisée pour une programmation manuelle.

    See Also

    getfield ,

    Authors

    V.C.


mtlb_isletter

Fonction M2SCI
Last update : 29/07/2004

mtlb_isletter - Fonction d'émulation de la fonction Matlab isletter

Description

Il n'y a pas de fonction Scilab équivalente à la fonction Matlab isletter et les expressions équivalentes sont assez compliquées, donc mfile2sci utilise mtlb_isletter(A) pour remplacer isletter(A) . Pour obtenir un code plus performant on peut remplacer les appels à mtlb_isletter :

  • Si A n'est pas une chaîne de caractères tf = mtlb_isletter(A) peut être remplacé par tf = zeros(A)
  • Si A est une chaîne de caractères tf = mtlb_isletter(A) peut être remplacé par tf = (asciimat(A)>=65&asciimat(A)<=90)|(asciimat(A)>=97&asciimat(A)<=122)

    • Attention : mtlb_isletter ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_isspace

Fonction M2SCI
Last update : 08/04/2004

mtlb_isspace - Fonction d'émulation de la fonction Matlab isspace

Description

Il n'y a pas de fonction Scilab équivalente à la fonction Matlab isspace mais son comportement peut être reproduit.

La fonction mtlb_isspace(A) est utilisée par mfile2sci pour remplacer isspace(A) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_isspace :

  • Si A est une matrice de chaînes de caractères mtlb_isspace(A) peut être remplacé par asciimat(A)==32
  • Si A n'est pas une matrice de chaînes de caractères mtlb_isspace(A) peut être remplacé par zeros(A)

    • Attention : mtlb_isspace ne doit pas être utilisée pour une programmation manuelle.

    See Also

    asciimat ,

    Authors

    V.C.


mtlb_is

Fonction M2SCI
Last update : 30/03/2004

mtlb_is - Fonction d'émulation de l'insertion dans une chaîne de caractères de Matlab

Description

L'insertion se comporte différemment dans Matlab et dans Scilab pour les chaînes de caractères étant donné que celles-ci ne sont pas considérées de la même façon.

La fonction str = mtlb_is(sto,sfrom,i,j) est utilisée par mfile2sci pour remplacer les opérations d'insertion dans des chaînes de caractères. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Elle ne peut être remplacée.

Attention : mtlb_is ne doit pas être utilisée pour une programmation manuelle.

See Also

Chaines_de_caracteres_Matlab-Scilab , mtlb_i ,

Authors

V.C.


mtlb_i

Fonction M2SCI
Last update : 30/03/2004

mtlb_i - Fonction d'émulation de l'insertion de Matlab

Description

Dans plusieurs cas particuliers, l'insertion se comporte différemment dans Matlab et dans Scilab :

  • En insérant une matrice dans une variable : Matlab ajuste automatiquement la taille de la variable de retour pour qu'elle corresponde avec la matrice à insérer mais pas Scilab. Par exemple, avec A=1, A([1,2,3,4])=[1,2;3,4]) retourne un message d'erreur dans Scilab alors que dans Matlab on obtient A=[1,2,3,4]. Si des valeurs manquent par rapport aux indices donnés pour insérer, Matlab remplit la valeur de retour avec des zéros.
  • Lors de l'insertion de données d'une matrice d'une chaîne de caractères : étant donné que les matrices de chaînes de caractères peuvent être adressées comme tout autre type de matrice dans Matlab (chaque caractère peut être adressé), l'insertion à partir dans une telle matrice ne change pas des autres types. Mais dans Scilab ceci ne peut être fait de la même manière... mtlb_is est une alternative.

    • La fonction A=mtlb_i(A,k,B) est utilisée par mfile2sci pour remplacer A(k)=B quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_i :

  • Si A n'est pas un vecteur A=mtlb_i(A,k,B) peut être remplacé par A(k)=B
  • Si A et B sont des vecteurs lignes ou colonnes A=mtlb_i(A,k,B) peut être remplacé par A(k)=B

    • Attention : mtlb_i ne doit pas être utilisée pour une programmation manuelle.

    See Also

    Chaines_de_caracteres_Matlab-Scilab , mtlb_is ,

    Authors

    V.C.


mtlb_linspace

Fonction M2SCI
Last update : 13/08/2004

mtlb_linspace - Fonction d'émulation de la fonction Matlab linspace

Description

Dans plusieurs cas particuliers, la fonction linspace se comporte différemment dans Matlab et dans Scilab :

  • Avec les chaînes de caractère: La fonction Matlab linspace(A,B[,n]) renvoie un vecteur de caractères si A ou B est une chaîne de caractère, mais la fonction Scilab ne marche pas avec des entrées de ce type.

    • La fonction mtlb_linspace(A,B[,n]) est utilisée par mfile2sci pour remplacer linspace(A,B[,n]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_linspace :

  • Si A et B ne sont pas des chaînes de caractères, mtlb_linspace(A,B[,n]) peut être remplacé par linspace(A,B[,n])
  • Si A ou B est une chaîne de caractères, mtlb_linspace(A,B[,n]) peut être remplacé par ascii(linspace(ascii(A),ascii(B)[,n]))

    • Attention : mtlb_linspace ne doit pas être utilisée pour une programmation manuelle.

    See Also

    ascii ,

    Authors

    V.C.


mtlb_load

Fonction M2SCI
Last update : 13/08/2004

mtlb_load - Fonction d'émulation de la fonction Matlab load

Description

La fonction mtlb_load était utilisée par les anciennes version de mfile2sci pour remplacer load mais est maintenant obsolète utilisez plutôt loadmatfile

See Also

loadmatfile ,

Authors

V.C.


mtlb_logical

Fonction M2SCI
Last update : 08/04/2004

mtlb_logical - Fonction d'émulation de la fonction Matlab logical

Description

Il n'y a pas de fonction Scilab équivalent à la fonction Matlab logical mais sont comportement peut être reproduit.

La fonction mtlb_logical(A) est utilisée par mfile2sci pour remplacer logical(A) quand il n'était pas possible de savoir ce qu'était le paramètre d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_logical :

  • Si A est une matrice de booléens mtlb_logical(A) peut être remplacé par A
  • Si A n'est pas une matrice vide mtlb_logical(A) peut être remplacé par A<>[]
  • Si A est une matrice vide mtlb_logical(A) peut être remplacé par []

    • Attention : mtlb_logical ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_logic

Fonction M2SCI
Last update : 30/03/2004

mtlb_logic - Fonction d'émulation des opérateurs logiques de Matlab

Description

Dans plusieurs cas particuliers, les opérateurs logiques se comportent différemment dans Matlab et dans Scilab :

  • Avec des opérandes complexes : Les opérateurs < , <= , > et >= ne peuvent pas être utilisés dans Scilab avec des opérandes complexes alors que cela est possible dans Matlab. Dans ce cas, seule la partie réelle des opérandes est comparée.
  • Avec des matrices vides : Si les deux opérandes des opérateurs < , <= , > and >= sont des matrices vides, Scilab renvoie un message d'erreur alors que Matlab retourne une matrice vide. Pour les opérateurs == et ~= , si au moins une opérande est une matrice vide alors Matlab renvoie [] alors que Scilab retourne un booléen %T ou %F.

    • La fonction mtlb_logic(A,symbol,B) (avec "symbol" une chaîne de caractères contenant le symbole de l'opérateur) est utilisée par mfile2sci pour remplacer A symbol B quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_logic :

  • Si A et B ne sont pas des complexes ni des matrices vides mtlb_logic(A,symbol,B) peut être remplacé par A symbol B

    • Attention : mtlb_logic ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_lower

Fonction M2SCI
Last update : 08/04/2004

mtlb_lower - Fonction d'émulation de la fonction Matlab lower

Description

Dans plusieurs cas particuliers, la fonction Matlab lower(A) et la fonction Scilab convstr(A,"l") se comportent différemment :

  • Si A n'est pas une chaîne de caractères : la fonction Matlab lower peut être utilisée avec A n'étant pas une chaîne de caractères mais pas la fonction Scilab convstr .

    • La fonction mtlb_lower(A) est utilisée par mfile2sci pour remplacer lower(A) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_lower :

  • Si A est une matrice de chaînes de caractères mtlb_lower(A) peut être remplacé par convstr(A,"l")
  • Si A n'est pas une matrice de chaînes de caractères mtlb_lower(A) peut être remplacé par A

    • Attention : mtlb_lower ne doit pas être utilisée pour une programmation manuelle.

    See Also

    convstr ,

    Authors

    V.C.


mtlb_l

Fonction M2SCI
Last update : 30/03/2004

mtlb_l - Fonction d'émulation de la division à gauche de Matlab

Description

Dans plusieurs cas particuliers, la division à gauche se comporte différemment dans Matlab et dans Scilab :

  • Avec des opérandes de type chaîne de caractères : L'opérateur \ ne peut pas être utilisé dans Scilab avec des chaînes de caractères, alors que dans Matlab c'est possible. Et dans ce cas, le résultat donné par matlab est tranposé d'une manière très floue...

    • La fonction mtlb_l(a,b) est utilisée par mfile2sci pour remplacer A\B quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_l :

  • Si A et B ne sont pas des chaînes de caractères mtlb_l(A,B) peut être remplacé par A\B

    • Attention : mtlb_l ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_max

Fonction M2SCI
Last update : 08/04/2004

mtlb_max - Fonction d'émulation de la fonction Matlab max

Description

Dans plusieurs cas particuliers, la fonction max se comporte différemment dans Matlab et dans Scilab :

  • Avec des valeurs complexes : La fonction Matlab max peut être utilisée avec des complexes mais pas la fonction Scilab.
  • En cas d'appel avec deux paramètres d'entrée : La fonction Matlab max traite les valeurs suivant la première dimension qui n'est pas 1 alors que Scilab traite l'ensemble des valeurs de l'entrée.
  • En cas d'appel avec deux paramètres d'entrée : si l'une d'elles est une matrice vide, Scilab retourne un message d'erreur alors que Matlab renvoie [].
  • En cas d'appel avec trois paramètres d'entrée : si le paramètre dim est plus grand que le nombre de dimensions de le première entrée, Scilab retourne un message d'erreur alors que Matlab retourne le premier paramètre.

    • La fonction [r[,k]] = mtlb_max(A[,B[,dim]]) est utilisée par mfile2sci pour remplacer [r[,k]] = max(A[,B[,dim]]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_max :

  • En cas d'appel avec un paramètre d'entrée, si A est un scalaire ou un vecteur [r[,k]] = mtlb_max(A) peut être remplacé par max(A)
  • En cas d'appel avec un paramètre d'entrée, si A est une matrice [r[,k]] = mtlb_max(A) peut être remplacé par max(A,"r")
  • En cas d'appel avec deux paramètres d'entrée, si A et B sont des matrices réelles et ne sont pas des matrices vides, [r[,k]] = mtlb_max(A,B) peut être remplacé par max(A,B)
  • En cas d'appel avec trois paramètres d'entrée, si dim est inférieur au nombre de dimensions de A , [r[,k]] = mtlb_max(A,[],dim) peut être remplacé par max(A,dim)

    • Attention : mtlb_max ne doit pas être utilisée pour une programmation manuelle.

    See Also

    firstnonsingleton ,

    Authors

    V.C.


mtlb_min

Fonction M2SCI
Last update : 08/04/2004

mtlb_min - Fonction d'émulation de la fonction Matlab min

Description

Dans plusieurs cas particuliers, la fonction min se comporte différemment dans Matlab et dans Scilab :

  • Avec des valeurs complexes : La fonction Matlab min peut être utilisée avec des complexes mais pas la fonction Scilab.
  • En cas d'appel avec deux paramètres d'entrée : La fonction Matlab min traite les valeurs suivant la première dimension qui n'est pas 1 alors que Scilab traite l'ensemble des valeurs de l'entrée.
  • En cas d'appel avec deux paramètres d'entrée : si l'une d'elles est une matrice vide, Scilab retourne un message d'erreur alors que Matlab renvoie [].
  • En cas d'appel avec trois paramètres d'entrée : si le paramètre dim est plus grand que le nombre de dimensions de le première entrée, Scilab retourne un message d'erreur alors que Matlab retourne le premier paramètre.

    • La fonction [r[,k]] = mtlb_min(A[,B[,dim]]) est utilisée par mfile2sci pour remplacer [r[,k]] = min(A[,B[,dim]]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_min :

  • En cas d'appel avec un paramètre d'entrée, si A est un scalaire ou un vecteur [r[,k]] = mtlb_min(A) peut être remplacé par min(A)
  • En cas d'appel avec un paramètre d'entrée, si A est une matrice [r[,k]] = mtlb_min(A) peut être remplacé par min(A,"r")
  • En cas d'appel avec deux paramètres d'entrée, si A et B sont des matrices réelles et ne sont pas des matrices vides, [r[,k]] = mtlb_min(A,B) peut être remplacé par min(A,B)
  • En cas d'appel avec trois paramètres d'entrée, si dim est inférieur au nombre de dimensions de A , [r[,k]] = mtlb_min(A,[],dim) peut être remplacé par min(A,dim)

    • Attention : mtlb_min ne doit pas être utilisée pour une programmation manuelle.

    See Also

    firstnonsingleton ,

    Authors

    V.C.


mtlb_more

Fonction M2SCI
Last update : 08/04/2004

mtlb_more - Fonction d'émulation de la fonction Matlab more

Description

Dans plusieurs cas particuliers, la fonction Matlab more et la fonction Scilab lines se comportent différemment :

  • Avec des chaînes de caractères comme entrée : La fonction Matlab more accepte "on" et "off" comme entrée mais pas la fonction Scilab lines , il existe des équivalents (0 et 60).

    • La fonction mtlb_more(in) est utilisée par mfile2sci pour remplacer more(in) quand il n'était pas possible de savoir ce qu'était le paramètre d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_more :

  • Si in est égal à "on" mtlb_more(in) peut être remplacé par lines(60)
  • Si in est égal à "off" mtlb_more(in) peut être remplacé par lines(0)
  • Si in est un double mtlb_more(in) peut être remplacé par lines(in)

    • Attention : mtlb_more ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_num2str

Fonction M2SCI
Last update : 01/07/2004

mtlb_num2str - Fonction d'émulation de la fonction Matlab num2str

Description

Dans plusieurs cas particuliers, la fonction Matlab num2str et ses équivalents Scilab ( string , msprintf ) se comportent différemment :

  • Avec deux paramètres d'entrée, le second donnant une précision : Il n'y a pas de fonction Scilab équivalente mais msprintf peut être utilisée pour émuler ce cas.
  • Avec deux paramètres d'entrée, le second donnant un format : l'équivalent Scilab pour l'expression Matlab num2string(a,format) est msprintf(format,a) .

    • La fonction mtlb_num2str(x,f) est utilisée par mfile2sci pour remplacer num2str(x,f) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_num2str :

  • Si f est une chaîne de caractères, mtlb_num2str(x,f) peut être remplacé par msprintf(f,x)

    • Attention : mtlb_num2str ne doit pas être utilisée pour une programmation manuelle.

    See Also

    string , msprintf ,

    Authors

    V.C.


mtlb_ones

Fonction M2SCI
Last update : 07/04/2004

mtlb_ones - Fonction d'émulation de la fonction Matlab ones

Description

Dans plusieurs cas particuliers, la fonction ones se comporte différemment dans Matlab et dans Scilab :

  • Avec une entrée qui est un scalaire : La fonction Matlab ones retourne une matrice n x n alors que Scilab retourne 1.

    • La fonction mtlb_ones(A) est utilisée par mfile2sci pour remplacer ones(A) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_ones :

  • Si A est un scalaire mtlb_ones(A) peut être remplacé par ones(A,A)
  • Si A n'est pas un scalaire mtlb_ones(A) peut être remplacé par ones(A)

    • Attention : mtlb_ones ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_plot

Fonction M2SCI
Last update : 30/06/2004

mtlb_plot - Fonction d'émulation de la fonction Matlab plot

Description

La fonction Matlab plot et la fonction Scilab plot2d se comportent différemment.

La fonction mtlb_plot(...) est utilisée par mfile2sci pour remplacer plot(...) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_plot quand il n'y a pas de valeur de sortie, dans ce cas, les couleurs doivent être changées par l'utilisateur:

  • Avec un paramètre d'entrée, si Y est réel mtlb_plot(Y) peut être remplacé par plot2d(Y)
  • Avec un paramètre d'entrée, si Y est complex mtlb_plot(Y) peut être remplacé par plot2d(real(Y),imag(Y))
  • Avec deux paramètres d'entrée X et Y , si Y n'est pas une chaîne de caractères, mtlb_plot(X,Y) peut être remplacé par plot2d(X,Y)

    • Attention : mtlb_plot ne doit pas être utilisée pour une programmation manuelle.

    See Also

    plot2d ,

    Authors

    V.C.


mtlb_prod

Fonction M2SCI
Last update : 09/04/2004

mtlb_prod - Fonction d'émulation de la fonction Matlab prod

Description

Dans plusieurs cas particuliers, la fonction prod se comporte différemment dans Matlab et dans Scilab :

  • En cas d'appel avec un paramètre d'entrée : La fonction Matlab prod traite les valeurs en suivant la première dimension qui n'est pas 1 alors que la fonction Scilab prod traite toutes les valeurs de l'entrée.
  • En cas d'appel avec deux paramètres d'entrée : La fonction Matlab prod peut être utilisée avec le second paramètre donnant une dimension du premier paramètre qui n'existe pas alors que la fonction Scilab prod retourne un message d'erreur.

    • La fonction mtlb_prod(A[,dim]) est utilisée par mfile2sci pour remplacer prod(A[,dim]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_prod :

  • En cas d'appel avec un paramètre d'entrée, si A est une matrice vide, un scalaire ou un vecteur, mtlb_prod(A) peut être remplacé par prod(A)
  • En cas d'appel avec un paramètre d'entrée, si A est une matrice non-vide, mtlb_prod(A) peut être remplacé par prod(A,1)
  • En cas d'appel avec un paramètre d'entrée, si A est hypermatrice, mtlb_prod(A) peut être remplacé par prod(A,firstnonsingleton(A))
  • En cas d'appel avec deux paramètres d'entrée, si dim est inférieure au nombre de dimensions de A mtlb_prod(A,dim) peut être remplacé par prod(A,dim)

    • Attention : mtlb_prod ne doit pas être utilisée pour une programmation manuelle.

    See Also

    firstnonsingleton ,

    Authors

    V.C.


mtlb_randn

Fonction M2SCI
Last update : 07/04/2004

mtlb_randn - Fonction d'émulation de la fonction Matlab randn

Description

Dans plusieurs cas particuliers, la fonction Matlab randn et la fonction Scilab rand(...,"normal") se comportent différemment :

  • Avec une entrée qui est un scalaire : La fonction Matlab randn retourne une matrice n x n alors que la fonction Scilab rand(...,"normal") retourne un scalaire.

    • La fonction mtlb_randn(A) est utilisée par mfile2sci pour remplacer randn(A) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_randn :

  • Si A est un scalaire mtlb_randn(A) peut être remplacé par rand(A,A,"normal")
  • Si A n'est pas un scalaire mtlb_randn(A) peut être remplacé par rand(A,"normal")

    • Attention : mtlb_randn ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_rand

Fonction M2SCI
Last update : 07/04/2004

mtlb_rand - Fonction d'émulation de la fonction Matlab rand

Description

Dans plusieurs cas particuliers, la fonction rand se comporte différemment dans Matlab et dans Scilab :

  • Avec une entrée qui est un scalaire : La fonction Matlab rand retourne une matrice n x n alors que la fonction Scilab retourne un scalaire.

    • La fonction mtlb_rand(A) est utilisée par mfile2sci pour remplacer rand(A) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_rand :

  • Si A est un scalaire mtlb_rand(A) peut être remplacé par rand(A,A)
  • Si A n'est pas un scalaire mtlb_rand(A) peut être remplacé par rand(A)

    • Attention : mtlb_rand ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_rcond

Fonction M2SCI
Last update : 09/04/2004

mtlb_rcond - Fonction d'émulation de la fonction Matlab rcond

Description

Dans plusieurs cas particuliers, la fonction rcond se comporte différemment dans Matlab et dans Scilab :

  • Avec une matrice vide : La fonction Matlab rcond retourne Inf et Scilab retourne []

    • La fonction mtlb_rcond(A) est utilisée par mfile2sci pour remplacer rcond(A) quand il n'était pas possible de savoir ce qu'était le paramètre d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_rcond :

  • Si A n'est pas une matrice vide mtlb_rcond(A) peut être remplacé par rcond(A)

    • Attention : mtlb_rcond ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_realmax

Fonction M2SCI
Last update : 28/10/2004

mtlb_realmax - Fonction d'émulation de la fonction Matlab realmax

Description

L'équivalent Scilab de la fonction Matlab realmax est number_properties mais tous les cas ne sont pas implémentés :

  • L'équivalent Scilab de l'expression Matlab realmax ou realmax('double') est number_properties("huge")
  • Il n'y a pas d'équivalent Scilab pour l'expression Matlab realmax('single')

    • La fonction mtlb_realmax(prec) est utilisée par mfile2sci pour remplacer realmax(prec) quand il n'était pas possible de savoir ce qu'était le paramètre d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_realmax :

  • Si prec est égale à "double" mtlb_realmax(prec) peut être remplacé par number_properties("huge")

    • Attention : mtlb_realmax ne doit pas être utilisée pour une programmation manuelle.

    See Also

    number_properties ,

    Authors

    V.C.


mtlb_realmin

Fonction M2SCI
Last update : 28/10/2004

mtlb_realmin - Fonction d'émulation de la fonction Matlab realmin

Description

L'équivalent Scilab de la fonction Matlab realmin est number_properties mais tous les cas ne sont pas implémentés :

  • L'équivalent Scilab de l'expression Matlab realmin ou realmin('double') est number_properties("tiny")
  • Il n'y a pas d'équivalent Scilab pour l'expression Matlab realmin('single')

    • La fonction mtlb_realmin(prec) est utilisée par mfile2sci pour remplacer realmin(prec) quand il n'était pas possible de savoir ce qu'était le paramètre d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_realmin :

  • Si prec est égale à "double" mtlb_realmin(prec) peut être remplacé par number_properties("tiny")

    • Attention : mtlb_realmin ne doit pas être utilisée pour une programmation manuelle.

    See Also

    number_properties ,

    Authors

    V.C.


mtlb_repmat

Fonction M2SCI
Last update : 13/08/2004

mtlb_repmat - Fonction d'émulation de la fonction Matlab repmat

Description

Il n'y a pas de fonction Scilab équivalente à la fonction Matlab repmat mais il existe des instructions équivalents.

La fonction mtlb_repmat(M,m[,n]) est utilisée par mfile2sci pour remplacer repmat(M,m[,n]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_repmat :

  • Si A est de type Double et que m est un scalaire, mtlb_repmat(M,m) peut être remplacé par ones(m,m).*.M et mtlb_repmat(M,m,n) peut être remplacé par ones(m,n).*.M
  • Si A est de type Booléen et que m est un scalaire, mtlb_repmat(M,m) peut être remplacé par ones(m,m).*..bool2s(M) et mtlb_repmat(M,m,n) peut être remplacé par ones(m,n).*..bool2s(M)
  • Si A est de type String et que m est un scalaire, mtlb_repmat(M,m) peut être remplacé par asciimat(ones(m,m).*.asciimat(M)) et mtlb_repmat(M,m,n) peut être remplacé par asciimat(ones(m,n).*.asciimat(M))
  • Si A est de type Double et que m est un vecteur, mtlb_repmat(M,m) peut être remplacé par ones(m(1),m(2),...).*.M
  • Si A est de type Booléen et que m est un vecteur, mtlb_repmat(M,m) peut être remplacé par ones(m(1),m(2),...).*..bool2s(M)
  • Si A est de type String et que m est un vecteur, mtlb_repmat(M,m) peut être remplacé par asciimat(ones(m(1),m(2),...).*.asciimat(M))

    • Attention : mtlb_repmat ne doit pas être utilisée pour une programmation manuelle.

    See Also

    ones , kron ,

    Authors

    V.C.


mtlb_save

Fonction M2SCI
Last update : 28/10/2004

mtlb_save - Fonction d'émulation de la fonction Matlab save

Description

La fonction mtlb_save était utilisée par les anciennes version de mfile2sci pour remplacer save mais est maintenant obsolète utilisez plutôt savematfile

See Also

savematfile ,

Authors

V.C.


mtlb_setstr

Fonction M2SCI
Last update : 09/04/2004

mtlb_setstr - Fonction d'émulation de la fonction Matlab setstr

Description

Dans plusieurs cas particuliers, la fonction Matlab setstr et la fonction Scilab ascii se comportent différemment :

  • Avec les chaînes de charactères : la fonction Matlab setstr retourne une chaîne de caractères alors que la fonction Scilab ascii retourne uen matrice de doubles.
  • Avec les matrices de doubles : la fonction Matlab setstr retourne une matrice de caractères alors que la fonction Scilab ascii retourne une chaine de caractères.

    • La fonction mtlb_setstr(A) est utilisée par mfile2sci pour remplacer setstr(A) quand il n'était pas possible de savoir ce qu'était le paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_setstr :

  • Si A est une chaîne de caratères ou une matrice de chaînes mtlb_setstr(A) peut être remplacé par A
  • Si A est un vecteur ligne de doubles mtlb_setstr(A) peut être remplacé par ascii(A)

    • Attention : mtlb_setstr ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_size

Fonction M2SCI
Last update : 09/04/2004

mtlb_size - Fonction d'émulation de la fonction Matlab size

Description

Dans plusieurs cas particuliers, la fonction size se comporte différemment dans Matlab et dans Scilab :

  • Avec deux paramètres d'entrée : La fonction Matlab size peut être utilisée avec le second paramètre donnant donnant une dimension du premier paramètre qui n'existe pas (retourne 1 dans ce cas) mais pas la fonction Scilab.
  • Avec plus d'une paramètre de sortie : si le nombre de paramètres de sortie est plus petit que le nombre de dimension, la dernière sortie est égale au produit de toutes les dimensions restantes dans Matlab mais pas dans Scilab. Si le nombre de sorties est plus grand que le nombre de dimensions, toutes les sorties correspondant à une dimension qui n'existe pas sont égales à 1 en Matlab mais Scilab retourne une erreur dans ce cas.

    • La fonction [d1,[d2,...]] = mtlb_size(X[,dim]) est utilisée par mfile2sci pour remplacer [d1,[d2,...]] = mtlb_size(X[,dim]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_size :

  • Avec deux paramètres d'entrée : si dim correspond à une dimension de X qui existe mtlb_size(X,dim) peut être remplacé par size(X,dim)
  • Avec plus d'un paramètre de sortie : si le nombre des sorties est égal au nombre de dimensions de X [d1,[d2,...]] = mtlb_size(X) peut être remplacé par [d1,[d2,...]] = size(X)

    • Attention : mtlb_size ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_sort

Fonction M2SCI
Last update : 13/10/2006

mtlb_sort - Fonction d'émulation de la fonction Matlab sort

Calling Sequence

P = mtlb_sort(X)
P = mtlb_sort(X,dim[,mode])

Parameters

  • X : un scalaire, un vecteur, une matrice ou hypermatrice d'elements compris dans [-1 1]un scalaire, un vecteur ou une matrice de réels, de booléens ou une string
  • ndim : un entier positif
  • mode :une chaine de caracteres ( "ascend" or "descend" )

Description

Dans plusieurs cas particuliers, la fonction sort de Matlab et la fonction gsort de Scilab se comportent différemment :

  • Si X est un vecteur alors l'appel de la fonction sort(X) de Matlab est équivalent à l'appel de la fonction sort(X,'g','i') de Scilab.
  • dim=1 (resp. 2 ) de Matlab est equivalent au flag 'r' (resp. 'c' ) de Scilab.
  • mode="ascend" (resp. "descend" ) est équivalent au flag 'i' (resp 'd' ) de Scilab.

    • La fonction mtlb_sort(X,dim[,mode]) est utilisée par mfile2sci pour remplacer sort(X,dim[,mode]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_sort par des appels gsort .

    Attention : mtlb_sort ne doit pas être utilisée pour une programmation manuelle.

    Authors

    F.B.


mtlb_strcmpi

Fonction M2SCI
Last update : 09/04/2004

mtlb_strcmpi - Fonction d'émulation de la fonction Matlab strcmpi

Description

Il n'y a pas dans Scilab de fonction équivalente à la fonction Matlab strcmpi mais il existe des instructions équivalentes.

La fonction mtlb_strcmpi(A,B) est utilisée par mfile2sci pour remplacer strcmpi(A,B) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_strcmpi :

  • Si A et B sont des chaînes de caractères mtlb_strcmpi(A,B) peut être remplacé par convstr(A)==convstr(B)
  • Si A et/ou B n'est pas une chaîne de caractères mtlb_strcmpi(A,B) peut être remplacé par 0

    • Attention : mtlb_strcmpi ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_strcmp

Fonction M2SCI
Last update : 09/04/2004

mtlb_strcmp - Fonction d'émulation de la fonction Matlab strcmp

Description

Il n'y a pas dans Scilab de fonction équivalente à la fonction Matlab strcmp mais il existe des instructions équivalentes.

La fonction mtlb_strcmp(A,B) est utilisée par mfile2sci pour remplacer strcmp(A,B) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_strcmp :

  • Si A et B sont des chaînes de caractères mtlb_strcmp(A,B) peut être remplacé par A==B
  • Si A et/ou B n'est pas une chaîne de caractères mtlb_strcmp(A,B) peut être remplacé par 0

    • Attention : mtlb_strcmp ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_strfind

Fonction M2SCI
Last update : 09/04/2004

mtlb_strfind - Fonction d'émulation de la fonction Matlab strfind

Description

Dans plusieurs cas particuliers, la fonction Matlab strfind et la fonction Scilab strindex se comportent différemment dans Matlab et dans Scilab :

  • Avec des paramètres d'entrée n'étant pas des chaînes de caractère : La fonction Matlab strfind peut être utilisée avec des entrées n'étant pas des chaînes de caractères mais pas la fonction Scilab strindex .

    • La fonction mtlb_strfind(A,B) est utilisée par mfile2sci pour remplacer strfind(A,B) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_strfind :

  • Si A et B sont des chaînes de caractères mtlb_strfind(A,B) peut être remplacé par strindex(A,B)

    • Attention : mtlb_strfind ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_strrep

Fonction M2SCI
Last update : 09/04/2004

mtlb_strrep - Fonction d'émulation de la fonction Matlab strrep

Description

Dans plusieurs cas particuliers, la fonction Matlab strrep et la fonction Scilab strsubst se comportent différemment :

  • Avec des paramètres d'entrée n'étant pas des chaînes de caractère : La fonction Matlab strrep peut être utilisée avec des entrées n'étant pas des chaînes de caractères mais pas la fonction Scilab strsubst .

    • La fonction mtlb_strrep(A,B,C) est utilisée par mfile2sci pour remplacer strrep(A,B,C) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_strrep :

  • Si A , B et C sont des chaînes de caractères y = mtlb_strrep(A,B,C) peut être remplacé par strsubst(A,B,C)

    • Attention : mtlb_strrep ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_sum

Fonction M2SCI
Last update : 09/04/2004

mtlb_sum - Fonction d'émulation de la fonction Matlab sum

Description

Dans plusieurs cas particuliers, la fonction sum se comporte différemment dans Matlab et dans Scilab :

  • En cas d'appel avec un paramètre d'entrée : La fonction Matlab sum traite les valeurs en suivant la première dimension qui n'est pas 1 alors que la fonction Scilab sum traite toutes les valeurs de l'entrée.
  • En cas d'appel avec deux paramètres d'entrée : La fonction Matlab sum peut être utilisée avec le second paramètre donnant une dimension du premier paramètre qui n'existe pas alors que la fonction Scilab sum retourne un message d'erreur.

    • La fonction mtlb_sum(A[,dim]) est utilisée par mfile2sci pour remplacer sum(A[,dim]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_sum :

  • En cas d'appel avec un paramètre d'entrée, si A est une matrice vide, un scalaire ou un vecteur, mtlb_sum(A) peut être remplacé par sum(A)
  • En cas d'appel avec un paramètre d'entrée, si A est une matrice non-vide, mtlb_sum(A) peut être remplacé par sum(A,1)
  • En cas d'appel avec un paramètre d'entrée, si A est hypermatrice, mtlb_sum(A) peut être remplacé par sum(A,firstnonsingleton(A))
  • En cas d'appel avec deux paramètres d'entrée, si dim est inférieure au nombre de dimensions de A mtlb_sum(A,dim) peut être remplacé par sum(A,dim)

    • Attention : mtlb_sum ne doit pas être utilisée pour une programmation manuelle.

    See Also

    firstnonsingleton ,

    Authors

    V.C.


mtlb_s

Fonction M2SCI
Last update : 30/03/2004

mtlb_s - Fonction d'émulation de la soustraction Matlab

Description

Dans plusieurs cas particuliers, la soustraction se comporte différemment dans Matlab et dans Scilab :

  • Avec des opérandes de type chaîne de caractères : L'opérateur - ne peut pas être utilisé dans Scilab avec des chaînes de caractère, alors que Matlab réalise dans ce cas la soustraction des codes ASCII des opérandes.
  • Avec une matrice vide : Dans Scilab, si une des opérandes est une matrice vide alors le résultat de la soustraction est l'autre opérande. Dans Matlab si une des opérandes est une matrice vide alors le résultat de la soustraction est soit une erreur (la seconde opérande n'est pas un scalaire) soit une matrice vide.

    • La fonction mtlb_s(A,B) est utilisée par mfile2sci pour remplacer A-B quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_s :

  • Si A et B sont des chaînes de caractères, mtlb_s(A,B) peut être remplacé par asciimat(A)-asciimat(B)
  • Si A et B ne sont pas des matrices vides mtlb_s(A,B) peut être remplacé par A-B , sinon mtlb_s(A,B) peut être remplacé par [] .
  • Si mtlb_mode()==%T, alors mtlb_s(A,B) peut être remplacé par A-B dans tous les cas où A et B ne sont pas des chaînes de caractères.

    • Attention : mtlb_s ne doit pas être utilisée pour une programmation manuelle.

    See Also

    mtlb_mode ,

    Authors

    V.C.


mtlb_toeplitz

Fonction M2SCI
Last update : 01/07/2004

mtlb_toeplitz - Fonction d'émulation de la fonction Matlab toeplitz

Description

Dans plusieurs cas particuliers, la fonction toeplitz se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée : si celui-ci est complexe ou si c'est une matrice, la valeur de sortie des fonctions toeplitz de Matlab et Scilab sera différente.
  • Avec deux paramètres d'entrée : si ce sont des vecteurs et que leurs premiers éléments sont différents, Scilab renvoie un message d'erreur alors que Matlab donne priorité à l'élément colonne. Si ce sont des matrices, la valeur retournée par la fonction toeplitz sera différente dans Matlab et dans Scilab.

    • La fonction mtlb_toeplitz(c[,r]) est utilisée par mfile2sci pour remplacer toeplitz(c[,r]) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_toeplitz :

  • Pour les appels avec un paramètre d'entrée, si c est un scalaire ou un vecteur réel, mtlb_toeplitz(c) peut être remplacé par toeplitz(c)
  • Pour les appels avec deux paramètres d'entrée, si c et r sont des scalaires ou des vecteurs et que leurs premiers éléments sont égaux, mtlb_toeplitz(c,r) peut être remplacé par toeplitz(c,r)

    • Attention : mtlb_toeplitz ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_tril

Fonction M2SCI
Last update : 09/04/2004

mtlb_tril - Fonction d'émulation de la fonction Matlab tril

Description

Dans plusieurs cas particuliers, la fonction tril se comporte différemment dans Matlab et dans Scilab :

  • Avec des paramètres d'entrée complexes : La fonction Matlab tril peut être utilisée avec des données complexes mais pas la fonction Scilab.
  • Avec des paramètres d'entrée de type chaîne de cacatères : étant donné que Matlab et Scilab ne considèrent pas les chaînes de caractères de la même façon, la fonction tril ne donne pas le même résutat pour ce type d'entrée dans Scilab et dans Matlab.
  • Avec des paramètres d'entrée booléens : La fonction Matlab tril peut être utilisée avec des données booléennes mais pas la fonction Scilab.

    • La fonction mtlb_tril(x,k) est utilisée par mfile2sci pour remplacer tril(x,k) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_tril :

  • Si X contient des doubles réels mtlb_tril(x,k) peut être remplacé par tril(x,k)
  • Si X contient des booléens mtlb_tril(x,k) peut être remplacé par tril(bool2s(x),k)

    • Attention : mtlb_tril ne doit pas être utilisée pour une programmation manuelle.

    See Also

    Chaines_de_caracteres_Matlab-Scilab ,

    Authors

    V.C.


mtlb_triu

Fonction M2SCI
Last update : 09/04/2004

mtlb_triu - Fonction d'émulation de la fonction Matlab triu

Description

Dans plusieurs cas particuliers, la fonction triu se comporte différemment dans Matlab et dans Scilab :

  • Avec des paramètres d'entrée complexes : La fonction Matlab triu peut être utilisée avec des données complexes mais pas la fonction Scilab.
  • Avec des paramètres d'entrée de type chaîne de cacatères : étant donné que Matlab et Scilab ne considèrent pas les chaînes de caractères de la même façon, la fonction triu ne donne pas le même résutat pour ce type d'entrée dans Scilab et dans Matlab.
  • Avec des paramètres d'entrée booléens : La fonction Matlab triu peut être utilisée avec des données booléennes mais pas la fonction Scilab.

    • La fonction mtlb_triu(x,k) est utilisée par mfile2sci pour remplacer triu(x,k) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_triu :

  • Si X contient des doubles réels mtlb_triu(x,k) peut être remplacé par triu(x,k)
  • Si X contient des booléens mtlb_triu(x,k) peut être remplacé par triu(bool2s(x),k)

    • Attention : mtlb_triu ne doit pas être utilisée pour une programmation manuelle.

    See Also

    Chaines_de_caracteres_Matlab-Scilab ,

    Authors

    V.C.


mtlb_true

Fonction M2SCI
Last update : 07/04/2004

mtlb_true - Fonction d'émulation de la fonction Matlab true

Description

Il n'y a pas d'équivalent Scilab pour la fonction Matlab true , cependant la fonction Scilab ones retourne un résultat interprété de la même façon pour Scilab.

Dans plusieurs cas particuliers, la fonction Matlab true et la fonction Scilab ones se comporte différemment :

  • Avec une entrée qui est un scalaire : La fonction Matlab true retourne une matrice n x n alors que la fonction Scilab ones retourne 1.

    • La fonction mtlb_true(A) est utilisée par mfile2sci pour remplacer true(A) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_true :

  • Si A est un scalaire mtlb_true(A) peut être remplacé par ones(A,A)
  • Si A n'est pas un scalaire mtlb_true(A) peut être remplacé par ones(A)

    • Attention : mtlb_true ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_t

Fonction M2SCI
Last update : 30/03/2004

mtlb_t - Fonction d'émulation de la transposition de Matlab

Description

Dans plusieurs cas particuliers, la transposition se comporte différemment dans Matlab et dans Scilab :

  • Avec des opérandes de type chaîne de caractère : L'opérateur ' est utilisé dans Scilab pour transposer des chaînes de caractères entières alors que Matlab fait la transposition caractère par caractère.

    • La fonction mtlb_t(A) est utilisée par mfile2sci pour remplacer A' quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_t :

  • Si A n'est pas une matrice de chaînes de caractères mtlb_t(A) peut être remplacé par A'

    • Attention : mtlb_t ne doit pas être utilisée pour une programmation manuelle.

    See Also

    Chaines_de_caracteres_Matlab-Scilab ,

    Authors

    V.C.


mtlb_uint16

Fonction M2SCI
Last update : 08/04/2004

mtlb_uint16 - Fonction d'émulation de la fonction Matlab uint16

Description

Dans plusieurs cas particuliers, la fonction uint16 se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée complexe : La fonction Matlab uint16 peut être utilisée avec des complexes mais pas la fonction Scilab.
  • Avec la valeur %inf : Matlab retourne 65535 alors que Scilab retourne 0.

    • La fonction mtlb_uint16(A) est utilisée par mfile2sci pour remplacer uint16(A) quand il n'était pas possible de savoir ce qu'était le paramètre d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_uint16 :

  • Si A ne contient pas de valeur %inf , %nan ou -%nan mtlb_uint16(A) peut être remplacé par uint16(A)

    • Attention : mtlb_uint16 ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_uint32

Fonction M2SCI
Last update : 08/04/2004

mtlb_uint32 - Fonction d'émulation de la fonction Matlab uint32

Description

Dans plusieurs cas particuliers, la fonction uint32 se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée complexe : La fonction Matlab uint32 peut être utilisée avec des complexes mais pas la fonction Scilab.
  • Avec la valeur %inf : Matlab retourne 4294967295 alors que Scilab retourne 0.

    • La fonction mtlb_uint32(A) est utilisée par mfile2sci pour remplacer uint32(A) quand il n'était pas possible de savoir ce qu'était le paramètre d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_uint32 :

  • Si A ne contient pas de valeur %inf , %nan ou -%nan mtlb_uint32(A) peut être remplacé par uint32(A)

    • Attention : mtlb_uint32 ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_uint8

Fonction M2SCI
Last update : 08/04/2004

mtlb_uint8 - Fonction d'émulation de la fonction Matlab uint8

Description

Dans plusieurs cas particuliers, la fonction uint8 se comporte différemment dans Matlab et dans Scilab :

  • Avec un paramètre d'entrée complexe : La fonction Matlab uint8 peut être utilisée avec des complexes mais pas la fonction Scilab.
  • Avec la valeur %inf : Matlab retourne 255 alors que Scilab retourne 0.

    • La fonction mtlb_uint8(A) est utilisée par mfile2sci pour remplacer uint8(A) quand il n'était pas possible de savoir ce qu'était le paramètre d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_uint8 :

  • Si A ne contient pas de valeur %inf , %nan ou -%nan mtlb_uint8(A) peut être remplacé par uint8(A)

    • Attention : mtlb_uint8 ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


mtlb_upper

Fonction M2SCI
Last update : 08/04/2004

mtlb_upper - Fonction d'émulation de la fonction Matlab upper

Description

Dans plusieurs cas particuliers, la fonction Matlab upper(A) et la fonction Scilab convstr(A,"u") se comportent différemment :

  • Si A n'est pas une chaîne de caractères : la fonction Matlab upper peut être utilisée avec A n'étant pas une chaîne de caractères mais pas la fonction Scilab convstr .

    • La fonction mtlb_upper(A) est utilisée par mfile2sci pour remplacer upper(A) quand il n'était pas possible de savoir ce qu'étaient les paramètres d'entrée pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_upper :

  • Si A est une matrice de chaînes de caractères mtlb_upper(A) peut être remplacé par convstr(A,"u")
  • Si A n'est pas une matrice de chaînes de caractères mtlb_upper(A) peut être remplacé par A

    • Attention : mtlb_upper ne doit pas être utilisée pour une programmation manuelle.

    See Also

    convstr ,

    Authors

    V.C.


mtlb_zeros

Fonction M2SCI
Last update : 07/04/2004

mtlb_zeros - Fonction d'émulation de la fonction Matlab zeros

Description

Dans plusieurs cas particuliers, la fonction zeros se comporte différemment dans Matlab et dans Scilab :

  • Avec une entrée qui est un scalaire : La fonction Matlab zeros retourne une matrice n x n alors que Scilab retourne 0.

    • La fonction mtlb_zeros(A) est utilisée par mfile2sci pour remplacer zeros(A) quand il n'était pas possible de savoir ce qu'étaient les opérandes pendant la conversion d'un code Matlab vers Scilab. Cette fonction va déterminer la sémantique correcte pendant l'exécution. Pour obtenir un code plus performant on peut remplacer les appels à mtlb_zeros :

  • Si A est un scalaire mtlb_zeros(A) peut être remplacé par zeros(A,A)
  • Si A n'est pas un scalaire mtlb_zeros(A) peut être remplacé par zeros(A)

    • Attention : mtlb_zeros ne doit pas être utilisée pour une programmation manuelle.

    Authors

    V.C.


sci_files

Documentation
Last update : 10/09/2004

sci_files - Comment écrire des fonctions de conversion

Description

Pour convertir les appels à des fonctions Matlab, mfile2sci utilise une fonctions appelée sci_<nom_de_la_fonction_Matlab> . Toutes ces fonctions sont définies dans des sci_files dans le répertoire SCI/macros/m2sci/sci_files/. La palette de sci_files fournie dans Scilab ne permet pas encore de convertir les appels à toutes les fonctions Matlab. Cependant, un utilisateur Scilab peut ajouter des sci_files (pour des fonctions Matlab ou pour ses propres fonctions) en utilisant les conseils suivants.

Dans M2SCI, un appel à une fonction est considéré comme un "arbre" (c'est aussi le cas des instructions du fichier à convertir), représenté dans Scilab par une tlist avec les champs suivants :

  • name : nom de la fonction Matlab
  • lhsnb : nombre de paramètres de sortie de la fonction Matlab
  • lhs : liste des paramètres de sortie de la fonction Matlab
  • rhs : liste des paramètres d'entrée de la fonction Matlab

    • Une sci_function a un paramètre d'entrée tree qui est aussi la sortie de cette fonction. Une sci_function doit convertir cet arbre pour qu'il soit compatible avec Scilab en changeant name, lhsnb, lhs et/ou rhs. L'autre rôle de cette fonction est de gérer l'inférence. L'arbre d'entrée contient des données d'inférence dans ses rhs qui devront être mises à jour avec ce que l'on peut inférer pour les lhs de cette fonction.

    Plusieurs fonctions ont été écrites pour aider à la rédaction de fonctions de conversion :

  • Funcall : créé un arbre qui représente l'appel à une fonction
  • Operation : créé un arbre qui représente une opération
  • Variable : créé un arbre qui représente une variable
  • Cste : créé un arbre qui représente une constante
  • Infer : créé un arbre qui représente les données d'inférence
  • Type : créé un arbre qui représente le type pour l'inférence
  • Equal : créé un arbre qui représente une instruction

    • Quelques fonctions ont été écrites pour récupérer les propriétés des opérandes/entrées. En considérant A comme une tlist utilisée dans l'arbre, vous pouvez utiliser les fonctions suivantes :

    La fonction | renvoie %T si...
is_empty(A) | toutes les dimensions de A sont égales à 0
not_empty(A) | toutes les dimensions de A sont connues et au moins une dimension de A est différente de 0
is_a_scalar(A) | toutes les dimensions de A sont égales 1
not_a_scalar(A) | toutes les dimensions de A sont connues et au moins une dimension de A est différente de 1
is_a_vector(A) | toutes les dimensions de A sotn connues et toutes les dimensions de A sauf une sont égales à 1
not_a_vector(A) | toutes les dimensions de A sotn connues et au moins deux dimensions de A sont supérieures à 1
is_real(A) | A est réel
is_complex(A) | A est complexe
isdefinedvar(A) | A est une variable déjà définie dans le M-file en cours de conversion
allunknown(A) | Toutes les dimensions de A sont inconnues

    D'autres fonctions ont été écrites pour des besoins spécifiques lors de l'écriture de fonctions de conversion :

  • first_non_singleton : est équivalente à firstnonsingleton pour une tlist M2SCI. Séquence d'appel : dim = first_non_singleton(A)
  • gettempvar : génère une variable temporaire portant une nom qui n'existe pas. Séquence d'appel : v = gettempvar()
  • insert : permet d'insérer des instruction. Séquence d'appel : insert(Equal(...),opt) avec opt~=1 pour insérer avan tl'instruction courante et opt=1 pour insérer après celle-ci.
  • getoperands : peut être utilisée pour extraire chaque opérande comme une variable. Séquence d'appel : [A,B] = getoperands(operation_tlist)
  • getrhs : peut être utilisée pour extraire chaque paramètre comme une variable. Séquence d'appel : [A,...] = getrhs(funcall_tlist)
  • convert2double : change le type de l'entrée quand ce type n'est pas implémenté pour une fonction particulière de Scilab. Séquence d'appel : A = convert2double(A)

    • Pour plus d'informations sur la fçon d'écrire ces fichiers, consulter le répertoire SCI/macros/m2sci/sci_files/ qui donne de nombreux exemples, des plus simples (e.g. sci_abs.sci) aux plus compliqués (e.g. sci_zeros.sci).

    See Also

    m2scideclare , Funcall , Operation , Variable , Cste , Infer , Type , Equal ,

    Authors

    V.C.


struct

Scilab Function
Last update : 09/10/2006

struct - creer une struct

Calling Sequence

st=struct(field1,value1,field2,value2, ...)

Parameters

  • field1, field2, ... : noms des champs (chaines de caracteres)
  • value1, value2, ... : les valeurs des champs (acceptent tous types de données (double, matrice de doubles,des cells, char, ...)

Description

La fonction struc t retourne une struct avec des noms de champs field1 , field2 , .., et dont les valeurs respectives sont value 1 , value2 , ...

Examples

//creer une struct: date les champs sont: 'jour' (valeur: 25), 'mois' (valeur: 'DEC'), 'annee' (valeur: 2006)
date=struct('jour',25,'mois','DEC','annee',2006)
// changer la valeur des champs
date.jour=19;
date.mois='AOU';
date.annee=1973;
// ajouter un champ 'semaine'
date.semaine=32

See Also

cell ,


Chaines_de_caracteres_Matlab-Scilab

Documentation
Last update : 02/04/2004

Chaines_de_caracteres_Matlab-Scilab - Généralités...

Description

Les chaînes de caractère ne sont pas considérées de la même façon en Matlab ou en Scilab. Voici une brève présentation des principales différences.

Matlab considère une chaine de caractères comme Scilab considère une matrice de caractères. Par exemple, un équivalent Scilab pour la chaîne de caractères Matlab 'machaine' pourrait être ["m","a","c","h","a","i","n","e"]. Donc, dans Scilab, une chaîne de caractères est un objet de type 'string' (10) et est toujours de taille 1 x 1 mais dans Matlab, une chaîne de caractères est de taille 1 x nombre_de_caractères.

Ainsi, on voit bien qu'une colonne donnée d'une matrice de chaînes de caractères Matlab ne peut contenir que des chaînes de même taille ce qui n'est pas vrai dans Scilab. On peut dire qu'une chaîne de caractères Scilab est équivalente à une cell de chaînes de caractère Matlab.

Toutes ces différences peuvent conduire à des résultats différents pour l'exécution des mêmes commandes dans Scilab ou dans Matlab, particulièrement pour les fonctions travaillant sur les dimensions comme length() ou size().

See Also

mstr2sci ,

Authors

V.C.


Contents

Fonction M2SCI
Last update : 05/10/2004

Contents - Créé un arbre contenant les données d'inférence du contenu d'une variable

Calling Sequence

contents=Contents(liste_d_index,list_d_infer)

Parameters

  • liste_d_index : liste d'indexes similaires aux indexes retournés par macr2tree .
  • liste_d_infer : liste de tlists de type "infer" contenant les données d'inférence pour l'index correspondant.
  • contents : une tlist de type "contents"

Description

Cette fonction créé une tlist représentant les données d'inférence pour le contenu d'une Cell ou d'une Struct quand on utilise M2SCI. Tous les paramètres d'entrée sont vérifiés pour être compatible avec les "tlists M2SCI". (Unknown=-1 dans M2SCI). Assurez vous que pour chaque entrée dans la liste d'indexes, il y a une entrée dans la liste de tlists de type "infer".

See Also

get_contents_infer , Funcall , Operation , Variable , Cste , Infer , Type , Equal ,

Authors

V.C.


Cste

Fonction M2SCI
Last update : 05/10/2004

Cste - Créé un arbre représentant une constante

Calling Sequence

const=Cste(value)

Parameters

  • value : valeur de la constante
  • const : une tlist de type "cste"

Description

Cette fonction créé une tlist représentant les données d'inférence quand on utilise M2SCI. Tous les paramètres d'entrée sont vérifiés pour être compatible avec les "tlists M2SCI".

See Also

Funcall , Operation , Variable , Infer , Contents , Type , Equal ,

Authors

V.C.


Equal

Fonction M2SCI
Last update : 05/10/2004

Equal - Créé un arbre représentant une instruction

Calling Sequence

eq=Equal(lhslist,expression)

Parameters

  • lhslist : liste des paramètres de sortie (liste de "tlists M2SCI")
  • expression : partie droite de l'instruction (une "tlist M2SCI")
  • eq : une tlist de type "equal"

Description

Cette fonction créé une tlist représentant les données d'inférence quand on utilise M2SCI. Tous les paramètres d'entrée sont vérifiés pour être compatible avec les "tlists M2SCI".

See Also

Funcall , Operation , Variable , Cste , Infer , Contents , Type ,

Authors

V.C.


Funcall

Fonction M2SCI
Last update : 05/10/2004

Funcall - Créé un arbre représentant l'appel à une fonction

Calling Sequence

fc=Funcall(name,lhsnb,rhslist,lhslist)

Parameters

  • name : nom de la fonction (chaîne de caratères)
  • lhsnb : nombre de paramètres de sortie (constante)
  • rhslist : liste des paramètres d'entrée (liste de "tlists M2SCI")
  • lhslist : liste des paramètres de sortie (liste de "tlists M2SCI")
  • fc : une tlist de type "funcall"

Description

Cette fonction créé une tlist représentant les données d'inférence quand on utilise M2SCI. Tous les paramètres d'entrée sont vérifiés pour être compatible avec les "tlists M2SCI".

See Also

Operation , Variable , Cste , Infer , Contents , Type , Equal ,

Authors

V.C.


Infer

Fonction M2SCI
Last update : 05/10/2004

Infer - Créé un arbre contenant les données d'inférence

Calling Sequence

infer=Infer(varargin)

Parameters

  • varargin : données d'inference
    • varargin(1) : liste des dimensions, la valeur par défaut est list(Unknown,Unknown)
    • varargin(2) : type (tlist de type "type", voir la page d'aide de Type), la valeur par défaut est Type(Unknown,Unknown)
    • varargin(3) : contenu (tlist de type "contents", voir la page d'aide de Type), la valeur par défaut est Contents(list(),list()). Ce champ est utilisé uniquement si la donnée réprésentée est une Cell ou une Struct.
  • infer : une tlist de type "infer"

Description

Cette fonction créé une tlist représentant les données d'inférence quand on utilise M2SCI. Tous les paramètres d'entrée sont vérifiés pour être compatible avec les "tlists M2SCI". (Unknown=-1 dans M2SCI)

See Also

Funcall , Operation , Variable , Cste , Contents , Type , Equal ,

Authors

V.C.


Matlab-Scilab_character_strings

Documentation
Last update : 06/01/2006

Matlab-Scilab_character_strings - Generally speaking about...

Description

Matlab and Scilab character strings are not considered in the same way. Here is a little talk about differences between them.

Matlab considers a character string as Scilab considers a matrix of characters. For example, a Scilab equivalent for Matlab 'mystring' could be ["m","y","s","t","r","i","n","g"]. So in Scilab, a character string is a object of type string (10) and always have size 1 x 1 but in Matlab, a character string have size equal to 1 x number_of_characters.

Considering this, we can see that a Matlab character string matrix column can only be made of same-size character strings what is not true in Scilab. We can say that a Scilab character string matrix is equivalent to a Matlab cell of character strings.

All these differences can lead to different results while executing same commands in Scilab or in Matlab, particularly for "dimension" functions such as length() or size().

See Also

mstr2sci ,

Authors

V.C.


Operation

Fonction M2SCI
Last update : 05/10/2004

Operation - Créé un arbre représentant une opération

Calling Sequence

op=Operation(operator,operands,out)

Parameters

  • operator : symbole de l'opérateur (chaîne de caractères)
  • operands : liste des opérandes (liste de "tlists M2SCI")
  • out : liste des paramètres de sortie (liste de "tlists M2SCI")
  • op : une tlist de type "operation"

Description

Cette fonction créé une tlist représentant les données d'inférence quand on utilise M2SCI. Tous les paramètres d'entrée sont vérifiés pour être compatible avec les "tlists M2SCI".

See Also

Funcall , Variable , Cste , Infer , Contents , Type , Equal ,

Authors

V.C.


Type

Fonction M2SCI
Last update : 05/10/2004

Type - Créé un arbre contenant les données d'inférence de type

Calling Sequence

tp=Type(vtype,property)

Parameters

  • vtype : type de donnée (voir l'aide de m2scideclare)
  • property : propriété de la donnée (voir l'aide de m2scideclare)
  • tp : une tlist de type "type"

Description

Cette fonction créé une tlist représentant les données d'inférence quand on utilise M2SCI. Tous les paramètres d'entrée sont vérifiés pour être compatible avec les "tlists M2SCI". (Unknown=-1 dans M2SCI)

See Also

Funcall , Operation , Variable , Cste , Infer , Contents , Equal , m2scideclare ,

Authors

V.C.


Variable

Fonction M2SCI
Last update : 05/10/2004

Variable - Créé un arbre représentant une variable

Calling Sequence

var=Variable(name,infer)

Parameters

  • var : nom de la variable (chaîne de caractères)
  • infer : données d'inférence (une tlist de type "infer", voir la page d'aide de Infer)
  • var : une tlist de type "variable"

Description

Cette fonction créé une tlist représentant les données d'inférence quand on utilise M2SCI. Tous les paramètres d'entrée sont vérifiés pour être compatible avec les "tlists M2SCI".

See Also

Funcall , Operation , Cste , Infer , Contents , Type , Equal ,

Authors

V.C.


Solveurs creux
dnaupd - Interface for the Implicitly Restarted Arnoldi Iteration, to compute approximations to a few eigenpairs of a real linear operator
dsaupd - Interface for the Implicitly Restarted Arnoldi Iteration, to compute approximations to a few eigenpairs of a real and symmetric linear operator
gmres - generalized minimum residual method with restarts
pcg - precondioned conjugate gradient
qmr - quasi minimal resiqual method with preconditioning


dnaupd

Scilab Function
Last update : 31/10/2006

dnaupd - Interface for the Implicitly Restarted Arnoldi Iteration, to compute approximations to a few eigenpairs of a real linear operator

Calling Sequence

[IDO,RESID,V,IPARAM,IPNTR,WORKD,WORKL,INFO] = dsaupd(ID0,BMAT,N,WHICH,NEV,TOL,RESID,NCV,V,IPARAM,IPNTR,WORKD,WORKL,INFO)

Parameters

  • ID0

    : Integer. (INPUT/OUTPUT) Reverse communication flag. IDO must be zero on the first call to dnaupd. IDO will be set internally to indicate the type of operation to be performed. Control is then given back to the calling routine which has the responsibility to carry out the requested operation and call dnaupd with the result. The operand is given in WORKD(IPNTR(1)), the result must be put in WORKD(IPNTR(2)).

    IDO = 0: first call to the reverse communication interface

    IDO = -1: compute Y = OP * X where IPNTR(1) is the pointer into WORKD for X, IPNTR(2) is the pointer into WORKD for Y. This is for the initialization phase to force the starting vector into the range of OP.

    IDO = 1: compute Y = OP * X where IPNTR(1) is the pointer into WORKD for X, IPNTR(2) is the pointer into WORKD for Y. In mode 3 and 4, the vector B * X is already available in WORKD(ipntr(3)). It does not need to be recomputed in forming OP * X.

    IDO = 2: compute Y = B * X where IPNTR(1) is the pointer into WORKD for X, IPNTR(2) is the pointer into WORKD for Y.

    IDO = 3: compute the IPARAM(8) real and imaginary parts of the shifts where INPTR(14) is the pointer into WORKL for placing the shifts. See Remark 5 below.

    IDO = 99: done

  • BMAT : Character, specifies the type of the matrix B that defines the semi-inner product for the operator OP.

    B = 'I' -> standard eigenvalue problem A*x = lambda*x

    B = 'G' -> generalized eigenvalue problem A*x = lambda*B*x

  • N : Integer, dimension of the eigenproblem.
  • WHICH : string of length 2, Specify which of the Ritz values of OP to compute.

    'LM' - want the NEV eigenvalues of largest magnitude.

    'SM' - want the NEV eigenvalues of smallest magnitude.

    'LR' - want the NEV eigenvalues of largest real part.

    'SR' - want the NEV eigenvalues of smallest real part.

    'LI' - want the NEV eigenvalues of largest imaginary part.

    'SI' - want the NEV eigenvalues of smallest imaginary part.

  • NEV : Integer, number of eigenvalues of OP to be computed. 0 < NEV < N-1.
  • TOL : scalar. Stopping criterion: the relative accuracy of the Ritz value is considered acceptable if BOUNDS(I) <= TOL*ABS(RITZ(I)). If TOL <= 0. is passed the machine precision is set.
  • RESID : array of length N (INPUT/OUTPUT)

    On INPUT: If INFO==0, a random initial residual vector is used, else RESID contains the initial residual vector, possibly from a previous run.

    On OUTPUT: RESID contains the final residual vector.

  • NCV : Integer. Number of columns of the matrix V. NCV must satisfy the two inequalities 2 <= NCV-NEV and NCV <= N. This will indicate how many Arnoldi vectors are generated at each iteration. After the startup phase in which NEV Arnoldi vectors are generated, the algorithm generates approximately NCV-NEV Arnoldi vectors at each subsequent update iteration. Most of the cost in generating each Arnoldi vector is in the matrix-vector operation OP*x.

    NOTE: 2 <= NCV-NEV in order that complex conjugate pairs of Ritz values are kept together. (See remark 4 below)

  • V : N by NCV array. Contains the final set of Arnoldi basis vectors.
  • IPARAM : array of length 11. (INPUT/OUTPUT)

    IPARAM(1) = ISHIFT: method for selecting the implicit shifts. The shifts selected at each iteration are used to restart the Arnoldi iteration in an implicit fashion.

    ISHIFT = 0: the shifts are provided by the user via reverse communication. The real and imaginary parts of the NCV eigenvalues of the Hessenberg matrix H are returned in the part of the WORKL array corresponding to RITZR and RITZI. See remark 5 below.

    ISHIFT = 1: exact shifts with respect to the current Hessenberg matrix H. This is equivalent to restarting the iteration with a starting vector that is a linear combination of approximate Schur vectors associated with the "wanted" Ritz values.

    IPARAM(2) = LEVEC No longer referenced.

    IPARAM(3) = MXITER On INPUT: maximum number of Arnoldi update iterations allowed. On OUTPUT: actual number of Arnoldi update iterations taken.

    IPARAM(4) = NB: blocksize to be used in the recurrence. The code currently works only for NB = 1.

    IPARAM(5) = NCONV: number of "converged" Ritz values. This represents the number of Ritz values that satisfy the convergence criterion.

    IPARAM(6) = IUPD No longer referenced. Implicit restarting is ALWAYS used.

    IPARAM(7) = MODE On INPUT determines what type of eigenproblem is being solved. Must be 1,2,3,4; See under Description of dsaupd for the five modes available.

    IPARAM(8) = NP
When ido = 3 and the user provides shifts through reverse
communication (IPARAM(1)=0), dsaupd  returns NP, the number
of shifts the user is to provide. 0  < NP  <= NCV-NEV. See Remark
5 below.

    IPARAM(9) = NUMOP, IPARAM(10) = NUMOPB, IPARAM(11) = NUMREO, OUTPUT: NUMOP = total number of OP*x operations, NUMOPB = total number of B*x operations if BMAT='G', NUMREO = total number of steps of re-orthogonalization.

  • IPNTR : array of length 14. Pointer to mark the starting locations in the WORKD and WORKL arrays for matrices/vectors used by the Arnoldi iteration.

    IPNTR(1): pointer to the current operand vector X in WORKD.

    IPNTR(2): pointer to the current result vector Y in WORKD.

    IPNTR(3): pointer to the vector B * X in WORKD when used in the shift-and-invert mode.

    IPNTR(4): pointer to the next available location in WORKL that is untouched by the program.

    IPNTR(5): pointer to the NCV by NCV upper Hessenberg matrix H in WORKL.

    IPNTR(6): pointer to the real part of the ritz value array RITZR in WORKL.

    IPNTR(7): pointer to the imaginary part of the ritz value array RITZI in WORKL.

    IPNTR(8): pointer to the Ritz estimates in array WORKL associated with the Ritz values located in RITZR and RITZI in WORKL.

    IPNTR(14): pointer to the NP shifts in WORKL. See Remark 5 below.

    Note: IPNTR(9:13) is only referenced by dseupd . See Remark 2.

    IPNTR(9): pointer to the real part of the NCV RITZ values of the original system.

    IPNTR(10): pointer to the imaginary part of the NCV RITZ values of the original system.

    IPNTR(11): pointer to the NCV corresponding error bounds.

    IPNTR(12):pointer to the NCV by NCV upper quasi-triangular Schur matrix for H.

    IPNTR(11): pointer to the NCV by NCV matrix of eigenvectors of the upper Hessenberg matrix H. Only referenced by dneupd if RVEC = .TRUE. See Remark 2 below.

  • WORKD : Double precision work array of length 3*N. (REVERSE COMMUNICATION) Distributed array to be used in the basic Arnoldi iteration for reverse communication. The user should not use WORKD as temporary workspace during the iteration. Upon termination WORKD(1:N) contains B*RESID(1:N). If an invariant subspace associated with the converged Ritz values is desired, see remark 2 below, subroutine dneupd uses this output. See Data Distribution Note below.
  • WORKL : work array of length at least 3*NCV**2 + 6*NCV. (OUTPUT/WORKSPACE) Private (replicated) array on each PE or array allocated on the front end. See Data Distribution Note below.
  • INFO : Integer. (INPUT/OUTPUT)

    If INFO == 0, a randomly initial residual vector is used, else RESID contains the initial residual vector, possibly from a previous run.

    Error flag on output.

    = 0: Normal exit.

    = 1: Maximum number of iterations taken. All possible eigenvalues of OP has been found. IPARAM(5) returns the number of wanted converged Ritz values.

    = 2: No longer an informational error. Deprecated starting with release 2 of ARPACK.

    = 3: No shifts could be applied during a cycle of the Implicitly restarted Arnoldi iteration. One possibility is to increase the size of NCV relative to NEV. See remark 4 below.

    = -1: N must be positive.

    = -2: NEV must be positive.

    = -3: NCV-NEV >= 2 and less than or equal to N.

    = -4: The maximum number of Arnoldi update iterations allowed must be greater than zero.

    = -5: WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'

    = -6: BMAT must be one of 'I' or 'G'.

    = -7: Length of private work array WORKL is not sufficient.

    = -8: Error return from LAPACK eigenvalue calculation;

    = -9: Starting vector is zero.

    = -10: IPARAM(7) must be 1,2,3,4.

    = -11: IPARAM(7) = 1 and BMAT = 'G' are incompatable.

    = -12: IPARAM(1) must be equal to 0 or 1.

    = -9999: Could not build an Arnoldi factorization. IPARAM(5) returns the size of the current Arnoldi factorization. The user is advised to check that enough workspace and array storage has been allocated.

Description

Reverse communication interface for the Implicitly Restarted Arnoldi iteration. This subroutine computes approximations to a few eigenpairs of a linear operator "OP" with respect to a semi-inner product defined by a symmetric positive semi-definite real matrix B. B may be the identity matrix. NOTE: If the linear operator "OP" is real and symmetric with respect to the real positive semi-definite symmetric matrix B, i.e. B*OP = (OP`)*B, then subroutine dsaupd should be used instead.

The computed approximate eigenvalues are called Ritz values and the corresponding approximate eigenvectors are called Ritz vectors.

dnaupd is usually called iteratively to solve one of the following problems:

Mode 1: A*x = lambda*x. OP = A , B = I .

Mode 2: A*x = lambda*M*x, M symmetric positive definite OP = inv[M]*A, B = M . (If M can be factored see remark 3 below)

Mode 3: A*x = lambda*M*x, M symmetric positive semi-definite. OP = Real_Part{ inv[A - sigma*M]*M }, B = M . shift-and-invert mode (in real arithmetic) If OP*x = amu*x , then amu = 1/2 * [ 1/(lambda-sigma) + 1/(lambda-conjg(sigma))] . Note: If sigma is real, i.e. imaginary part of sigma is zero; Real_Part{ inv[A - sigma*M]*M } == inv[A - sigma*M]*M amu == 1/(lambda-sigma) .

Mode 4: A*x = lambda*M*x, M symmetric semi-definite OP = Imaginary_Part{ inv[A - sigma*M]*M } , B = M . shift-and-invert mode (in real arithmetic) If OP*x = amu*x , then amu = 1/2i * [ 1/(lambda-sigma) - 1/(lambda-conjg(sigma)) ] .

Both mode 3 and 4 give the same enhancement to eigenvalues close to the (complex) shift sigma. However, as lambda goes to infinity, the operator OP in mode 4 dampens the eigenvalues more strongly than does OP defined in mode 3.

NOTE: The action of w <- inv[A - sigma*M]*v or w <- inv[M]*v should be accomplished either by a direct method using a sparse matrix factorization and solving [A - sigma*M]*w = v or M*w = v , or through an iterative method for solving these systems. If an iterative method is used, the convergence test must be more stringent than the accuracy requirements for the eigenvalue approximations.

Remarks

1. The computed Ritz values are approximate eigenvalues of OP. The selection of WHICH should be made with this in mind when Mode = 3 and 4. After convergence, approximate eigenvalues of the original problem may be obtained with the ARPACK subroutine dneupd. 2. If a basis for the invariant subspace corresponding to the converged Ritz values is needed, the user must call dneupd immediately following completion of dnaupd. This is new starting with release 2 of ARPACK. 3. If M can be factored into a Cholesky factorization M = LL` then Mode = 2 should not be selected. Instead one should use Mode = 1 with OP = inv(L)*A*inv(L`). Appropriate triangular linear systems should be solved with L and L` rather than computing inverses. After convergence, an approximate eigenvector z of the original problem is recovered by solving L`z = x where x is a Ritz vector of OP. 4. At present there is no a-priori analysis to guide the selection of NCV relative to NEV. The only formal requrement is that NCV > NEV + 2. However, it is recommended that NCV >= 2*NEV+1. If many problems of the same type are to be solved, one should experiment with increasing NCV while keeping NEV fixed for a given test problem. This will usually decrease the required number of OP*x operations but it also increases the work and storage required to maintain the orthogonal basis vectors. The optimal "cross-over" with respect to CPU time is problem dependent and must be determined empirically. See Chapter 8 of Reference 2 for further information. 5. When IPARAM(1) = 0, and IDO = 3, the user needs to provide the NP = IPARAM(8) real and imaginary parts of the shifts in locations

   real part                  imaginary part
   -----------------------    -----------------------
1  WORKL(IPNTR(14))           WORKL(IPNTR(14)+NP)
2  WORKL(IPNTR(14)+1)         WORKL(IPNTR(14)+NP+1)

NP  WORKL(IPNTR(14)+NP-1)     WORKL(IPNTR(14)+2*NP-1).

Only complex conjugate pairs of shifts may be applied and the pairs must be placed in consecutive locations. The real part of the eigenvalues of the current upper Hessenberg matrix are located in WORKL(IPNTR(6)) through WORKL(IPNTR(6)+NCV-1) and the imaginary part in WORKL(IPNTR(7)) through WORKL(IPNTR(7)+NCV-1). They are ordered according to the order defined by WHICH. The complex conjugate pairs are kept together and the associated Ritz estimates are located in WORKL(IPNTR(8)), WORKL(IPNTR(8)+1), ... , WORKL(IPNTR(8)+NCV-1).

See Also

dsaupd ,

Authors

Danny Sorensen, Richard Lehoucq, Phuong Vu CRPC / Rice University Applied Mathematics Rice University Houston, Texas

Bibliography

1. D.C. Sorensen, "Implicit Application of Polynomial Filters in a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), pp 357-385.

2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration", Rice University Technical Report TR95-13, Department of Computational and Applied Mathematics.

3. B.N. Parlett, "The Symmetric Eigenvalue Problem". Prentice-Hall, 1980.

4. B.N. Parlett, B. Nour-Omid, "Towards a Black Box Lanczos Program", Computer Physics Communications, 53 (1989), pp 169-179.

5. B. Nour-Omid, B.N. Parlett, T. Ericson, P.S. Jensen, "How to Implement the Spectral Transformation", Math. Comp., 48 (1987), pp 663-673.

6. R.G. Grimes, J.G. Lewis and H.D. Simon, "A Shifted Block Lanczos Algorithm for Solving Sparse Symmetric Generalized Eigenproblems", SIAM J. Matr. Anal. Apps., January (1993).

7. L. Reichel, W.B. Gragg, "Algorithm 686: FORTRAN Subroutines for Updating the QR decomposition", ACM TOMS, December 1990, Volume 16 Number 4, pp 369-377.

8. R.B. Lehoucq, D.C. Sorensen, "Implementation of Some Spectral Transformations in a k-Step Arnoldi Method". In Preparation.

Used Function

Based on ARPACK routine dsaupd


dsaupd

Scilab Function
Last update : 25/10/2006

dsaupd - Interface for the Implicitly Restarted Arnoldi Iteration, to compute approximations to a few eigenpairs of a real and symmetric linear operator

Calling Sequence

[IDO,RESID,V,IPARAM,IPNTR,WORKD,WORKL,INFO] = dsaupd(ID0,BMAT,N,WHICH,NEV,TOL,RESID,NCV,V,IPARAM,IPNTR,WORKD,WORKL,INFO)

Parameters

  • ID0

    : Integer. (INPUT/OUTPUT) Reverse communication flag. IDO must be zero on the first call to dsaupd . IDO will be set internally to indicate the type of operation to be performed. Control is then given back to the calling routine which has the responsibility to carry out the requested operation and call dsaupd with the result. The operand is given in WORKD(IPNTR(1)), the result must be put in WORKD(IPNTR(2)). (If Mode = 2 see remark 5 below)

    IDO = 0: first call to the reverse communication interface

    IDO = -1: compute Y = OP * X where IPNTR(1) is the pointer into WORKD for X, IPNTR(2) is the pointer into WORKD for Y. This is for the initialization phase to force the starting vector into the range of OP.

    IDO = 1: compute Y = OP * X where IPNTR(1) is the pointer into WORKD for X, IPNTR(2) is the pointer into WORKD for Y. In mode 3,4 and 5, the vector B * X is already available in WORKD(ipntr(3)). It does not need to be recomputed in forming OP * X.

    IDO = 2: compute Y = B * X where IPNTR(1) is the pointer into WORKD for X, IPNTR(2) is the pointer into WORKD for Y.

    IDO = 3: compute the IPARAM(8) shifts where IPNTR(11) is the pointer into WORKL for placing the shifts. See remark 6 below.

    IDO = 99: done

  • BMAT : Character, specifies the type of the matrix B that defines the semi-inner product for the operator OP.

    B = 'I' -> standard eigenvalue problem A*x = lambda*x

    B = 'G' -> generalized eigenvalue problem A*x = lambda*B*x

  • N : Integer, dimension of the eigenproblem.
  • WHICH : string of length 2, Specify which of the Ritz values of OP to compute.

    'LA' - compute the NEV largest (algebraic) eigenvalues.

    'SA' - compute the NEV smallest (algebraic) eigenvalues.

    'LM' - compute the NEV largest (in magnitude) eigenvalues.

    'SM' - compute the NEV smallest (in magnitude) eigenvalues.

    'BE' - compute NEV eigenvalues, half from each end of the spectrum. When NEV is odd, compute one more from the high end than from the low end. (see remark 1 below)

  • NEV : Integer, number of eigenvalues of OP to be computed. 0 < NEV < N.
  • TOL

    4. B.N. Parlett, B. Nour-Omid, "Towards a Black Box Lanczos Program", Computer Physics Communications, 53 (1989), pp 169-179.

    5. B. Nour-Omid, B.N. Parlett, T. Ericson, P.S. Jensen, "How to Implement the Spectral Transformation", Math. Comp., 48 (1987), pp 663-673.

    6. R.G. Grimes, J.G. Lewis and H.D. Simon, "A Shifted Block Lanczos Algorithm for Solving Sparse Symmetric Generalized Eigenproblems", SIAM J. Matr. Anal. Apps., January (1993).

    7. L. Reichel, W.B. Gragg, "Algorithm 686: FORTRAN Subroutines for Updating the QR decomposition", ACM TOMS, December 1990, Volume 16 Number 4, pp 369-377.

    8. R.B. Lehoucq, D.C. Sorensen, "Implementation of Some Spectral Transformations in a k-Step Arnoldi Method". In Preparation.

    : scalar. Stopping criterion: the relative accuracy of the Ritz value is considered acceptable if BOUNDS(I) <= TOL*ABS(RITZ(I)). If TOL <= 0. is passed the machine precision is set.
  • RESID : array of length N (INPUT/OUTPUT)

    On INPUT: If INFO==0, a random initial residual vector is used, else RESID contains the initial residual vector, possibly from a previous run.

    On OUTPUT: RESID contains the final residual vector.

  • NCV : Integer.Number of columns of the matrix V (less than or equal to N). This will indicate how many Lanczos vectors are generated at each iteration. After the startup phase in which NEV Lanczos vectors are generated, the algorithm generates NCV-NEV Lanczos vectors at each subsequent update iteration. Most of the cost in generating each Lanczos vector is in the matrix-vector product OP*x. (See remark 4 below).
  • V : N by NCV array. The NCV columns of V contain the Lanczos basis vectors.
  • IPARAM : array of length 11. (INPUT/OUTPUT)

    IPARAM(1) = ISHIFT: method for selecting the implicit shifts. The shifts selected at each iteration are used to restart the Arnoldi iteration in an implicit fashion.

    ISHIFT = 0: the shifts are provided by the user via reverse communication. The NCV eigenvalues of the current tridiagonal matrix T are returned in the part of WORKL array corresponding to RITZ. See remark 6 below.

    ISHIFT = 1: exact shifts with respect to the reduced tridiagonal matrix T. This is equivalent to restarting the iteration with a starting vector that is a linear combination of Ritz vectors associated with the "wanted" Ritz values.

    IPARAM(2) = LEVEC No longer referenced. See remark 2 below.

    IPARAM(3) = MXITER On INPUT: maximum number of Arnoldi update iterations allowed. On OUTPUT: actual number of Arnoldi update iterations taken.

    IPARAM(4) = NB: blocksize to be used in the recurrence. The code currently works only for NB = 1.

    IPARAM(5) = NCONV: number of "converged" Ritz values. This represents the number of Ritz values that satisfy the convergence criterion.

    IPARAM(6) = IUPD No longer referenced. Implicit restarting is ALWAYS used.

    IPARAM(7) = MODE On INPUT determines what type of eigenproblem is being solved. Must be 1,2,3,4,5; See under Description of dsaupd for the five modes available.

    IPARAM(8) = NP
When ido = 3 and the user provides shifts through reverse
communication (IPARAM(1)=0), dsaupd  returns NP, the number
of shifts the user is to provide. 0  < NP  <= NCV-NEV. See Remark
6 below.

    IPARAM(9) = NUMOP, IPARAM(10) = NUMOPB, IPARAM(11) = NUMREO, OUTPUT: NUMOP = total number of OP*x operations, NUMOPB = total number of B*x operations if BMAT='G', NUMREO = total number of steps of re-orthogonalization.

  • IPNTR : array of length 11. Pointer to mark the starting locations in the WORKD and WORKL arrays for matrices/vectors used by the Lanczos iteration.

    IPNTR(1): pointer to the current operand vector X in WORKD.

    IPNTR(2): pointer to the current result vector Y in WORKD.

    IPNTR(3): pointer to the vector B * X in WORKD when used in the shift-and-invert mode.

    IPNTR(4): pointer to the next available location in WORKL that is untouched by the program.

    IPNTR(5): pointer to the NCV by 2 tridiagonal matrix T in WORKL.

    IPNTR(6): pointer to the NCV RITZ values array in WORKL.

    IPNTR(7): pointer to the Ritz estimates in array WORKL associated with the Ritz values located in RITZ in WORKL.

    IPNTR(11): pointer to the NP shifts in WORKL. See Remark 6 below.

    Note: IPNTR(8:10) is only referenced by dseupd . See Remark 2.

    IPNTR(8): pointer to the NCV RITZ values of the original system.

    IPNTR(9): pointer to the NCV corresponding error bounds.

    IPNTR(10): pointer to the NCV by NCV matrix of eigenvectors of the tridiagonal matrix T. Only referenced by dseupd if RVEC = .TRUE. See Remarks

  • WORKD : work array of length 3*N. (REVERSE COMMUNICATION) Distributed array to be used in the basic Arnoldi iteration for reverse communication. The user should not use WORKD as temporary workspace during the iteration. Upon termination WORKD(1:N) contains B*RESID(1:N). If the Ritz vectors are desired subroutine dseupd uses this output. See Data Distribution Note below.
  • WORKL : work array of length at least NCV**2 + 8*NCV. (OUTPUT/WORKSPACE) Private (replicated) array on each PE or array allocated on the front end. See Data Distribution Note below. add here the parameter description
  • INFO : Integer. (INPUT/OUTPUT)

    If INFO == 0, a randomly initial residual vector is used, else RESID contains the initial residual vector, possibly from a previous run.

    Error flag on output.

    = 0: Normal exit.

    = 1: Maximum number of iterations taken. All possible eigenvalues of OP has been found. IPARAM(5) returns the number of wanted converged Ritz values.

    = 2: No longer an informational error. Deprecated starting with release 2 of ARPACK.

    = 3: No shifts could be applied during a cycle of the Implicitly restarted Arnoldi iteration. One possibility is to increase the size of NCV relative to NEV. See remark 4 below.

    = -1: N must be positive.

    = -2: NEV must be positive.

    = -3: NCV must be greater than NEV and less than or equal to N.

    = -4: The maximum number of Arnoldi update iterations allowed must be greater than zero.

    = -5: WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.

    = -6: BMAT must be one of 'I' or 'G'.

    = -7: Length of private work array WORKL is not sufficient.

    = -8: Error return from trid. eigenvalue calculation; Informatinal error from LAPACK routine dsteqr .

    = -9: Starting vector is zero.

    = -10: IPARAM(7) must be 1,2,3,4,5.

    = -11: IPARAM(7) = 1 and BMAT = 'G' are incompatable.

    = -12: IPARAM(1) must be equal to 0 or 1.

    = -13: NEV and WHICH = 'BE' are incompatable.

    = -9999: Could not build an Arnoldi factorization. IPARAM(5) returns the size of the current Arnoldi factorization. The user is advised to check that enough workspace and array storage has been allocated.

Description

Reverse communication interface for the Implicitly Restarted Arnoldi Iteration. For symmetric problems this reduces to a variant of the Lanczos method. This method has been designed to compute approximations to a few eigenpairs of a linear operator OP that is real and symmetric with respect to a real positive semi-definite symmetric matrix B, i.e. B*OP = (OP`)*B .

Another way to express this condition is < x,OPy > = < OPx,y > where <z,w > = z`Bw .

In the standard eigenproblem B is the identity matrix.( A` denotes transpose of A)

The computed approximate eigenvalues are called Ritz values and the corresponding approximate eigenvectors are called Ritz vectors.

dsaupd is usually called iteratively to solve one of the following problems:

Mode 1: A*x = lambda*x, A symmetric ===> OP = A and B = I.

Mode 2: A*x = lambda*M*x, A symmetric, M symmetric positive definite ===> OP = inv[M]*A and B = M. ===> (If M can be factored see remark 3 below)

Mode 3: K*x = lambda*M*x, K symmetric, M symmetric positive semi-definite ===> OP = (inv[K - sigma*M])*M and B = M. ===> Shift-and-Invert mode

Mode 4: K*x = lambda*KG*x, K symmetric positive semi-definite, KG symmetric indefinite ===> OP = (inv[K - sigma*KG])*K and B = K. ===> Buckling mode

Mode 5: A*x = lambda*M*x, A symmetric, M symmetric positive semi-definite ===> OP = inv[A - sigma*M]*[A + sigma*M] and B = M. ===> Cayley transformed mode

NOTE: The action of w <- inv[A - sigma*M]*v or w <- inv[M]*v should be accomplished either by a direct method using a sparse matrix factorization and solving [A - sigma*M]*w = v or M*w = v ,

or through an iterative method for solving these systems. If an iterative method is used, the convergence test must be more stringent than the accuracy requirements for the eigenvalue approximations.

Remarks

1. The converged Ritz values are always returned in ascending algebraic order. The computed Ritz values are approximate eigenvalues of OP. The selection of WHICH should be made with this in mind when Mode = 3,4,5. After convergence, approximate eigenvalues of the original problem may be obtained with the ARPACK subroutine dseupd .

2. If the Ritz vectors corresponding to the converged Ritz values are needed, the user must call dseupd immediately following completion of dsaupd . This is new starting with version 2.1 of ARPACK.

3. If M can be factored into a Cholesky factorization M = LL` then Mode = 2 should not be selected. Instead one should use Mode = 1 with OP = inv(L)*A*inv(L`). Appropriate triangular linear systems should be solved with L and L` rather than computing inverses. After convergence, an approximate eigenvector z of the original problem is recovered by solving L`z = x where x is a Ritz vector of OP.

4. At present there is no a-priori analysis to guide the selection of NCV relative to NEV. The only formal requrement is that NCV > NEV. However, it is recommended that NCV >= 2*NEV. If many problems of the same type are to be solved, one should experiment with increasing NCV while keeping NEV fixed for a given test problem. This will usually decrease the required number of OP*x operations but it also increases the work and storage required to maintain the orthogonal basis vectors. The optimal "cross-over" with respect to CPU time is problem dependent and must be determined empirically.

5. If IPARAM(7) = 2 then in the Reverse commuication interface the user
    must do the following. When IDO = 1, Y = OP * X is to be computed.
    When IPARAM(7) = 2 OP = inv(B)*A. After computing A*X the user
    must overwrite X with A*X. Y is then the solution to the linear set
    of equations B*Y = A*X.

6. When IPARAM(1) = 0, and IDO = 3, the user needs to provide the
    NP = IPARAM(8) shifts in locations:
    1   WORKL(IPNTR(11))
    2   WORKL(IPNTR(11)+1)

    NP  WORKL(IPNTR(11)+NP-1).

    The eigenvalues of the current tridiagonal matrix are located in
    WORKL(IPNTR(6)) through WORKL(IPNTR(6)+NCV-1). They are in the
    order defined by WHICH. The associated Ritz estimates are located in
    WORKL(IPNTR(8)), WORKL(IPNTR(8)+1), ... , WORKL(IPNTR(8)+NCV-1).

See Also

dnaupd ,

Authors

Danny Sorensen, Richard Lehoucq, Phuong Vu CRPC / Rice University Applied Mathematics Rice University Houston, Texas

Bibliography

1. D.C. Sorensen, "Implicit Application of Polynomial Filters in a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), pp 357-385.

2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration", Rice University Technical Report TR95-13, Department of Computational and Applied Mathematics.

3. B.N. Parlett and Y. Saad, "Complex Shift and Invert Strategies for Real Matrices", Linear Algebra and its Applications, vol 88/89, pp 575-595, (1987).

Used Function

Based on ARPACK routine dnaupd


gmres

Scilab Function
Last update : 06/01/2006

gmres - generalized minimum residual method with restarts

Calling Sequence

[x,flag,err,iter,res] = gmres(A,b,rstr,tol,maxi,M,x0)

Parameters

  • A : n-by-n matrix or function returning A*x
  • b : right hand side vector
  • x0 : initial guess vector (default: zeros(n,1))
  • M : preconditioner: matrix or function returning M*x (In the first case, default: eye(n,n))
  • rstr : number of iterations between restarts (default: 10)
  • maxi : maximum number of iterations (default: n)
  • tol : error tolerance (default: 1e-6)
  • x : solution vector
  • err : final residual norm
  • iter : number of iterations performed
  • flag : 0 = gmres converged to the desired tolerance within maxi iterations
  • res : residual vector

Description

Solves the linear system Ax=b using the Generalized Minimal residual (GMRES(m)) method with restarts.

See Also

pcg ,

Author

Sage Group (IRISA, 2005)


pcg

Scilab Function
Last update : 13/06/2006

pcg - precondioned conjugate gradient

Calling Sequence

[x, flag, err, iter, res] = pcg(A, b [, tol [, maxit [, M [, M2 [, x]]]]])
[x, flag, err, iter, res] = pcg(A, b, key=value,...)

Parameters

  • A : symmetric positive definite full or sparse matrix of size nxn or a function returning A*x for each given x
  • b : right hand side vector (size: nx1)
  • tol : error tolerance (default: 1000*%eps)
  • maxi : maximum number of iterations (default: n)
  • M : preconditioner: full or sparse matrix or function returning M\x (default: none)
  • M2 : preconditioner: full or sparse matrix or function returning M2\x for each x (default: none)
  • x0 : initial guess vector (default: zeros(n,1))
  • x : solution vector
  • flag : 0 if pcg converged to the desired tolerance within maxi iterations, 1 else
  • err : final relative norm of the residual
  • iter : number of iterations performed
  • res : vector of the residual norms

Description

Solves the linear system Ax=b using the conjugate gradient method with or without preconditioning. The preconditionning should be defined by a symmetric positive definite matrix M , or two matrices M1 and M2 such that M=M1*M2 . in the case the function solves inv(M)*A*x = inv(M)*b for x . M , M1 and M2 can be Scilab functions with calling sequence y=Milx(x) which computes the corresponding left division y=Mi\x . The A matrix must be a symmetric positive definite matrix (full or sparse) or a function with calling sequence y=Ax(x) which computes y=A*x

Examples

 //Well conditionned problem
 A=[ 94  0   0   0    0   28  0   0   32  0
     0   59  13  5    0   0   0   10  0   0
     0   13  72  34   2   0   0   0   0   65
     0   5   34  114  0   0   0   0   0   55
     0   0   2   0    70  0   28  32  12  0
     28  0   0   0    0   87  20  0   33  0
     0   0   0   0    28  20  71  39  0   0
     0   10  0   0    32  0   39  46  8   0
     32  0   0   0    12  33  0   8   82  11
     0   0   65  55   0   0   0   0   11  100];

  b=ones(10,1);
  [x, fail, err, iter, res]=pcg(A,b,1d-12,15);
  mprintf("      fail=%d, iter=%d, errrel=%e\n",fail,iter,err)

  //Ill contionned one
 A=[ 894     0   0     0   0   28  0   0   1000  70000
      0      5   13    5   0   0   0   0   0     0
      0      13  72    34  0   0   0   0   0     6500
      0      5   34    1   0   0   0   0   0     55
      0      0   0     0   70  0   28  32  12    0
      28     0   0     0   0   87  20  0   33    0
      0      0   0     0   28  20  71  39  0     0
      0      0   0     0   32  0   39  46  8     0
      1000   0   0     0   12  33  0   8   82    11
      70000  0   6500  55  0   0   0   0   11    100];

  [x, fail, err, iter, res]=pcg(A,b,maxIter=30,tol=1d-12);
  mprintf("      fail=%d, iter=%d, errrel=%e\n",fail,iter,err)

   //sparse matrix
   A=sparse(A);
   [x, fail, err, iter, res]=pcg(A,b,maxIter=30,tol=1d-12);
   mprintf("      fail=%d, iter=%d, errrel=%e\n",fail,iter,err)

   //using a function
   function y=Atimesx(x,A),y=A*x, endfunction

   //A passed by the calling context
   [x, fail, err, iter, res]=pcg(Atimesx,b,maxIter=30,tol=1d-12);
   mprintf("      fail=%d, iter=%d, errrel=%e\n",fail,iter,err)

   // A passed as an argument
   [x, fail, err, iter, res]=pcg(list(Atimesx,A),b,maxIter=30,tol=1d-12);
   mprintf("      fail=%d, iter=%d, errrel=%e\n",fail,iter,err)

See Also

backslash , qmr , gmres ,

Author

Sage Group (IRISA, 2004)


qmr

Scilab Function
Last update : 06/01/2006

qmr - quasi minimal resiqual method with preconditioning

Calling Sequence

[x,flag,err,iter,res] = qmr(A,b,x0,M1,M1p,M2,M2p,maxi,tol)

Parameters

  • A : matrix of size n-by-n or function returning A*x
  • b : right hand side vector
  • x0 : initial guess vector (default: zeros(n,1))
  • M1 : left preconditioner: matrix or function returning M1*x (In the first case, default: eye(n,n))
  • M1p : must only be provided when M1 is a function. In this case M1p is the function which returns M1'*x
  • M2 : right preconditioner: matrix or function returning M2*x (In the first case, default: eye(n,n))
  • M2p : must only be provided when M2 is a function. In this case M2p is the function which returns M2'*x
  • maxi : maximum number of iterations (default: n)
  • tol : error tolerance (default: 1000*%eps)
  • x : solution vector
  • flag : 0 = qmr converged to the desired tolerance within maxi iterations
  • res : residual vector
  • err : final residual norm
  • iter : number of iterations performed

Description

Solves the linear system Ax=b using the Quasi Minimal Residual Method with preconditioning.

See Also

gmres ,

Author

SAGE Group, IRISA 2005


Calcul parallèle avec PVM
AdCommunications - advanced communication toolbox for parallel programming
pvm - communications with other applications using Parallel Virutal Machine
pvm_addhosts - add hosts to the virtual machine.
pvm_barrier - blocks the calling process until all processes in a group have called it.
pvm_bcast - broacasts a message to all members of a group
pvm_bufinfo - Returns information about a message buffer.
pvm_config - sends a message
pvm_delhosts - deletes hosts from the virtual machine.
pvm_error - Prints message describing an error returned by a PVM call
pvm_exit - tells the local pvmd that this process is leaving PVM.
pvm_f772sci - Convert a F77 complex into a complex scalar
pvm_get_timer - Gets the system's notion of the current time.
pvm_getinst - returns the instance number in a group of a PVM process.
pvm_gettid - returns the tid of the process identified by a group name and instance number
pvm_gsize - returns the number of members presently in the named group.
pvm_halt - stops the PVM daemon
pvm_joingroup - enrolls the calling process in a named group.
pvm_kill - Terminates a specified PVM process.
pvm_lvgroup - Unenrolls the calling process from a named group.
pvm_mytid - returns the tid of the calling process.
pvm_parent - tid of the process that spawned the calling process.
pvm_probe - Check if message has arrived.
pvm_recv - receive a message.
pvm_reduce - Performs a reduce operation over members of the specified group
pvm_sci2f77 - Convert complex scalar into F77
pvm_send - immediately sends (or multicast) data.
pvm_set_timer - Sets the system's notion of the current time.
pvm_spawn - Starts new Scilab processes.
pvm_spawn_independent - Starts new PVM processes.
pvm_start - Start the PVM daemon
pvm_tasks - information about the tasks running on the virtual machine.
pvm_tidtohost - returns the host of the specified PVM process.
pvmd3 - PVM daemon


pvmd3

pvm daemon
Last update : 12/01/2004

pvmd3 - PVM daemon

Description

pvmd3 is a daemon process which coordinates hosts in a virtual machine. One pvmd must run on each host in the group. They provide the communication and process control functions needed by the user's PVM processes. The daemon can be started manually with a host file argument that will automatically start the remote pvmds. The local and remote pvmds can also be started from the PVM console program pvm.

The name of the daemon executable is pvmd3. It is usually started by a shell script, $PVM_ROOT/lib/pvmd.

Local daemon may also be started by the scilab instruction pvm_start() and remote daemons may also be started by the scilab function pvm_addhosts

Options

The following options may be specified on the command line when starting the master pvmd or PVM console:

  • - dmask Set pvmd debug mask. Used to debug the pvmd or libpvm (not intended to be used to debug application programs). Mask is a hexadecimal number which is the sum of the following bits: Bit Information
  • 1 Packet routing
  • 2 Message routing and entry points
  • 4 Task management
  • 8 Slave pvmd startup
  • 10 Host table updates
  • 20 Select loop (below packet layer)
  • 40 IP network
  • 80 Multiprocessor port debugging
  • 100 Resource manager interface
  • 200 Application (messages with no destination, etc.)
  • -nname Specify an alternate hostname for the master pvmd to use. Useful when gethostname() returns a name not assigned to any network interface.

    • The following options are used by the master pvmd when starting slaves and are only of interest to someone writing a hoster. Don't just go using them, now.

  • -s Start pvmd in slave mode. Hostfile cannot be used, five additional parameters must be supplied: master pvmd index, master IP, master MTU, slave pvmd index, and slave IP.
  • -S Same as -s, but slave pvmd doesn't wait for its stdin to be closed after printing its parameters. Used for manual startup.
  • -f Slave doesn't fork after configuration (useful if the slave is to be controlled or monitored by some process).

    • Lines beginning with a splat ( # ), optionally preceded by whitespace, are ignored.

    A simple host file might look like:

# my first host file
thud
fred
wilma
barney
betty

    This specifies the names of five hosts to be configured in the virtual machine. The master pvmd for a group is started by hand on the localhost, and it starts slaves on each of the remaining hosts using the rsh or rexec command. The master host may appear on any line of the hostfile, but must have an entry. The simple format above works fine if you have the same login name on all five machines and the name of the master host in your .rhosts files on the other four. There are several host file options available:

  • lo=NAME Specifies an alternate login name (NAME) to use.
  • so=pw This is necessary when the remote host cannot trust the master. Causes the master pvmd to prompt for a password for the remote host in the tty of the pvmd (note you can't start the master using the console or background it when using this option) you will see: Password (honk.cs.utk.edu:manchek): you should type your password for the remote host. The startup will then continue as normal.
  • dx=FILE Specifies the path of the pvmd executable. FILE may be a simple filename, an absolute pathname, or a path relative to the user's home directory on the remote host. This is mainly useful to aid in debugging new versions of PVM, but may have other uses.
  • ep=PATH Specifies a path for the pvmd to search for executable program components when spawning a new process. The path may have multiple elements, separated by colons ( : ).
  • wd=PATH Specifies a working directory in which all spawned tasks on this host will execute.
  • sp=VALUE Specifies the relative computational speed of this host compared to other hosts in the configuration. VALUE is an integer in the range [1 - 1000000]
  • bx=PATH Specifies the debugger program path. Note: the environment variable PVM_DEBUGGER can also be set.
  • so=ms Rarely used. Causes the master pvmd to request user to manually perform the startup of a pvmd on a slave host when rsh and rexec network services are disabled but IP connectivity exists. See section "MANUAL STARTUP".

    • A dollar sign ( $ ) in an option introduces a variable name, for example $PVM_ARCH. Names are expanded from environment variables by each pvmd. Each of the flags above has a default value. These are:

  • lo The loginname on the master host.
  • so Nothing
  • dx $PVM_ROOT/lib/pvmd (or environment variable PVM_DPATH)
  • ep pvm3/bin/$PVM_ARCH:$PVM_ROOT/bin/$PVM_ARCH
  • wd $HOME
  • sp 1000
  • bx $PVM_ROOT/lib/debugger

    • You can change these by adding a line with a star ( * ) in the first field followed by the options, for example:

  • * lo=afriend so=pw This sets new default values for `lo' and `so' for the remainder of the host file, or until the next `*' line. Options set on the last `*' line also apply to hosts added dynamically using pvm_addhosts().

    • Host options can be set without starting the hosts automatically. Information on host file lines beginning with `&' is stored, but the hosts are not started until added using pvm_addhosts().

    Example hostfile:

# hostfile for testing on various platforms fonebone refuge
# installed in /usr/local/here
sigi.cs
     dx=/usr/local/pvm3/lib/pvmd # borrowed accts, "guest", don't trust fonebone
  • * lo=guest so=pw sn666.jrandom.com cubie.misc.edu # really painful one, must start it by hand and share a homedir & igor.firewall.com lo=guest2 so=ms ep=bob/pvm3/bin/$PVM_ARCH

    • Manual STARTUP

    When adding a host with this option set you will see on the tty of the pvmd:

*** Manual startup ***

    Login to "honk" and type:

$PVM_ROOT/lib/pvmd -S -d0 -nhonk 1 80a9ca95:0cb6 4096 2 80a95c43:0000 Type response:

    after typing the given command on host honk, you should see a line like:

ddpro<2312> arch<ALPHA> ip<80a95c43:0a8e> mtu<4096>

    type this line on the tty of the master pvmd. You should then see:

Thanks

    and the two pvmds should be able to communicate. Note you can't start the master using the console or background it when using this option.

    Stopping PVMD3

    The preferred method of stopping all the pvmds is to give the halt command in the PVM console. This kills all pvm tasks, all the remote daemons, the local daemon, and finally the console itself. If the master pvmd is killed manually it should be sent a SIGTERM signal to allow it to kill the remote pvmds and clean up various files. The pvmd can be killed in a manner that leaves the file /tmp/pvmd.uid behind on one or more hosts. Uid is the numeric user ID (from /etc/passwd) of the user. This will prevent PVM from restarting on that host. Deletion of this file will fix this problem:

rm `( grep $user /etc/passwd || ypmatch $user passwd ) | \
 awk -F: `{print "/tmp/pvmd."$3; exit}'`


pvm_addhosts

Scilab function
Last update : 13/07/2005

pvm_addhosts - add hosts to the virtual machine.

Calling Sequence

[infos] = pvm_addhosts(hosts)

Parameters

  • hosts : row of strings, naming the hosts to be added.
  • infos : row of integer, corresponding to the status for each host.

Description

pvm_addhosts adds the computers named in the row matrix hosts to the configuration of computers making up the virtual machine. The names should have the same syntax as lines of a pvmd hostfile: i.e a hostname followed by options of the form xx=y (see man page for pvmd3).

The row matrix info will contain for each added host its status. Values less than zero indicate an error, while positive values are TIDs of the new hosts.

The status of hosts can be requested by the application using pvm_config . If a host fails it will be automatically deleted from the configuration. Using pvm_addhosts a replacement host can be added by the application, however it is the responsibility of the application developer to make his application tolerant of host failure. Another use of this feature would be to add more hosts as they become available, for example on a weekend, or if the application dynamically determines it could use more computational power.

See Also

pvm_delhosts , pvm_config ,


pvm_barrier

Scilab function
Last update : 13/07/2005

pvm_barrier - blocks the calling process until all processes in a group have called it.

Calling Sequence

[info] = pvm_barrier(group,count)

Parameters

  • type : string, name of an existing group.
  • count : integer, specifying the number of group members that must call pvm_barrier before they are all released.
  • info : integer, status code returned by the routine.

Description

pvm_barrier blocks the calling process until count members of the group have called pvm_barrier . The count argument is required because processes could be joining the given group after other processes have called pvm_barrier . Thus PVM doesn't know how many group members to wait for at any given instant. Although count can be set less, it is typically the total number of members of the group. So the logical function of the pvm_barrier call is to provide a group synchronization. During any given barrier call all participating group members must call barrier with the same count value. Once a given barrier has been successfully passed, pvm_barrier can be called again by the same group using the same group name.

The returned value info will be zero if pvm_barrier is successful and will be will be < 0 if some error occurs.

See Also

pvm_joingroup ,


pvm_bcast

Scilab function
Last update : 13/07/2005

pvm_bcast - broacasts a message to all members of a group

Calling Sequence

[info] = pvm_bcast(group, buff, msgtag)

Parameters

  • group : string, string group name of an existing group.
  • buff : data to be send (any Scilab object).
  • msgtag : integer, message tag supplied by the user.
  • info : integer,

Description

pvm_bcast broadcasts a message to all the members of the group named group .

In PVM 3.2 and later the broadcast message is not sent back to the sender. Any PVM task can call pvm_bcast() , it need not be a member of the group. The content of the message can be distinguished by its tag msgtag

The returned value info will be zero if pvm_bcast is successful and will be will be < 0 if some error occurs.

pvm_bcast is asynchronous. Computation on the sending processor resumes as soon as the message is safely on its way to the receiving processors. This is in contrast to synchronous communication, during which computation on the sending processor halts until a matching receive is executed by all the receiving processors.

pvm_bcast first determines the tids of the group members by checking a group data base. A multicast is performed to these tids. If the group is changed during a broadcast the change will not be reflected in the broadcast. Multicasting is not supported by most multiprocessor vendors. Typically their native calls only support broadcasting to all the user's processes on a multiprocessor. Because of this omission, pvm_bcast may not be an efficient communication method on some multiprocessors.

See Also

pvm_joingroup ,


pvm_bufinfo

Scilab function
Last update : 12/01/2004

pvm_bufinfo - Returns information about a message buffer.

Calling Sequence

[bytes, msgtag, tid, info] = pvm_bufinfo(bufid)

Parameters

  • bufid : integer, specifying a particular message buffer identifier.
  • bytes : integer, size of the message in bytes (not very useful inside scilab).
  • msgtag : integer, label of the message. Useful when the message was received with a wildcard msgtag.
  • tid : integer, task ID of the source of the message.
  • info : integer, status code returned by the routine. Values less than zero indicate an error.

Description

pvm_bufinfo returns information about the requested message buffer. Typically it is used to determine facts about the last received message such as its size or source. pvm_bufinfo is especially useful when an application is able to receive any incoming message, and the action taken depends on the source tid and the msgtag associated with the message that comes in first.

The returned value info will be zero if pvm_bufinfo is successful and will be will be < 0 if some error occurs.

See Also

pvm_recv ,


pvm_config

Scilab function
Last update : 28/06/2005

pvm_config - sends a message

Calling Sequence

res = pvm_config()

Parameters

  • res list of 7 elements such that:
    • (1) : integer returning the number of hosts (pvmds) in the virtual machine.
    • (2) : integer returning the number of different data formats being used.
    • (3) : integer returning pvmd task ID for host.
    • (4) : character string returning name of host.
    • (5) : character string returning architecture name of host
    • (6) : integer returning relative speed of host. Default value is 1000.
    • (7) : integer status code returned by the routine.

Description

pvm_config returns information about the present virtual machine. The information returned is similar to that available from the console command.

The pvm_config function returns information about the entire virtual machine in one call.

The returned value res(7) will be zero if the call is successful and will be will be < 0 if some error occurs.

Examples

if pvm_start()==0 then
    res = pvm_config()
    pvm_halt()
end

See Also

pvm_start , pvm_tasks ,


pvm_delhosts

Scilab function
Last update : 13/07/2005

pvm_delhosts - deletes hosts from the virtual machine.

Calling Sequence

infos = pvm_delhosts(hosts)

Parameters

  • hosts : row of strings, containing the names of the machines to be deleted.
  • infos : row of integers, contains the status code returned by the routine for the individual hosts.

Description

pvm_delhosts deletes the computers named in hosts from the existing configuration of computers making up the virtual machine. All PVM processes and the pvmd running on these computers are killed as the computer is deleted. The array info can be checked to determine the status of each host. Values less than zero indicate an error, while zero values indicate a success.

If a host fails, the PVM system will continue to work and will automatically delete the failing host from the virtual machine. It is the responsibility of the application developer to make his application tolerant of host failure.

See Also

pvm_addhosts ,


pvm_error

Scilab function
Last update : 13/07/2005

pvm_error - Prints message describing an error returned by a PVM call

Calling Sequence

[errmsg] = pvm_error(err)

Parameters

  • err : integer, error code returned by a pvm function.
  • errmsg : string, the error message corresponding to the error code err .

Description

pvm_error returns the error message corresponding to an PVM error code returned by a PVM call.


pvm_exit

Scilab function
Last update : 12/01/2004

pvm_exit - tells the local pvmd that this process is leaving PVM.

Calling Sequence

[info] = pvm_exit()

Parameters

  • info : integer

Description

pvm_exit tells the local pvmd that this process is leaving PVM. This routine does not kill the process, which can continue to perform tasks just like any other serial process.

pvm_exit should be called by all PVM processes before they stop or exit for good. It must be called by processes that were not started with pvm_spawn .

Examples

pvm_exit()

See Also

pvm ,


pvm_f772sci

Scilab function
Last update : 12/01/2004

pvm_f772sci - Convert a F77 complex into a complex scalar

Calling Sequence

[res] = pvm_f772sci(var)

Parameters

  • var : local scilab variable. On return, the variable will be overwritten with the result of conversion operation.
  • res : if the parameter var is not a variable, the result of the conversion is returned in res.

Description

pvm_f772sci converts all the complex matrices contained in the representation of a scilab variable form a f77 coding to the Scilab complex matrix coding scheme. This can be useful if Scilab is receiving data from a non scilab application (directly from a C or F77 program for example).

Note that the parameter is passed by adress. It means that if the parameter is a variable, this variable will be overwritten with the result of conversion operation. On the other case, if the parameter is not a variable, the result will be returned in res.

Examples

a = [1+%i, 2+2*%i,3+3*%i];
pvm_f772sci(a)
if norm(a - [1.+2* %i,3.+%i, 2. + 3. *%i ]) >10*%eps then pause;end

See Also

pvm_sci2f77 ,


pvm_getinst

Scilab function
Last update : 13/07/2005

pvm_getinst - returns the instance number in a group of a PVM process.

Calling Sequence

[inum] = pvm_getinst(group, tid)

Parameters

  • group : string, string group name of an existing group.
  • tid : integer, task identifier of a PVM process.
  • inum : integer, instance number returned by the routine.

Description

pvm_getinst takes a group name group and a PVM task identifier tid and returns the unique instance number that corresponds to the input. It can be called by any task whether in the group or not.

The returned value inum will be >= 0 if the call is successful and will be will be < 0 if some error occurs.

See Also

pvm_joingroup , pvm_gettid ,


pvm_gettid

Scilab function
Last update : 13/07/2005

pvm_gettid - returns the tid of the process identified by a group name and instance number

Calling Sequence

[tid] = pvm_gettid(group, inum)

Parameters

  • group : string, string that contains the name of an existing group.
  • inum : string, instance number of the process in the group.
  • tid : integer

Description

pvm_gettid returns the tid of the PVM process identified by the group name group and the instance number inum

The returned value tid will be >= 0 if the call is successful and will be will be < 0 if some error occurs.

See Also

pvm_joingroup , pvm_getinst ,


pvm_get_timer

Scilab function
Last update : 12/01/2004

pvm_get_timer - Gets the system's notion of the current time.

Calling Sequence

[time] = pvm_get_timer()

Parameters

  • time : scalar

Description

pvm_get_timer returns the time elapsed since the last call of pvm_get_timer or the last call of pvm_set_timer . The time is expressed in elapsed microseconds. The resolution of the system clock is hardware dependent; the time may be updated continuously or in clock ticks.

The returned value time will be >= 0 if the call is successful and will be will be -1 if some error occurs.

Examples

B = rand(100,100);
A = rand(100,100);
pvm_set_timer();C=A*B;t=pvm_get_timer()

See Also

pvm_set_timer ,


pvm_gsize

Scilab function
Last update : 13/07/2005

pvm_gsize - returns the number of members presently in the named group.

Calling Sequence

[nb] = pvm_gsize(group)

Parameters

  • group : string, string group name of an existing group.
  • nb : integer, returning the number of members presently in the group.

Description

pvm_gsize returns the size of the group named group

The returned value nb will be >= 0 if the call is successful and will be will be < 0 if some error occurs.

Since groups can change dynamically in PVM 3.0, this routine can only guarantee to return the instantaneous size of a given group.

See Also

pvm_joingroup ,


pvm_halt

Scilab function
Last update : 12/01/2004

pvm_halt - stops the PVM daemon

Calling Sequence

[info] = pvm_halt()

Parameters

  • info : integer, status code returned by the routine. Values less than zero indicate an error.

Description

pvm_halt kills all PVM tasks, all the remote daemons, and the local daemon. If the master pvmd is killed manually it should be sent a SIGTERM signal to allow it to kill the remote pvmds and clean up various files.

The pvmd can be killed in a manner that leaves the file /tmp/pvmd.uid behind on one or more hosts (the uid suffix is the numeric user ID from /etc/passwd ) of the user. This will prevent PVM from restarting on that host. Deletion of this file will fix this problem and it can be done as follows: rm `( grep $user /etc/passwd || ypmatch $user passwd ) | awk -F: '{print "/tmp/pvmd.";$3;exit}'`

For example:

-->pvm_halt()
 ans  =

    0.

-->pvm_halt()
 ans  =

  - 14.

Error -14 means: pvm_halt(): Can't contact local daemon

See Also

pvm_start , pvm_addhosts , pvm_config ,


pvm_joingroup

Scilab function
Last update : 13/07/2005

pvm_joingroup - enrolls the calling process in a named group.

Calling Sequence

[inum] = pvm_joingroup(group)

Parameters

  • group : string, string group name of an existing group.
  • inum : integer, instance number returned by the routine.

Description

pvm_joingroup enrolls the calling task in the group named group and returns the instance number of this task in this group.

The returned value will be >= 0 if the call is successful and will be will be < 0 if some error occurs.

Instance numbers start at 0 and count up. When using groups a (group, inum) pair uniquely identifies a PVM process. This is consistent with the PVM 2.4 naming schemes. If a task leaves a group by calling pvm_lvgroup and later rejoins the same group, the task is not guaranteed to get the same instance number. PVM attempts to reuse old instance numbers, so when a task joins a group it will get the lowest available instance number. A task can be a member of multiple groups simultaneously.

See Also

pvm_lvgroup ,


pvm_kill

Scilab function
Last update : 13/07/2005

pvm_kill - Terminates a specified PVM process.

Calling Sequence

[infos] = pvm_kill(tids)

Parameters

  • tids : row of integer, task identifier of the PVM process to be killed (not yourself).
  • infos : row of integer, status code returned by the routine. Values less than zero indicate an error.

Description

pvm_kill sends a terminate ( SIGTERM ) signal to the PVM process identified by tids .

In the case of multiprocessors the terminate signal is replaced with a host dependent method for killing a process.

The array infos can be checked to determine the status for each process. Values less than zero indicate an error, while zero values indicate a success.

pvm_kill is not designed to kill the calling process. To kill yourself in C call pvm_exit() followed by quit() .

See Also

pvm_exit ,


pvm_lvgroup

Scilab function
Last update : 13/07/2005

pvm_lvgroup - Unenrolls the calling process from a named group.

Calling Sequence

[info] = pvm_lvgroup(group)

Parameters

  • group : string, group name of an existing group.
  • info : integer, status code returned by the routine.

Description

pvm_lvgroup unenrolls the calling process from the group named group

The returned value will be >= 0 if the call is successful and will be will be < 0 if some error occurs.

If a process leaves a group by calling either pvm_lvgroup or pvm_exit, and later rejoins the same group, the process may be assigned a new instance number. Old instance numbers are reassigned to processes calling pvm_joingroup.

See Also

pvm_joingroup ,


pvm_mytid

Scilab function
Last update : 13/07/2005

pvm_mytid - returns the tid of the calling process.

Calling Sequence

[tid] = pvm_mytid()

Parameters

  • tid : integer, the task identifier of the calling PVM process. Values less than zero indicate an error.

Description

pvm_mytid enrolls this process into PVM on its first call. It also generates a unique tid

if this process was not created by pvm_spawn . pvm_mytid returns the tid of the calling process and can be called multiple times in an application.

Any PVM system call (not just pvm_mytid) will enroll a task in PVM if the task is not enrolled before the call.

The tid is a 32 bit positive integer created by the local pvmd. The 32 bits are divided into fields that encode various information about this process such as its location in the virtual machine (i.e. local pvmd address), the CPU number in the case where the process is on a multiprocessor, and a process ID field. This information is used by PVM and is not expected to be used by applications. Applications should not attempt to predict or interpret the tid with the exception of calling tidtohost()

If PVM has not been started before an application calls pvm_mytid , the returned value will be will be < 0.

See Also

pvm_tidtohost , pvm_parent ,


pvm_parent

Scilab function
Last update : 13/07/2005

pvm_parent - tid of the process that spawned the calling process.

Calling Sequence

tid = pvm_parrent()

Parameters

  • tid : integer, the task identifier of the parent of the calling process.

Description

pvm_parent returns the tid of the process that spawned the calling process. If the calling process was not created with pvm_spawn , then tid is set to PvmNoParent=-23

See Also

pvm_spawn ,


pvm_probe

Scilab function
Last update : 12/01/2004

pvm_probe - Check if message has arrived.

Calling Sequence

[buffid] = pvm_probe(tid, msgtag)

Parameters

  • tid : integer, task identifier of sending process supplied by the user.
  • msgtag : integer, message tag supplied by the user. msgtag should be >= 0.
  • buffid : integer, returning the value of the new active receive buffer identifier. Values less than zero indicate an error.

Description

pvm_probe checks to see if a message with label msgtag has arrived from tid . If a matching message has arrived pvm_probe returns a buffer identifier in bufid . This bufid can be used in a pvm_bufinfo call to determine infor- mation about the message such as its source and length.

If the requested message has not arrived, then pvm_probe returns with a 0 in bufid. If some error occurs bufid will be < 0.

A -1 in msgtag or tid matches anything. This allows the user the following options. If tid = -1 and msgtag is defined by the user, then pvm_probe will accept a message from any process which has a matching msgtag. If msgtag = -1 and tid is defined by the user, then pvm_probe will accept any message that is sent from process tid. If tid = -1 and msgtag = -1, then pvm_probe will accept any message from any process.

pvm_probe can be called multiple times to check if a given message has arrived yet. After the message has arrived, pvm_recv must be called before the message can be unpacked into the user's memory using the unpack routines.

For example

arrived = pvm_probe( tid, msgtag );
if (arrived >= 0) then [bytes, msgtag, tid, info] = pvm_info(arrived); end

See Also

pvm_recv ,


pvm_recv

Scilab function
Last update : 28/06/2005

pvm_recv - receive a message.

Calling Sequence

[buff, info, msgtid, tag] = pvm_recv(tid, msgtag)

Parameters

  • tid : integer, task identifier of sending process supplied by the user.
  • msgtag : integer, message tag supplied by the user. msgtag should be >= 0.
  • buff : scilab variable, where the received message will be stored.
  • info : integer, status code returned by the routine. Values less than zero indicate an error.
  • msgtid : integer, returning the source of the message. Useful when the message was received with a wildcard tid.
  • tag : integer, returning the message label. Useful when the message was received with a wildcard msgtag.

Description

pvm_recv blocks the process until a message with label msgtag ( -1 can be used to match all message tags) has arrived from tid ( -1 can be used to match all tids). pvm_recv returns the message in buff .

If tid=-1 and msgtag is defined by the user, then pvm_recv will accept a message from any process which has a matching msgtag .

If msgtag = -1 and tid is defined by the user, then pvm_recv will accept any message that is sent from process tid . If tid=-1 and msgtag = -1 then pvm_recv will accept any message from any process.

When wildcard are used, the application is able to receive any incoming message. If the action taken depends on the source tid and the msgtag associated with the message that comes in first, the information given by msgtid and tag can be very usefull.

The PVM model guarantees the following about message order. If task 1 sends message A to task 2, then task 1 sends message B to task 2, message A will arrive at task 2 before message B. Moreover, if both messages arrive before task 2 does a receive, then a wildcard receive will always return message A.

info will be the status code returned by the routine. If some error occurs then it will be < 0.

pvm_recv is blocking which means the routine waits until a message matching the user specified tid and msgtag values arrives at the local pvmd. If the message has already arrived then pvm_recv returns immediately with the message.

Once pvm_recv returns, the data in the message can be unpacked into the user's memory using the unpack routines.

See Also

pvm_send , pvm_bcast ,


pvm_reduce

Scilab function
Last update : 13/07/2005

pvm_reduce - Performs a reduce operation over members of the specified group

Calling Sequence

[buff, info] = pvm_reduce(func, buff, msgtag, group, rootginst)

Parameters

  • func : string, defines the operation performed on the global data. Should be : Max, Min, Sum or Pro.
  • buff : scalar, local scilab variable. On return, the data array on the root will be overwritten with the result of the reduce operation over the group.
  • msgtag : integer, message tag supplied by the user. msgtag should be >= 0. It allows the user's program to distinguish between different kinds of messages.
  • group : string, group name of an existing group.
  • rootginst : integer, instance number of group member who gets the result.
  • info : integer, status code returned by the routine. Values less than zero indicate an error.

Description

pvm_reduce performs global operations such as max, min, sum or product over all the tasks in a group. All group members call pvm_reduce with their local data, and the result of the reduction operation appears on the user specified root task root. The root task is identified by its instance number in the group.

Max and Min are implemented for scalar datatypes (double, complex). For complex values the minimum [maximum] is that complex pair with the minimum [maximum] modulus. Sum and Product are implemented for scalar datatypes.

Note: pvm_reduce does not block. If a task calls pvm_reduce and then leaves the group before the root has called pvm_reduce an error may occur.

See Also

pvm_bcast , pvm_barrier , pvm_send , pvm_getinst , pvm_gsize , pvm_joingroup , pvm_lvgroup ,


pvm_sci2f77

Scilab function
Last update : 12/01/2004

pvm_sci2f77 - Convert complex scalar into F77

Calling Sequence

[res] = pvm_sci2f77(var)

Parameters

  • var : local scilab variable. On return, the variable will be overwritten with the result of conversion operation.
  • res : if the parameter var is not a variable, the result of the conversion is returned in res.

Description

pvm_sci2f77 converts all the complex of a scilab variable (array, list...) in the F77 representation. MAy be useful if an application is sendind data to a non scilab application (direcvtly to a C or F77 program for example).

Note that the parameter is passed by adress. It means that if the parameter is a variable, this variable will be overwritten with the result of conversion operation. On the other case, if the parameter is not a variable, the result will be returned in res.

Examples

a = [1+%i, 2+2*%i,3+3*%i];
pvm_sci2f77(a)
if norm(a - [1.+2* %i,1+3*%i, 2. + 3. *%i ]) >10*%eps then pause;end

See Also

pvm_f772sci ,


pvm_send

Scilab function
Last update : 13/07/2005

pvm_send - immediately sends (or multicast) data.

Calling Sequence

[info] = pvm_send(tids,buff,msgtag)

Parameters

  • tids : row of integers, contains the task IDs of the tasks to be sent to.
  • buff : scilab variable.
  • msgtag : integer, message tag supplied by the user. msgtag should be >= 0. It allows the user's program to distinguish between different kinds of messages .
  • info : integer, status code returned by the routine. Values less than zero indicate an error.

Description

pvm_send sends (or multicasts) a message to the PVM process identified in the tids array. Note that the message is not sent to the caller even if listed in the array of tids. msgtag is used to label the content of the message.

The returned value will be >= 0 if the call is successful and will be will be < 0 if some error occurs.

The pvm_send routine is asynchronous. Computation on the sending processor resumes as soon as the message is safely on its way to the receiving processor. This is in contrast to synchronous communication, during which computation on the sending processor halts until the matching receive is executed by the receiving processor.

If a multicast is performed, pvm_send first determines which other pvmds contain the specified tasks. Then passes the message to these pvmds which in turn distribute the message to their local tasks without further network traffic.

The PVM model guarantees the following about message order. If task 1 sends message A to task 2, then task 1 sends message B to task 2, message A will arrive at task 2 before message B. Moreover, if both messages arrive before task 2 does a receive, then a wildcard receive will always return message A.

Terminating a PVM task immediately after sending a message or messages from it may result in those messages being lost. To be sure, always call pvm_exit() before stopping.

See Also

pvm_recv , pvm_bcast ,


pvm_set_timer

Scilab function
Last update : 12/01/2004

pvm_set_timer - Sets the system's notion of the current time.

Calling Sequence

[info] = pvm_set_timer()

Parameters

  • info : scalar

Description

pvm_set_timer initialized the timer.

The returned value will be 0 if the call is successful and will be will be -1 if some error occurs.

Examples

pvm_set_timer()

See Also

pvm_get_timer ,


pvm_spawn_independent

Scilab function
Last update : 13/07/2005

pvm_spawn_independent - Starts new PVM processes.

Calling Sequence

[tids, numt] = pvm_spawn_independent(task, ntask, [where])

Parameters

  • task: string, which is the executable file name of the PVM process to be started. The executable must already reside on the host on which it is to be started. The name may be a file in the PVM search path or an absolute path. The default PVM search path is $HOME/pvm3/bin/$PVM_ARCH/ .
  • ntask: integer, specifying the number of copies of the executable file to start.
  • where: string (optional), can be a host name such as ``tequila.ens-lyon.fr'' or a PVM architecture class such as ``SUN4''.
  • numt: integer, the actual number of tasks started. Values less than zero indicate a system error.
  • tids row of integers, array of the tids of the PVM processes started by this pvm_spawn_independent call.

Description

pvm_spawn_independent starts ntask copies of the executable named task .

On systems that support environment variables, pvm_spawn_independent passes selected variables from parent environment to children tasks. If set, the envar PVM_EXPORT is passed. If PVM_EXPORT contains other names (separated by ':') they will be passed too. This is useful for e.g.:

 setenv DISPLAY myworkstation:0.0
 setenv MYSTERYVAR 13
 setenv PVM_EXPORT DISPLAY:MYSTERYVAR

The hosts on which the PVM processes are started are determined by the where arguments. On return the array tids contains the PVM task identifiers for each process started. If pvm_spawn_independent starts one or more tasks, numt will be the actual number of tasks started. If a system error occurs then numt will be < 0. If numt is les than ntask then some executables have failed to start. The last locations in the tids array will contain error codes (see below for meaning). Note that the first tids in the array are always valid.

When the argument where is omitted an heuristic (round-robin assignment) is used to distribute the ntask processes across the virtual machine.

In the special case where a multiprocessor is specified by where . pvm_spawn_independent will start all copies on this single machine using the vendor's underlying routines.

See Also

pvm , pvm_spawn ,


pvm_spawn

Scilab function
Last update : 13/07/2005

pvm_spawn - Starts new Scilab processes.

Calling Sequence

[tids, numt] = pvm_spawn(task, ntask, [nw], [where])

Parameters

  • task : string, which is the file name of the scilab script (see exec) to be started. The Scilab script must already reside on the host on which it is to be started. The name must an absolute path.
  • ntask : integer, specifying the number of copies of the scilab script to start.
  • win : string (optional). If win is equal to ``nw'' the Scilab process will be spawned in background with out any window coming up.
  • where : string (optional), can be a host name such as ``tequila.ens-lyon.fr'' or a PVM architecture class such as ``SUN4''.
  • numt : integer, the actual number of tasks started. Values less than zero indicate a system error.
  • tids row of integers, array of the tids of the PVM processes started by this pvm_spawn call.

Description

pvm_spawn starts ntask copies of the scilab script task .

On systems that support environment, pvm_spawn passes selected variables from parent environment to children tasks. If set, the envar PVM_EXPORT is passed. If PVM_EXPORT contains other names (separated by ':') they will be passed too. This is useful for e.g.:

 setenv DISPLAY myworkstation:0.0
 setenv MYSTERYVAR 13
 setenv PVM_EXPORT DISPLAY:MYSTERYVAR

The hosts on which the PVM processes are started are determined by the where arguments. On return the array tids contains the PVM task identifiers for each process started.

If pvm_spawn starts one or more tasks, numt will be the actual number of tasks started. If a system error occurs then numt will be < 0.

If numt is less than ntask then some executables have failed to start and the user should check the last locations in the tids array which will contain error codes (see below for meaning). The first numt tids in the array are always valid.

When the argument where is omitted an heuristic (round-robin assignment) is used to distribute the ntask processes across the virtual machine.

In the special case where a multiprocessor is specified by where pvm_spawn will start all copies on this single machine using the vendor's underlying routines.

See Also

pvm , pvm_spawn_independent ,


pvm_start

Scilab function
Last update : 12/01/2004

pvm_start - Start the PVM daemon

Calling Sequence

[info] = pvm_start(["hostfile"])

Parameters

  • hostfile : name of the hostfile describing the configuration for each host of the virtual machine.
  • info : integer, status code returned by the routine. Values less than zero indicate an error.

Description

pvm_start starts the Pvmd3 daemon process which coordinates unix hosts in a virtual machine. One pvmd3 must run on each host component of the virtual machine. They provide the communication and process control functions needed by the user's PVM processes. The local and remote pvmds can also be started from the PVM console program pvm.

The optional parameter is the name of a host file. See pvmd3 for more details on the host file format. If no argument is given to pvm_start , but the variable PVM_ROOT is set, scilab will try to load the file $HOME/.pvmd.conf. If this file does not exist, or the variable PVM_ROOT is not set, scilab will try to load the default file $SCI/.pvmd.conf. In all other cases, scilab will supposed that PVM and scilab are in standard place on your net.

Note that, to be able to start a PVM daemon, scilex must know the place to find both scilex and pvmd. Normally, scilex will start a new PVM daemon by using rsh. See the help on pvmd3 and pvm for more detail on how to start/stop pvm.

For example:

pvm_start()
 ans  =

    0.
-->pvm_start()
 ans  =

  - 28.

Error -28 means: pvm_start_pvmd(): Duplicate host

See Also

pvmd3 , pvm_halt , pvm_addhosts , pvm_config ,


pvm_tasks

Scilab function
Last update : 12/01/2004

pvm_tasks - information about the tasks running on the virtual machine.

Calling Sequence

res = pvm_tasks([where])

Parameters

  • where : (optional) integer, specifying what tasks to return information about. The options are:

 0(default) for all the tasks on the virtual machine
 pvmd tid for all tasks on a given host
   tid  for a specific task
  • res : list of 7 elements such that:
    • res(1) : integer returning task ID of one task
    • res(2) : integer returning parent task ID
    • res(3) : integer returning pvmd task ID of host task is on
    • res(4) : integer returning status of task
    • res(5) : string returning the name of spawned task. Manually started tasks return blank.
    • res(6) : integer returning the number of tasks being reported on.
    • res(7) : integer status code returned by the routine.

Description

pvm_tasks returns information about tasks presently running on the virtual machine. The information returned is the same as that available from the console command

The pvm_tasks function returns information about the entire virtual machine in one call.

If pvm_tasks is successful,

will be 0. If some error occurs then

will be < 0.

for example:

-->res = pvm_tasks()
 res  =

       res(1)

!   262148.    262151.    262152. !

       res(2)

!   262147.    0.    262151. !

       res(3)

!   262144.    262144.    262144. !

       res(4)

!   6.    4.    6. !

       res(5)

!pvmgs    /home/ubeda/SCILAB/scilab-2.4/bin/scilex  !

       res(6)

    3.

       res(7)

    0.

See Also

pvm_config , pvm_tidtohost ,


pvm_tidtohost

Scilab function
Last update : 13/07/2005

pvm_tidtohost - returns the host of the specified PVM process.

Calling Sequence

[dtid] = pvm_tidtohost(tid)

Parameters

  • tid : integer, task identifier of the PVM process in question.
  • dtid : integer, the tid of the host's pvmd3 or a negative value if an error.

Description

pvm_tidtohost returns the host id on which the process identified by tid is running.

The returned value dtid will be >= 0 if the call is successful and will be will be < 0 if some error occurs.

See Also

pvm_config , pvm_tasks ,


pvm

Scilab description
Last update : 12/01/2004

pvm - communications with other applications using Parallel Virutal Machine

Description

is a software system that enables a collection of heterogeneous computers to be used as a coherent and flexible concurrent computational resource.

The individual computers may be shared- or local-memory multiprocessors, vector supercomputers, specialized graphics engines, or scalar workstations, that may be interconnected by a variety of networks, such as ethernet, FDDI.

Daemon programs ( pvmd3 ) provide communication and process control between computers (see PVM manpage and manual for more details).

Most important functions of the PVM communication library are included in Scilab.

Warning

PVM must be installed in your envriromnent before using it in Scilab. PVM scilab have been developped using the version 3.3.7 of the PVM library.

See Also

pvm_barrier , pvm_mytid , pvm_bcast , pvm_parent , pvm_config , pvm_delhosts , pvm_recv , pvm_exit , pvm_send , pvm_getinst , pvm_spawn , pvm_gettid , pvm_spawn_independent , pvm_gsize , pvm_tasks , pvm_joingroup , pvm_tidtohost , pvm_kill , pvm_lvgroup , pvm_start , pvm_halt ,

Author

PVM have been developped by A. L. Beguelin, J. J. Dongarra, G. A. Geist, W. C. Jiang, R. J. Manchek, B. K. Moore, V. S. Sunderam (see http://www.netlib.org/pvm3)


AdCommunications

Scilab description
Last update : 05/08/2005

AdCommunications - advanced communication toolbox for parallel programming

Description

This the beta version of the Advanced Communications Toolbox (ACT).

This toolbox is based on existing libraries, such as

PVM - Parallel Vitual Machine

PBLAS - Message Passing Library dedicated to Matrix

ScaLapack - Parallel linear algebra Library

ACT manage remote executions of softwares and allow efficient exchanges of messages between those softwares. It offers the possibility to exploit numerous machines on a network, as a virtual computer, by creating a distributed group of independent softwares.


Interface TCL/Tk
ScilabEval - tcl instruction : Evaluate a string with scilab interpreter
TCL_CreateSlave - Create a TCL slave interpreter
TCL_DeleteInterp - delete TCL interpreter
TCL_ExistInterp - Return %T if a tcl slave interperter exists
TCL_ExistVar - Return %T if a tcl variable exists
TCL_GetVar - Get a tcl/tk variable value
TCL_GetVersion - get the version of the TCL/TK library at runtime.
TCL_SetVar - Set a tcl/tk variable value
TCL_UnsetVar - Remove a tcl variable
TCL_UpVar - Make a link from a tcl source variable to a tcl destination variable
TCL_EvalFile - Reads and evaluate a tcl/tk file
TK_EvalFile - Reads and evaluate a tcl/tk file (obsolete)
TCL_EvalStr - Evaluate a string whithin the tcl/tk interpreter
TK_EvalStr - Evaluate a string whithin the tcl/tk interpreter (obsolete)
TK_GetVar - Get a tcl/tk variable value (obsolete)
TK_SetVar - Set a tcl/tk variable value (obsolete)
close - close a figure
figure - create a figure
findobj - find an object with specified property
uicontrol - create a Graphic User Interface object
uimenu - Create a menu or a submenu in a figure


close

Scilab Function
Last update : 12/01/2004

close - close a figure

Parameters

  • o h : integer Handle of the window to close

Description

This routine close a tksci figure (toplevel window). If a handle is given, the figure corresponding to this handle is closed. Otherwise, the current (active) figure is closed.

Examples

h=figure();
// creates  figure number 1.
uicontrol( h, 'style','text', ...
 'string','scilab is great', ...
 'position',[50 70 100 100], ...
 'fontsize',15);
// put a clever text in figure 1
figure();
// create figure 2
uicontrol( 'style','text', ...
 'string','Really great', 'position',[50 70 100 100], 'fontsize',15);
// put a text in figure 2
close();
// close the current graphic window (ie fig. 2)
close(h);
// close figure 1

See Also

figure , gcf ,

Author

Bertrand Guiheneuf


figure

Scilab Function
Last update : 12/01/2004

figure - create a figure

Parameters

  • o h : integer Handle of the window to create. If not specified, the first free handle is used
  • o prop{1, 2 ...} : character string name of a property to set
  • o val{1, 2 ...} : scilab object value to give to the corresponding property
  • o hn : handle of the newly created window

Description

This routine creates a tksci figure (toplevel window). If a handle is given, the figure corresponding to this handle is created . Otherwise, the window is created with the first free handle, that is the lowest integer not already used by a window. The property named 'position' allows to control the geometrical aspect of the control. It is a [ 1,4] real vector x y w h where the letters stand for the x location of the left bottom corner, the y location of the left bottom corner, the width and the height of the uicontrol. One can also set this property by giving a string where the fields are separated by a '|', ie "x|y|w|h".

Examples

h=figure(3);
// creates  figure number 1.
uicontrol( h, 'style','text', ...
 'string','This is a figure', ...
 'position',[50 70 100 100], ...
 'fontsize',15);
// put a  text in figure 3
figure();
// create figure 1
uicontrol( 'style','text', ...
 'string','Another figure', ...
 'position',[50 70 100 100], ...
 'fontsize',15);
// put a text in figure 1
close();
// close the current graphic window (ie fig. 1)
close(h);
// close figure 3

See Also

close , gcf ,

Author

Bertrand Guiheneuf


findobj

Scilab Function
Last update : 19/04/2005

findobj - find an object with specified property

Parameters

  • prop : string character Name of the property to test (case unsensitive).
  • value : string character specify the value the tested propoerty should be equal to (case sensitive).
  • h : handle of the found object.

Description

This routine is currently used to find objects knowing their 'tag' property. It returns handle of the first found object which property 'prop' is equal to 'value'. If such an object does not exist, the function returns an empty matrix.

Examples

h=figure();
// creates  figure number 1.
uicontrol( h, 'style','text', ...
 'string','This is a figure', ...
 'position',[50 70 100 100], ...
 'fontsize',15, ...
 'tag','Alabel');
// put a  text in figure 1
lab=findobj('tag','Alabel');
// find the object which 'tag' value is 'Alabel'
disp('the handle of the label is '+string(lab));
close();

See Also

uicontrol , uimenu , set , get ,

Author

Bertrand Guiheneuf


uicontrol

Scilab Function
Last update : 06/11/2006

uicontrol - create a Graphic User Interface object

Calling Sequence

    h = uicontrol('PropertyName',PropertyValue,...) h =
uicontrol(parent,'PropertyName',PropertyValue,...)
h=uicontrol(uich)

Description

this routine creates an object in a figure. If the handle of the figure is given (as the first parameter), the uicontrol is created in this figure. If no handle is given, the uicontrol is created in the current figure ( which may be obtained with a call to gcf() ). If there is no current figure, then one is created before the creation of the uicontrol. Then when the control is created, the properties given as parameters are set with the coresponding values. It is equivalent to create the uicontrol, and then set its properties with the set() command. Nevertheless, it generally more efficient to set the properties in the call to uicontrol(). This is particularly true coincerning the 'style' field. Indeed, the default value for this property is 'pushbutton'. So if you do not set it at creation time, a button will be created, and will be transformed to another uicontrol when you call the get(h,'style', ... ) instruction. Scilab and all the graphic objects communicate through the property mechanism. Thus, to create adapted uicontrol, one has to know the use of the property fields.

h = uicontrol('PropertyName',PropertyValue,...) creates a uicontrol and assigns the specified properties and values to it. It assigns the default values to any properties you do not specify. The default uicontrol style is a pushbutton. The default parent is the current figure. See Properties for information about these and other properties.

h = uicontrol(parent,'PropertyName',PropertyValue,...) creates a uicontrol in the object specified by the handle, parent. If you also specify a different value for the Parent property, the value of the Parent property takes precedence. parent is the handle of a figure.

h=uicontrol(uich) gives focus to the uicontrol specified by the handle, uich.

Those are described under:

Properties

  • BackgroundColor [1,3] real vector or string Background color of the uicontrol. A color is specified as Red, Green and Blue values. Those values are real in [ 0,1]. The color can be given as a real vector, ie [R,G,B] or a string where each value is separated by a |, ie "R|G|B"
  • callback string String evaluated by the scilab interpreter when an usicontrol is activated. (for example when you click on a button).
  • fontangle string : {'normal'} | italic | oblique For a control containing some text, this property sets the slant of the font.
  • fontsize real For a control containing some text, this property sets the size of the font in FontUnits.
  • fontunits string : {points} | pixels | normalized For a control containing some text, this property sets the units with which the fontsize is specified.
  • fontweight string : light | {normal} | demi | bold For a control containing some text, this property sets the weight of the used font
  • fontname string : used to choose the name of the font selected to display the text of the control.
  • ForegroundColor [1,3] real vector or string Foreground color of the uicontrol. A color is specified as Red, Green and Blue values. Those values are real in [ 0,1]. The color can be given as a real vector, ie [R,G,B] or a string where each value is separated by a |, ie "R|G|B"
  • Horizontalalignment string: left | {center} | right. Set text horizontal alignment in the uicontrol. This property can only be used with 'text', 'edit' and 'checkbox' styles.
  • ListboxTop integer For a ListBox, this property tells which item of the list appears on the first line of the visible area of the list.
  • Max scalar Specifies the largest value the 'value' property can be set to. It has however differnet meaning on each uicontrol:
  • o Check Boxes : Max is the value the 'value' property take when control is checked
  • o Silders : Maximinum value of the slider
  • o List boxes : if (Max-Min)>1 the list allows multiple selection, Otherwise not.
  • Min scalar Specifies the lowest value the 'value' property can be set to. It has however different meaning on each uicontrol:
  • o Check Boxes : Min is the value the 'value' property take when control is unchecked
  • o Silders : Mininum value of the slider
  • o List boxes : if (Max-Min)>1 the list allows multiple selection, Otherwise not.
  • Parent integer Handle of the control parent. Changing this property allows to move a control from a figure to another.
  • Path This property is read-only. It allows to get the TK path of the control as a string. (Useful when creating User Interfaces using uicontrols and TCL/TK scripts.)
  • Position [1,4] real vector or string. This property is used to set or get the geometrical configuration of a control. It is a real; vector : x y w h where the letters stand for the x location of the left bottom corner, the y location of the left bottom corner, the width and the height of the uicontrol. The unit is determined by the 'Unit' property.
  • SliderStep [1,2] real vector or string, [small big]. The small step represents the movement achieved when clicking on the slider trough or tapping on the keyboard arrows (when the slider has focus); the big step is the amount moved when using Ctrl-keyboard-arrows. If the big step is omitted, it is defaulted to 1/10 of the scale.
  • String string. Generally, this property represents the text appearing in a uicontrol. Its exact meaning sometimes depends on the uicontrol style:
  • o List Boxes, Popup Menu the value can be a vector of string or a string where the items are separated by a '|'.
  • Style string : {pushbutton} | radiobutton | checkbox | edit | text | slider | frame |listbox | popupmenu Style of the uicontrol. Here is a short description of each one:
  • o pushbutton A rectangular button generally used to run a callback.
  • o radiobutton A button whith to states : on or off.
  • o checkbox a small uicontrol that have to state : on or off
  • o edit an editable string control
  • o text a text control (generally static).
  • o slider a scale control, that is a scrollbar use to set values between in range with the mouse.
  • o frame a control representing a zone used to group of related controls.
  • o listbox a control representing a list of item that can be scrolled. The item can be selected with the mouse.
  • o popupmenu a button which make a menu appear when clicked.
  • Tag string this property is generally used to identify the control. It allows to give it a "name". Mainly used in conjontion with findobj().
  • Units string : {points} | pixels | normalized Set the units used to specify the 'position' property.
  • Userdata this can be used to associate some scilab objects (string,string matrix, matrix mxn) to an uicontrol.
  • Value Value of the uicontrol. The exact meaning depends on the style of the uicontrol.
  • o Check boxes, Radio buttons value is set to Max (see above) when on and Min when off.
  • o List Boxes, Popu Menu value is a vector of indexes corresponding to the index of the selected entry in the list. 1 is the first item of the list.
  • o Sliders value indicated by the slider bar.
  • Verticalalignment string: top | {middle} | bottom. Set text vertical alignment in the uicontrol. This property can only be used with 'text' and 'checkbox' styles.

    • Examples

    f=figure();
// create a figure
h=uicontrol(f,'style','listbox', ...
 'position', [10 10 150 160]);
// create a listbox
set(h, 'string', "item 1|item 2|item3");
// fill the list
set(h, 'value', [1 3]);
// select item 1 and 3 in the list
close(f);
// close the figure

    See Also

    figure , set , get , uimenu ,

    Author

    Bertrand Guiheneuf


uimenu

Scilab Function
Last update : 19/04/2005

uimenu - Create a menu or a submenu in a figure

Calling Sequence

h=uimenu([prop1,val1] [,prop2, val2] ...)
h=uimenu(parent,[prop1, val1] [,prop2, val2] ...)

Parameters

  • parent : integer Handle of menu's parent
  • prop{1, 2 ...} : string character name of a property to set up
  • val{1, 2 ...} : scilab object value to affect to the corresponding property
  • h : integer handle of the corresponding menu

Description

This allows to create menus in a figure. If parent is a figure, then the menu item will be added to the menu bar of the figure. If parent is a menu item , then the new item will be added to the parent item, allowing to create cascaded submenu.

Properties

  • callback string: allows to set up the scilab instruction to call when the item is selected by the user.
  • label string: allows to set up the text appearing for the item.
  • tag string: this property is generally used to identify the menu. It allows to give it a "name". Mainly used in conjontion with findobj .

    • Examples

f=figure('position', [10 10 300 200]);
// create a figure
m=uimenu(f,'label', 'windows');
// create an item on the menu bar
m1=uimenu(m,'label', 'operations');
m2=uimenu(m,'label', 'quit scilab', 'callback', "exit");
//create two items in the menu "windows"
m11=uimenu(m1,'label', 'new window', 'callback',"xselect()");
m12=uimenu(m1,'label', 'clear  window', 'callback',"xbasc()");
// create a submenu to the item "operations"
close(f);
// close the figure

    See Also

    figure , uicontrol , set , get ,

    Author

    Bertrand Guiheneuf


ScilabEval

TCL Function
Last update : 08/02/2006

ScilabEval - tcl instruction : Evaluate a string with scilab interpreter

Calling Sequence

ScilabEval instruction
ScilabEval instruction "seq"
ScilabEval instruction "sync"
ScilabEval instruction "sync" "seq"
ScilabEval "flush"

Parameters

  • instruction : tcl string character contains a Scilab instruction to evaluate with the current Scilab interpreter.

Description

This function must be called in a tcl/tk script executed from Scilab. It allows to associate Scilab actions to tcl/tk widgets (graphic objects) or to use Scilab to perform some computations within a tcl script.

  • ScilabEval instruction

    If the ScilabEval instruction syntax is used, the instruction is first stored in a FIFO queue, ScilabEval returns immediately. Scilab executes the queued instructions when possible (it should be at the prompt but also at the end of each instructions of the currently running function) in the order they were submitted. This syntax can be used to associate Scilab actions to tcl/tk widgets but not into a tcl script executed by TCL_EvalFile or TCL_EvalStr because in this situation the Scilab interpreter is blocked up to the end of the script. Note that with the ScilabEval instruction syntax, if there are many ScilabEval commands stored in the queue the execution of the second one can be started in the middle of the execution of the first one (in particular if the first one contains more than a simple expression).

    If the "seq" option is added, the associated instruction evaluation should be finished (or paused) before the next queued instruction evaluation can be started. The next callback stored in the command queue will only be taken into account when the current one will be finished or paused.

  • ScilabEval instruction "sync"

    If the ScilabEval instruction "sync" syntax is used, the instruction is executed immediately (not queued) and the ScilabEval returns when the instruction evaluation is finished. The scilab instruction evaluation may be interrupted by new or queued commands.

    If the "seq" option is added, the associated instruction evaluation should be finished (or paused) before any queued instruction evaluation can be started. The scilab instruction evaluation may not be interrupted by new or queued commands (except if it is paused).

  • ScilabEval "flush"

    If the ScilabEval "flush" syntax is used, all the previously queued instructions are executed immediately and the ScilabEval returns when the execution is finished. Each instruction is executed with the option used at the time of queuing up (i.e. seq or no option).

    • The evaluation context of all these cases is the current Scilab context when the instruction evaluation starts.

    Examples

//Callbacks and "seq" option usage

//create tcl instructions
tcl_script=['toplevel .w1'
'button .w1.b -text ""Click here to execute without seq option""  -command WithoutSeq'
'button .w1.b1 -text ""Click here to execute with seq option""  -command  WithSeq'
'pack .w1.b .w1.b1'
'proc  WithoutSeq {} { ';
'  ScilabEval ""cont=%f;;cont=%t;"" '
'  ScilabEval ""if cont then disp(''ok''),else disp(''wrong'');end;cont=%f;"" '
'}'
'proc WithSeq {} { ';
'  ScilabEval ""cont=%f;;cont=%t;""  ""seq""'
'  ScilabEval ""if cont then disp(''ok''),else disp(''wrong'');end;cont=%f;"" '
'}'];
mputl(tcl_script,TMPDIR+'/test.tcl') //write them to a file
// Execute the tcl script
cont=%f;
TCL_EvalFile(TMPDIR+'/test.tcl');;

//scripts and "sync" option usage

//----------------without "sync"----------------
tcl_script=['  set t ""0""'
    '  while {$t != ""10""} {'
    '     ScilabEval ""a=$t;mprintf(''%d '',a);""'
    '     incr t'
    '  }'];

mputl(tcl_script,TMPDIR+'/test.tcl') //write them to a file
// Execute the tcl script
TCL_EvalFile(TMPDIR+'/test.tcl');mprintf('TCL_EvalFile finished\n');
// The ScilabEval are executed  after the and of TCL_EvalFile

//----------------with "sync"----------------
tcl_script=['  set t ""0""'
    '  while {$t != ""10""} {'
    '     ScilabEval ""a=$t;mprintf(''%d '',a);"" ""sync""'
    '     incr t'
    '  }'];

mputl(tcl_script,TMPDIR+'/test.tcl') //write them to a file
// Execute the tcl script
TCL_EvalFile(TMPDIR+'/test.tcl');mprintf('TCL_EvalFile finished\n');
// The ScilabEval are executed  synchronously with TCL_EvalFile

    See Also

    TCL_EvalFile , TCL_EvalStr , TCL_GetVar , TCL_SetVar ,

    Author

    Bertrand Guiheneuf


TCL_CreateSlave

Scilab Function
Last update : 18/11/2005

TCL_CreateSlave - Create a TCL slave interpreter

Calling Sequence

TCL_CreateSlave(interp)

Parameters

  • interp : character string parameter. Name of the slave tcl interpreter in which the operation has to be performed.

Description

This routine allows to create a TCL slave interpreter.

Examples

  TCL_CreateSlave('TCLinterp')
  TCL_SetVar('a','r','TCLinterp')
  TCL_ExistVar('a','TCLinterp')
  TCL_ExistVar('a')
  TCL_DeleteInterp('TCLinterp')

See Also

TCL_SetVar , TCL_ExistVar , TCL_DeleteInterp ,

Author

Allan CORNET


TCL_DeleteInterp

Scilab Function
Last update : 30/11/2005

TCL_DeleteInterp - delete TCL interpreter

Calling Sequence

TCL_DeleteInterp(interp)
TCL_DeleteInterp()

Parameters

  • interp : character string parameter. Name of the slave tcl interpreter to delete. If not provided, it defaults to the main tcl interpreter created by Scilab.

Description

This routine allows to delete a TCL slave interpreter or the main scilab TCL interpreter.

Examples

TCL_SetVar("Scilab","OK")
TCL_ExistVar("Scilab")
TCL_DeleteInterp()
TCL_ExistVar("Scilab")
TCL_CreateSlave('BisInterp')
TCL_ExistInterp('BisInterp')
TCL_SetVar("Scilab","OK",'BisInterp')
TCL_ExistVar("Scilab",'BisInterp')
TCL_DeleteInterp('BisInterp')
TCL_ExistInterp('BisInterp')

See Also

TCL_SetVar , TCL_ExistVar , TCL_CreateSlave , TCL_ExistInterp ,

Author

Allan CORNET


TCL_ExistInterp

Scilab Function
Last update : 21/11/2005

TCL_ExistInterp - Return %T if a tcl slave interperter exists

Calling Sequence

OK=TCL_ExistInterp(interp)

Parameters

  • interp : character string parameter. Name of the slave tcl interpreter.
  • ok : boolean. %T if TCL interpreter exists.

Description

This routine allows to test if TCL interpreter exists.

Examples

  TCL_ExistInterp('SlaveInterp')
  TCL_CreateSlave('SlaveInterp')
  TCL_ExistInterp('SlaveInterp')
  TCL_DeleteInterp('SlaveInterp')

See Also

TCL_CreateSlave , TCL_DeleteInterp ,

Author

Allan CORNET


TCL_ExistVar

Scilab Function
Last update : 18/11/2005

TCL_ExistVar - Return %T if a tcl variable exists

Calling Sequence

OK=TCL_ExistVar(varname [,interp])

Parameters

  • varname : character string. Contains the name of the tcl/tk variable.
  • interp : optional character string parameter. Name of the slave tcl interpreter in which the operation has to be performed. If not provided, it defaults to the main tcl interpreter created by Scilab.
  • ok : boolean. %T if varname exists.

Description

This routine allows to test if a tcl variable exists.

Examples

TCL_SetVar("Scilab","OK")
TCL_GetVar("Scilab")
TCL_UnsetVar("Scilab")
TCL_ExistVar("Scilab")

TCL_SetVar("aa",1)
TCL_CreateSlave('SlaveInterp');
TCL_SetVar("aa",2,'SlaveInterp')
TCL_ExistVar("aa")
TCL_GetVar("aa")
TCL_UnsetVar("aa")
TCL_GetVar("aa",'SlaveInterp')
TCL_UnsetVar("aa",'SlaveInterp')
TCL_ExistVar("aa",'SlaveInterp')
TCL_DeleteInterp('SlaveInterp')

See Also

ScilabEval , TCL_EvalFile , TCL_EvalStr , TCL_GetVar , TCL_SetVar , TCL_UnsetVar , TCL_UpVar , TCL_CreateSlave ,

Author

Allan CORNET


TCL_GetVar

Scilab Function
Last update : 21/11/2005

TCL_GetVar - Get a tcl/tk variable value

Calling Sequence

value=TCL_GetVar(Varname [,interp])

Parameters

  • varname : character string. Contains the name of the tcl/tk variable.
  • interp : optional character string parameter. Name of the slave tcl interpreter in which the operation has to be performed. If not provided, it defaults to the main tcl interpreter created by Scilab.
  • value : may be a character string or a strings matrix. Contains the value of the tcl/tk variable varname in the interpreter interp .

Description

When tcl/tk support is enabled in Scilab, this routine can be used to retreive the value of a tcl/tk variable.

Examples

//----------------------------------------------------
TCL_EvalStr("toplevel .tst1");
// creates a toplevel TK window.
TCL_EvalStr("entry .tst1.e -textvariable tvar");
// create an editable entry
TCL_EvalStr("set tvar foobar");
// set the entry value
TCL_EvalStr("pack .tst1.e");
// pack the entry widget. It appears on the screen.
text=TCL_GetVar("tvar")
// retrieve the variable value
// change the entry text and repeat the last command ...
//delete the toplevel TK window.
TCL_EvalStr("destroy .tst1")
//----------------------------------------------------
a=["A","B","C";"D","E","F"];
TCL_SetVar("A",a)
AfromTCL=TCL_GetVar("A")
//----------------------------------------------------
b=[6,4,1;2,3,5];
TCL_SetVar("B",b)
BfromTCL=TCL_GetVar("B")
//----------------------------------------------------
TCL_SetVar("StringTCL","string")
StringFromTCL=TCL_GetVar("StringTCL")
//----------------------------------------------------
TCL_SetVar("ScalarTCL",1.22)
ScalarFromTCL=TCL_GetVar("ScalarTCL")
//----------------------------------------------------
// Examples with a slave interpreter
//----------------------------------------------------
a=['AA','BB','CC';'DD','EE','FF'];
TCL_CreateSlave('SlaveInterp')
TCL_SetVar("A_slave",a,'SlaveInterp')
AfromTCL_slave=TCL_GetVar('A_slave','SlaveInterp')
TCL_DeleteInterp('SlaveInterp')
//----------------------------------------------------
b=[66,44,11;22,33,55];
TCL_CreateSlave('SlaveInterp1')
TCL_SetVar("B_slave",b,'SlaveInterp1')
BfromTCL_slave=TCL_GetVar('B_slave','SlaveInterp1')
TCL_DeleteInterp('SlaveInterp1')
//----------------------------------------------------
TCL_CreateSlave('SlaveInterp2')
TCL_SetVar("StringTCL_slave","string in slave interpreter",'SlaveInterp2')
StringFromTCL_slave=TCL_GetVar("StringTCL_slave",'SlaveInterp2')
TCL_DeleteInterp('SlaveInterp2')
//----------------------------------------------------
TCL_CreateSlave('SlaveInterp3')
TCL_SetVar("ScalarTCL_slave",1.22,'SlaveInterp3')
ScalarFromTCL_slave=TCL_GetVar("ScalarTCL_slave",'SlaveInterp3')
TCL_DeleteInterp('SlaveInterp3')
//----------------------------------------------------

See Also

ScilabEval , TCL_EvalFile , TCL_EvalStr , TCL_SetVar , TCL_ExistVar , TCL_UnsetVar , TCL_UpVar , TCL_CreateSlave , TCL_DeleteInterp ,

Author

Allan CORNET


TCL_GetVersion

Scilab Function
Last update : 08/06/2005

TCL_GetVersion - get the version of the TCL/TK library at runtime.

Calling Sequence

TCL_GetVersion()

Description

get the version of the TCL/TK library at runtime.

Examples

TCL_GetVersion()

Author

Allan CORNET


TCL_SetVar

Scilab Function
Last update : 21/11/2005

TCL_SetVar - Set a tcl/tk variable value

Calling Sequence

TCL_SetVar(varname, value [,interp])

Parameters

  • varname : character string. Contains the name of the tcl/tk variable to set.
  • value : may be a character string, a scalar, a real or string matrix (m x n). Contains the value to give to the tcl/tk variable.
  • interp : optional character string parameter. Name of the slave tcl interpreter in which the operation has to be performed. If not provided, it defaults to the main tcl interpreter created by Scilab.

Description

This routine allows to set a variable within a tcl/tk interpreter. When tcl/tk support is enabled in scilab, this routine can be used to set up the value of a tcl/tk variable. This can be useful to change some value in the tcl/tk interpreter without having to build a tcl/tk instruction (and use TCL_EvalStr ).

Examples

//----------------------------------------------------
TCL_EvalStr("toplevel .tst1");
// creates a toplevel TK window.
TCL_EvalStr("entry .tst1.e -textvariable tvar");
// create an editable entry
TCL_EvalStr("set tvar foobar");
// set the entry value
TCL_EvalStr("pack .tst1.e");
// pack the entry widget. It appears on the screen.
text=TCL_GetVar("tvar")
// retrieve the variable value
// change the entry text and repeat the last command ...
//delete the toplevel TK window.
TCL_EvalStr("destroy .tst1")
//----------------------------------------------------
a=["A","B","C";"D","E","F"];
TCL_SetVar("A",a)
AfromTCL=TCL_GetVar("A")
//----------------------------------------------------
b=[6,4,1;2,3,5];
TCL_SetVar("B",b)
BfromTCL=TCL_GetVar("B")
//----------------------------------------------------
TCL_SetVar("StringTCL","string")
StringFromTCL=TCL_GetVar("StringTCL")
//----------------------------------------------------
TCL_SetVar("ScalarTCL",1.22)
ScalarFromTCL=TCL_GetVar("ScalarTCL")

//----------------------------------------------------
// Examples with a slave interpreter
//----------------------------------------------------
TCL_CreateSlave('TCLSlave')
a=['AA','BB','CC';'DD','EE','FF'];
TCL_SetVar("A_slave",a,'TCLSlave')
AfromTCL_slave=TCL_GetVar('A_slave','TCLSlave')
TCL_DeleteInterp('TCLSlave')
//----------------------------------------------------
TCL_CreateSlave('TCLSlave')
b=[66,44,11;22,33,55];
TCL_SetVar("B_slave",b,'TCLSlave')
BfromTCL_slave=TCL_GetVar('B_slave','TCLSlave')
TCL_DeleteInterp('TCLSlave')
//----------------------------------------------------
TCL_CreateSlave('TCLSlave')
TCL_SetVar("StringTCL_slave","string in slave interpreter",'TCLSlave')
StringFromTCL_slave=TCL_GetVar("StringTCL_slave",'TCLSlave')
TCL_DeleteInterp('TCLSlave')
//----------------------------------------------------
TCL_CreateSlave('TCLSlave')
TCL_SetVar("ScalarTCL_slave",1.22,'TCLSlave')
ScalarFromTCL_slave=TCL_GetVar("ScalarTCL_slave",'TCLSlave')
TCL_DeleteInterp('TCLSlave')
//----------------------------------------------------

See Also

ScilabEval , TCL_EvalFile , TCL_EvalStr , TCL_GetVar , TCL_ExistVar , TCL_UnsetVar , TCL_UpVar , TCL_CreateSlave , TCL_DeleteInterp ,

Author

Allan CORNET


TCL_UnsetVar

Scilab Function
Last update : 18/11/2005

TCL_UnsetVar - Remove a tcl variable

Calling Sequence

OK=TCL_UnsetVar(varname [,interp])

Parameters

  • varname : character string. Contains the name of the tcl/tk variable to unset.
  • interp : optional character string parameter. Name of the slave tcl interpreter in which the operation has to be performed. If not provided, it defaults to the main tcl interpreter created by Scilab.
  • ok : boolean. %T if varname was deleted.

Description

This routine allows to unset a tcl variable.

Examples

TCL_SetVar("Scilab","OK")
TCL_GetVar("Scilab")
TCL_UnsetVar("Scilab")
TCL_ExistVar("Scilab")

TCL_CreateSlave('InterpSlave');
TCL_SetVar("Scilab","Good",'InterpSlave')
TCL_GetVar("Scilab",'InterpSlave')
TCL_UnsetVar("Scilab",'InterpSlave')
TCL_ExistVar("Scilab",'InterpSlave')
TCL_DeleteInterp('InterpSlave')

See Also

ScilabEval , TCL_EvalFile , TCL_EvalStr , TCL_GetVar , TCL_SetVar , TCL_ExistVar , TCL_UpVar , TCL_CreateSlave , TCL_DeleteInterp ,

Author

Allan CORNET


TCL_UpVar

Scilab Function
Last update : 18/11/2005

TCL_UpVar - Make a link from a tcl source variable to a tcl destination variable

Calling Sequence

OK=TCL_UpVar(varname1,varname2,[interp])

Parameters

  • varname1 : character string. Contains the name of the tcl source variable.
  • varname2 : character string. Contains the name of the tcl destination variable.
  • interp : optional character string parameter. Name of the slave tcl interpreter in which the operation has to be performed. If not provided, it defaults to the main tcl interpreter created by Scilab.
  • ok : boolean. %T if it is ok.

Description

Make a link from a tcl source variable to a tcl destination variable.

Examples

TCL_SetVar("Scilab","OK")
TCL_UpVar("Scilab","ScilabBis")
TCL_GetVar("ScilabBis")
TCL_SetVar("Scilab","NOK")
TCL_GetVar("ScilabBis")
TCL_SetVar("ScilabBis","modified")
TCL_GetVar("ScilabBis")
TCL_GetVar("Scilab")

TCL_CreateSlave('InterpBis')
TCL_SetVar("Scilab","Good",'InterpBis')
TCL_UpVar("Scilab","ScilabBis",'InterpBis')
TCL_GetVar("ScilabBis",'InterpBis')
TCL_SetVar("Scilab","Not good",'InterpBis')
TCL_GetVar("ScilabBis",'InterpBis')
TCL_SetVar("ScilabBis","modified again",'InterpBis')
TCL_GetVar("ScilabBis",'InterpBis')
TCL_GetVar("Scilab",'InterpBis')
TCL_DeleteInterp('InterpBis')

See Also

ScilabEval , TCL_EvalFile , TCL_EvalStr , TCL_GetVar , TCL_SetVar , TCL_ExistVar , TCL_UnsetVar , TCL_CreateSlave , TCL_DeleteInterp ,

Author

Allan CORNET


TCL_EvalFileTK_EvalFile

Scilab Function
Last update : 22/10/2005

TCL_EvalFile - Reads and evaluate a tcl/tk file

TK_EvalFile - Reads and evaluate a tcl/tk file (obsolete)

Calling Sequence

TCL_EvalFile(filename [,interp])

Parameters

  • filename : character string. Contains the name of the file to read and evaluate.
  • interp : optional character string parameter. Name of the slave tcl interpreter in which the operation has to be performed. If not provided, it defaults to the main tcl interpreter created by Scilab.

Description

With this routine, one can read and evaluate the content of a file containing tcl/tk scripts. This allows to create powerful tk interfaces.

The filename might be relative or absolute.

Advantages and drawbacks of this functionality

This routines allows to use directly tcl/tk scripts. This thus allows, for instance to use Interface Builders such as SpecTcl to design the interface. The interfaces built directly with tcl/tk scripts are much faster than the ones built with the Scilab Graphic Object library provided with tksci (see uicontrol for example). Indeed, those Objects are warpings around tk graphic widgets. Nevertheless, this way of creating graphic user interface should only be used when one aims at addressing directly specific tk/tcl features. There are two main reasons for this. First of all, there is no simple way to manipulate Scilab objects from within a tcl/tk script. Thus, the interface designer has to write two sets of callbacks routines. One to describe the changes occuring in the interface when the user acts on the widgets. The second set of call routines will perform the (pure) Scilab reactions to the user actions.

Here is an example: Suppose you design a scrollbar corresponding to a spline tension value. You want the spline to be displayed in a graphic windows and updated each time the user moves the scrollbar. At the same time, you want the value of this tension parameter to be displayed within the Interface. You will have to write a first tcl/tk (callback) function which will be automatically called by the tk scrollbar ("-command" option). This callback function will update the displayed value of the parameter in the interface and will then call the scilab routine ("ScilabEval" command) to update the graph.

Remarks on the tcl/tk script style

Because Scilab manages the tcl/tk events, it creates the root window ".", this window should not be destroyed nor directly used by your tcl/tk scripts. You should thus always create your own toplevel windows. Moreover, since this module was written at a time when namespaces didn't exist, some variables defined by scilab tcl/tk scripts could collide your code. Running your scripts in a slave interpreter may help in such a case.

Examples

TCL_EvalFile(SCI+"/demos/tk/puzzle")

scipad();TCL_EvalFile(SCI+"/demos/tk/puzzle","scipad")

See Also

ScilabEval , TCL_EvalStr , TCL_GetVar , TCL_SetVar , TCL_ExistVar , TCL_UnsetVar , TCL_UpVar ,

Author

Allan CORNET


TCL_EvalStrTK_EvalStr

Scilab Function
Last update : 16/12/2005

TCL_EvalStr - Evaluate a string whithin the tcl/tk interpreter

TK_EvalStr - Evaluate a string whithin the tcl/tk interpreter (obsolete)

Calling Sequence

TCL_EvalStr(str [,interp])

Parameters

  • str : string or vector of strings, contains the tcl/tk instructions
  • interp : optional character string parameter. Name of the slave tcl interpreter in which the operation has to be performed. If not provided, it defaults to the main tcl interpreter created by Scilab.

Description

This routine allows to evaluate tcl/tk instructions with the tcl/tk interpreter launched with Scilab (when the interp parameter is not given), or in a slave interpreter.

When tcl/tk support is enabled in Scilab, you can evaluate tcl/tk expression from Scilab interpreter. In fact, Scilab launches a main tcl/tk interpreter. The Scilab instruction TCL_EvalStr can be used to evaluate expressions without having to write tcl/tk instructions in a separated file (this capability is provided by TCL_EvalFile ).

Examples

//with one call
TCL_EvalStr(["toplevel .foo1"
   "label .foo1.l -text ""TK married Scilab !!!"""
   "pack .foo1.l"
   "button .foo1.b -text close -command {destroy .foo1}"
   "pack .foo1.b"])

//step by step (debugging)
TCL_EvalStr("toplevel .foo2");
// creates a toplevel TK window.
TCL_EvalStr("label .foo2.l -text ""TK married Scilab !!!""");
// create a static label
TCL_EvalStr("pack .foo2.l");
// pack the label widget. It appears on the screen.
text="button .foo2.b -text close -command {destroy .foo2}";
TCL_EvalStr(text);
TCL_EvalStr("pack .foo2.b");

//kill the windows by program
TCL_EvalStr("destroy .foo1");
TCL_EvalStr("destroy .foo2");

//with one call, and in a slave interpreter
TCL_CreateSlave('TCLSlave');
TCL_EvalStr('set test ""in Slave TCL Interp""','TCLSlave');
TCL_GetVar('test','TCLSlave')

TCL_DeleteInterp('TCLSlave')

See Also

ScilabEval , TCL_EvalFile , TCL_GetVar , TCL_SetVar , TCL_ExistVar , TCL_UnsetVar , TCL_UpVar ,

Author

Allan CORNET


TK_GetVar

Scilab Function
Last update : 08/09/2005

TK_GetVar - Get a tcl/tk variable value (obsolete)

Description

See TCL_GetVar.

See Also

TCL_GetVar ,

Author

Allan CORNET


TK_SetVar

Scilab Function
Last update : 08/09/2005

TK_SetVar - Set a tcl/tk variable value (obsolete)

Description

See TCL_SetVar.

See Also

TCL_SetVar ,

Author

Allan CORNET


Interface Java
SciComplex - Class to use complex object with scilab
SciComplexArray - Class to use complex matrix in Scilab.
SciDouble - Class to use double object with scilab
SciDoubleArray - Class to use real matrix in Scilab.
SciString - Class to use String object in Scilab.
SciStringArray - Classe to use String matrix in Scilab.
Scilab - Scilab Class
javasci - Scilab tool to interface Scilab functions to Java


javasci

Java Interface
Last update : 30/01/2006

javasci - Scilab tool to interface Scilab functions to Java

Description

Java interface written to allow calling Scilab computational engine from Java.

Examples

 // See SCI/examples/Callsci/CallsciJava directory

See Also

Scilab , SciDouble , SciDoubleArray , SciString , SciStringArray ,

Author

A.C


Scilab

Java Interface
Last update : 01/06/2006

Scilab - Scilab Class

Description

Method Summary :

public static void Events() : do a scilab event.

public static boolean HaveAGraph() : return true if there is a scilab graphic window.

public static boolean Exec(String job) : execute a job in scilab. return true if there is no error.

public static native boolean ExistVar(String VarName) : Detect if VarName exists in Scilab. return true if Varname exist.

public static native int TypeVar(String VarName) : return Scilab type of VarName. See type

public static native int GetLastErrorCode() : return last Error code. See lasterror

public static native boolean Finish() : terminate scilab (call scilab.quit , close a scilab object)

Examples

 // See SCI/examples/Callsci/CallsciJava directory

See Also

SciDouble , SciDoubleArray , SciString , SciStringArray , type , lasterror ,

Author

A.C


SciComplex

Java Interface
Last update : 19/07/2006

SciComplex - Class to use complex object with scilab

Description

Method Summary :

public SciComplex(String name,SciComplex Obj) : Constructor

public SciComplex(String name) : Constructor

public SciComplex(String name,double realpart,double imaginarypart ) : Constructor

public String getName() : Get Name of scilab object

public double getRealPartData() : Get Real Part Value of scilab object

public double getImaginaryPartData() : Get Imaginary Part Value of scilab object

public void Get() : Get in java object , value of scilab object

public boolean Job(String job) : Execute a job in scilab

public void Send() : Send to scilab object , value of java object

public void disp() : disp object

public void toString() : convert complex to a string

Examples

 // See SCI/examples/Callsci/CallsciJava directory

See Also

Scilab , SciComplexArray , SciString , SciStringArray , SciDoubleArray , SciDouble ,

Author

A.C


SciComplexArray

Java Interface
Last update : 19/07/2006

SciComplexArray - Class to use complex matrix in Scilab.

Description

Method Summary :

public SciComplexArray(String name,SciComplexArray Obj) : Constructor

public SciComplexArray(String name,int r,int c) : Constructor

public SciComplexArray(String name,int r,int c,double [] realpart,double [] imaginarypart) : Constructor

public int getRow() : Get number of rows

public int getCol() : Get number of colons

public String getName() : Get Name of scilab object

public double[] getRealPartData() : Get Real Part Value of scilab object

public double[] getImaginaryPartData() : Get Imaginary Part Value of scilab object

public void disp() : disp object

public boolean Job(String job) : Execute a job in scilab

public void Get() : Get in java object , value of scilab object

public void Send() : Send to scilab object , value of java object

public double GetRealPartElement(int indr, int indc) : Get a specific element of scilab object

public double GetImaginaryPartElement(int indr, int indc) : Get a specific element of scilab object

Examples

 // See SCI/examples/Callsci/CallsciJava directory

See Also

Scilab , SciComplex , SciDouble , SciDoubleArray , SciString , SciStringArray ,

Author

A.C


SciDouble

Java Interface
Last update : 30/01/2006

SciDouble - Class to use double object with scilab

Description

Method Summary :

public SciDouble(String name,SciDouble Obj) : Constructor

public SciDouble(String name) : Constructor

public SciDouble(String name,double Value ) : Constructor

public String getName() : Get Name of scilab object

public double getData() : Get Value of scilab object

public void Get() : Get in java object , value of scilab object

public boolean Job(String job) : Execute a job in scilab

public void Send() : Send to scilab object , value of java object

public void disp() : disp object

Examples

 // See SCI/examples/Callsci/CallsciJava directory

See Also

Scilab , SciDoubleArray , SciString , SciStringArray ,

Author

A.C


SciDoubleArray

Java Interface
Last update : 30/01/2006

SciDoubleArray - Class to use real matrix in Scilab.

Description

Method Summary :

public SciDoubleArray(String name,SciDoubleArray Obj) : Constructor

public SciDoubleArray(String name,int r,int c) : Constructor

public SciDoubleArray(String name,int r,int c,double [] x ) : Constructor

public int getRow() : Get number of rows

public int getCol() : Get number of colons

public String getName() : Get Name of scilab object

public double[] getData() : Get Value of scilab object

public void disp() : disp object

public boolean Job(String job) : Execute a job in scilab

public void Get() : Get in java object , value of scilab object

public void Send() : Send to scilab object , value of java object

public double GetElement(int indr, int indc) : Get a specific element of scilab object

Examples

 // See SCI/examples/Callsci/CallsciJava directory

See Also

Scilab , SciDouble , SciString , SciStringArray ,

Author

A.C


SciString

Java Interface
Last update : 16/02/2006

SciString - Class to use String object in Scilab.

Description

Method Summary :

public SciString(String name,SciString Obj) : Constructor

public SciString(String name) : Constructor

public String getName() : Get Name of scilab object

public void Get() : Get in java object , value of scilab object

public String getData() :Get Value of scilab object

public void Send() : Send to scilab object , value of java object

public void disp() : disp object

public boolean Job(String job) : Execute a job in scilab

Examples

 // See SCI/examples/Callsci/CallsciJava directory

See Also

Scilab , SciDouble , SciDoubleArray , SciStringArray ,

Author

A.C


SciStringArray

Java Interface
Last update : 30/01/2006

SciStringArray - Classe to use String matrix in Scilab.

Description

Method Summary :

public SciDoubleArray(String name,SciDoubleArray Obj) : Constructor

public SciStringArray(String name,int r,int c) : Constructor

public SciStringArray(String name,int r,int c,String [] x ) : Constructor

public int getRow() : Get number of rows

public int getCol() : Get number of colons

public String getName() : Get Name of scilab object

public String[] getData() : Get Value of scilab object

public void Get() : Get in java object , value of scilab object

public void Send() : Send to scilab object , value of java object

public void disp() : disp object

public boolean Job(String job) : Execute a job in scilab

public String GetElement(int indr, int indc) : Get a specific element of scilab object

Examples

 // See SCI/examples/Callsci/CallsciJava directory

See Also

Scilab , SciDouble , SciDoubleArray , SciString ,

Author

A.C


lincos

Scilab Function

lincos - Constructs by linearization a linear state-space model from a general dynamical system described by a scicos diagram

Calling Sequence

sys= lincos(scs_m [,x0,u0 [,param] ])

Parameters

  • scs_m : a Scicos data structure
  • x0 : column vector. Continuous state around which linearization to be done (default 0)
  • u0 : column vector. Input around which linearization to be done (default 0)
  • param : param: list with two elements (default list(1.d-6,0)) param(1): scalar. Perturbation level for linearization; the following variation is used del([x;u])_i = param(1)+param(1)*1d-4*abs([x;u])_i. param(2): scalar. Time t.
  • sys : state-space system

Description

Construct a linear state-space system by linearizing a model given as a Scicos diagram.

The output is a Scilab data structure of type continuous-time state-space linear system.

See Also

steadycos , scicos_simulate ,

Authors

Ramine Nikoukhah


scicos

Scilab Function

scicos - Block diagram editor and GUI for the hybrid simulator scicosim

Calling Sequence

scs_m = scicos([toto])

Parameters

  • toto : either a Scicos diagram structure (scs_m) or a character string containing the path of the diagram file (.cos or .cosf extension). If no input argument is used, an empty diagram is opened (default name Untitled).
  • scs_m : Scicos diagram structure after edition.

Description

Scicos is a visual editor for constructing models of hybrid dynamical systems. Invoking Scicos with no argument opens up an empty Scicos window. Models can then be assembled, loaded, saved, compiled, simulated, using GUI of Scicos. Scicos serves as an interface to the various block diagram compilers and the hybrid simulator scicosim.

The input and output arguments are useful for debugging purposes.

See Also

scicosim , scicos_simulate ,

Authors

Ramine Nikoukhah


scicos_simulate

Scilab Function

scicos_simulate - Function for running scicos simulation in batch mode.

Calling Sequence

Info=scicos_simulate(scs_m,Info[,%scicos_context][,flag])

Parameters

  • scs_m : scicos diagram (obtained by "load file.cos"). Note that the version of file.cos must be the current version. If not, load into scicos and save.
  • Info : a list. It must be list() at the first call, then use output Info as input Info for the next calls. Info contains compilation and simulation information and is used to avoid recompilation when not needed.
  • %scicos_context : a scilab struct containing values of symbolic variables used in the context and Scicos blocks. This is often used to change a parameter in the diagram context. In that case, make sure that in the diagram context the variable is defined such that it can be modified. Say a variable "a" is to be defined in the context having value 1, and later in batch mode, we want to change the value of "a". In that case, in the context of the diagram place: if ~exists('a') then a=1,end If you want then to run the simulation in batch mode using the value a=2, set: %scicos_context.a=2
  • flag : string. If it equals 'nw' (no window), then blocks using graphical windows are not executed. Note that the list of such blocks must be updated as new blocks are added.
  • Info : contains compilation and simulation information and is used to avoid recompilation when not needed. Normally it should not be modified.

Description

This function is used to simulate scicos diagrams in batch mode. It requires the scs_m structure which can be obtained by loading in Scilab the .cos file (e.g. load mydiagram.cos).

Contrary to the function scicosim , the diagram need not be compiled before being saved.

See Also

scicosim , scicos , steadycos , lincos ,

Authors

Ramine Nikoukhah


scicosim

Scilab Function

scicosim - Scicos (batch) simulation function

Calling Sequence

[state,t] = scicosim(state,tcur,tf,sim,str,tol)

Parameters

  • state : Scilab tlist containing initial state. Usually generated by Scicos Compile. After loading a compiled .cos file, it can be found in %cpr.state.
  • tcur : starting time of simulation. At the beginning it must be zero.
  • tf : final simulation time.
  • sim : Scilab tlist containing compilation results. Usually generated by Scicos Compile. After loading a compiled .cos file, it can be found in %cpr.sim.
  • str : 'start' , 'run' or 'finish'. Function must be first called with 'start', then with 'run' one or more times, and finally with 'finish'.
  • tol : vector [atol,rtol,ttol,deltat,realtimescale,solver,hmax] where atol, rtol are respectively the absolute and relative tolerances for ode or dae solver, ttol is the precision on event dates (must be very small). deltat is maximum integration interval for each call to ode solver (sometimes needed to force restaring the call to solver). raltimescale is the correspondance between simulation time and real time (0 means no slowing down). solver is the choice of solver (0: lsodar, 100: daskr). hmax: max step size used by solver. Default: [0.0001,1.000E-06,1.000E-10,100001,0,0]
  • state : state after simulation
  • t : final reached time. Usually tf but not always.

Description

Simulator for Scicos compiled diagram. Usually scicosim is called by scicos to perform simulation of a diagram. But scicosim may also be called outside Scicos. Typical usage in such a case may be: 1- Use Scicos to define a block diagram, compile it. 2- Save the compiled diagram using Save,SaveAs Scicos menus . 3- In Scilab, load saved file using load function. You get variables scicos_ver, scs_m, %cpr scs_m is the diagram Scicos main data structure. %cpr is the data structure containing (state,sim,cor,corinv) if the diagram had been compiled before saved, else %cpr=list(). 4- Extract state, sim out of cpr 5- Execute [state,t]=scicosim(state,0,tf,sim,'start',tol) for initialisation. 6- Execute [state,t]=scicosim(state,0,tf,sim,'run',tol) for simulation from 0 to tf. Many successives such calls may be performed changing initial and final time. 7- Execute [state,t]=scicosim(state,0,tf,sim,'finish',tol) at the very end of the simulation to close files,... For advanced user it is possible to "manually" change some parameters or state values.

See Also

scicos_simulate , scicos ,

Authors

Ramine Nikoukhah


steadycos

Scilab Function

steadycos - Finds an equilibrium state of a general dynamical system described by a scicos diagram

Calling Sequence

[X,U,Y,XP]=steadycos(scs_m,X,U,Y,Indx,Indu,Indy [,Indxp [,param ] ])

Parameters

  • scs_m : a Scicos data structure
  • X : column vector. Continuous state. Can be set to [] if zero.
  • U : column vector. Input. Can be set to [] if zero.
  • Y : column vector. Output. Can be set to [] if zero.
  • Indx : index of entries of X that are not fixed. If all can vary, set to 1:$
  • Indu : index of entries of U that are not fixed. If all can vary, set to 1:$
  • Indy : index of entries of Y that are not fixed. If all can vary, set to 1:$
  • Indxp : index of entries of XP (derivative of x) that need not be zero. If all can vary, set to 1:$. Default [].
  • param : list with two elements (default list(1.d-6,0)). param(1): scalar. Perturbation level for linearization; the following variation is used del([x;u])_i = param(1)+param(1)*1d-4*abs([x;u])_i. param(2): scalar. Time t.
  • X : steady state X
  • U : stationary input U
  • Y : output corresponding to steady state found
  • XP : derivative of the state corresponding to steady state found

Description

This function finds the steady state for a given system described by a Scicos diagram. The diagram consists in general of a Super block with input and output port blocks. The steady states concerns only the continuous-time dynamics.

See Also

lincos , scicos_simulate , scicos ,

Authors

Ramine Nikoukhah

Used Function

optim