Introduction `a Scilab
Micha¨el Baudin Artem Glebov Jerome Briot Mars 2013
R´esum´e Dans ce document, nous faisons un survol des fonctionnalit´es de Scilab afin de nous familiariser avec cet environnement. L’objectif est de pr´esenter les comp´etences n´ecessaires pour d´emarrer avec Scilab. Dans la premi`ere partie, nous pr´esentons comment obtenir et installer ce logiciel sur notre ordinateur. Nous pr´esentons ´egalement comment obtenir de l’aide avec la documentation fournie en ligne et aussi grˆaceaux ressources sur internet et aux forums. Dans les sections suivantes, nous pr´esentons le langage Scilab, en particulier ses fonctionnalit´es de programmation structur´ee.Nous pr´esentons une caract´eristique importante de Scilab, qui est la gestion des matrices r´eelles. La d´efinition des fonctions et de la gestion ´el´ementaire des variables d’entr´ee et de sortie est pr´esent´ee. Nous pr´esentons les fonctionnalit´es graphiques de Scilab et nous montrons comment cr´eer un trac´e2D, comment configurer son titre et sa l´egende et comment exporter ce trac´edans un format vectoriel ou bitmap.
Table des mati`eres
1 Vue d’ensemble5 1.1 Introduction...... 5 1.2 Vue d’ensemble de Scilab...... 5 1.3 Comment obtenir et installer Scilab...... 6 1.3.1 Installer Scilab sous Windows...... 7 1.3.2 Installation de Scilab sous GNU/Linux...... 7 1.3.3 Installation de Scilab sous Mac OS...... 8 1.4 Comment obtenir de l’aide...... 8 1.5 Listes de diffusion, forum, wiki, rapports de bogue et la Forge....9 1.6 Obtenir de l’aide `apartir des d´emonstrations Scilab et des macros.. 11 1.7 Exercices...... 12
2 Mise en route 12 2.1 La console...... 13 2.2 L’´editeur...... 14 2.3 Ancrage des fenˆetres graphiques...... 17 2.4 Le navigateur de variable et l’historique des commandes...... 18 2.5 Utiliser exec ...... 21
1 2.6 Commentaires...... 21 2.7 Ex´ecution par lot...... 21 2.8 Localisation...... 23 2.9 ATOMS, le syst`eme de paquetage de Scilab...... 26 2.10 Exercises...... 28
3 Basic elements of the language 30 3.1 Creating real variables...... 30 3.2 Variable names...... 31 3.3 Comments and continuation lines...... 32 3.4 Elementary mathematical functions...... 32 3.5 Pre-defined mathematical variables...... 32 3.6 Booleans...... 33 3.7 Complex numbers...... 34 3.8 Integers...... 35 3.8.1 Overview of integers...... 35 3.8.2 Conversions between integers...... 36 3.8.3 Circular integers and portability issues...... 37 3.9 Floating point integers...... 38 3.10 The ans variable...... 39 3.11 Strings...... 39 3.12 Dynamic type of variables...... 40 3.13 Notes and references...... 40 3.14 Exercises...... 40
4 Matrices 41 4.1 Overview...... 41 4.2 Create a matrix of real values...... 42 4.3 The empty matrix [] ...... 43 4.4 Query matrices...... 44 4.5 Accessing the elements of a matrix...... 44 4.6 The colon ”:” operator...... 46 4.7 The eye matrix...... 48 4.8 Matrices are dynamic...... 49 4.9 The dollar ”$” operator...... 50 4.10 Low-level operations...... 51 4.11 Elementwise operations...... 52 4.12 Conjugate transpose and non-conjugate transpose...... 52 4.13 Multiplication of two vectors...... 53 4.14 Comparing two real matrices...... 54 4.15 Issues with floating point integers...... 55 4.16 More on elementary functions...... 57 4.17 Higher-level linear algebra features...... 58 4.18 Exercises...... 58
2 5 Looping and branching 60 5.1 The if statement...... 60 5.2 The select statement...... 61 5.3 The for statement...... 62 5.4 The while statement...... 64 5.5 The break and continue statements...... 65
6 Functions 66 6.1 Overview...... 66 6.2 Defining a function...... 67 6.3 Function libraries...... 69 6.4 Managing output arguments...... 71 6.5 Levels in the call stack...... 72 6.6 The return statement...... 73 6.7 Debugging functions with pause ...... 74
7 Plotting 76 7.1 Overview...... 76 7.2 2D plot...... 76 7.3 Contour plots...... 78 7.4 Titles, axes and legends...... 81 7.5 Export...... 83
8 Notes and references 84
9 Acknowledgments 85
10 Answers to exercises 86 10.1 Answers for section 1.7...... 86 10.2 Answers for section 2.10...... 86 10.3 Answers for section 3.14...... 89 10.4 Answers for section 4.18...... 92
R´ef´erences 93
Index 94
3 Copyright c 2013 - Jerome Briot
Copyright c 2013 - Michael Baudin
Copyright c 2010 - Artem Glebov
Copyright c 2008-2011 - Consortium Scilab - Digiteo - Michael Baudin
Ce fichier doit ˆetre utilis´eselon les termes de la licence ”Creative Commons Attribution - Partage dans les Mˆemes Conditions 3.0 non transpos´e”:
http://creativecommons.org/licenses/by-sa/3.0/deed.fr
4 1 Vue d’ensemble
Dans cette section, nous pr´esentons un aper¸cude Scilab. Le premier chapitre pr´esente le projet open source associ´e`ala cr´eation de ce document. Ensuite, nous pr´esentons les aspects logiciels, licences et scientifiques de Scilab. Dans le troisi`eme chapitre, nous d´ecrivons les m´ethodes pour t´el´echarger et installer Scilab sur les syst`emes d’exploitation Windows, GNU/Linux et Mac. Dans les autres chapitres, nous d´ecrivons diff´erentes sources d’informations utiles pour obtenir de l’aide depuis Scilab ou de la part d’autres utilisateurs. Nous d´ecrivons les pages d’aide int´egr´ees et nous analysons les listes de diffusion et le wiki qui sont disponibles en ligne. Enfin, nous prenons un moment pour regarder les d´emonstrations qui sont fournies avec Scilab.
1.1 Introduction
Ce document est un projet open source. Les sources LATEX sont disponibles sur la forge Scilab : http://forge.scilab.org/index.php/p/docintrotoscilab/
Les sources LATEX sont fournies selon les termes de la licence ”Creative Commons Attribution - Partage dans les Mˆemes Conditions 3.0 non transpos´e”: http://creativecommons.org/licenses/by-sa/3.0 Les scripts Scilab sont disponibles sur la forge, `al’int´erieur du projet, dans le sous- r´epertoire scripts. Les scripts sont disponibles sous la licence CeCILL : http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt
1.2 Vue d’ensemble de Scilab Scilab est un langage de programmation associ´e`aune riche collection d’algo- rithmes num´eriques couvrant de nombreux aspects des probl`emes de calcul scienti- fique. Du point de vue logiciel, Scilab est un langage interpr´et´e. Ceci acc´el`ere g´en´era- lement le processus de d´eveloppement, parce que l’utilisateur acc`ede directement `a un langage de haut niveau, avec un riche ensemble de fonctionnalit´esoffertes par la biblioth`eque. Le langage Scilab est destin´e`aˆetre ´etendu afin que des types de don- n´ees « utilisateurs » puissent ˆetre d´efinis par d’´eventuelles op´erations de surcharge. Les utilisateurs de Scilab peuvent d´evelopper leurs propres modules afin de r´esoudre leurs probl`emes particuliers. Le langage Scilab peut compiler et lier dynamiquement d’autres langages tels que Fortran et C : de cette fa¸con, des biblioth`eques externes peuvent ˆetre utilis´eescomme si elles faisaient partie des fonctionnalit´esint´egr´ees de Scilab. Scilab s’interface ´egalement avec LabVIEW, une plate-forme et un l’envi- ronnement de d´eveloppement pour le langage de programmation visuel de National Instruments. Du point de vue de la licence, Scilab est un logiciel gratuit et open source, sous licence Cecill [2]. Le logiciel est distribu´eavec le code source, de telle sorte que
5 l’utilisateur dispose d’un acc`esaux aspects les plus internes de Scilab. La plupart du temps, l’utilisateur t´el´echarge et installe une version binaire de Scilab, car le consortium Scilab fournit les versions ex´ecutables pour Windows, Linux et Mac OS. L’aide en ligne est disponible dans de nombreuses langues. Du point de vue scientifique, Scilab est livr´eavec de nombreuses fonctionnalit´es. Au tout d´ebut de Scilab, les fonctionnalit´esse sont concentr´ees sur l’alg`ebre lin´eaire. Mais, rapidement, leur nombre s’est ´elargi pour couvrir de nombreux domaines de l’informatique scientifique. Voici une courte liste de ses capacit´es: – alg`ebre lin´eaire, matrices creuses ; – polynˆomes et fractions rationnelles ; – interpolation, approximation ; – optimisation lin´eaire, quadratique et non lin´eaire ; – solveur d’´equations diff´erentielles ordinaires et solveur d’´equations diff´eren- tielles alg´ebriques ; – commande classique et robuste, optimisation par in´egalit´ematricielle lin´eaire ; – optimisation diff´erentiable et non diff´erentiable ; – traitement du signal ; – statistiques. Scilab offre de nombreuses fonctionnalit´esgraphiques, y compris un ensemble de fonctions de tra¸cage, qui cr´eent des trac´es2D et 3D ainsi que des interfaces utilisateur. L’environnement Xcos fournit un modeleur et un simulateur hybride de syst`emes dynamiques.
1.3 Comment obtenir et installer Scilab Quelle que soit votre plate-forme (Windows, Linux ou Mac), les binaires Scilab peuvent ˆetre t´el´echarg´esdirectement `apartir de la page d’accueil Scilab :
http://www.scilab.org ou `apartir de l’espace de t´el´echargement :
http://www.scilab.org/download
Les binaires sont fournis pour les plates-formes 32 et 64 bits afin de correspondre `ala machine d’installation cible. Scilab peut ´egalement ˆetre t´el´echarg´esous forme de source, de sorte que vous pouvez compiler Scilab par vous-mˆeme et produire votre propre binaire. Compi- ler Scilab et g´en´erer un binaire est particuli`erement int´eressant lorsque l’on veut comprendre ou d´eboguer une fonction existante, ou lorsqu’on souhaite ajouter une nouvelle fonctionnalit´e. Pour compiler Scilab, certains fichiers binaires pr´erequis sont n´ecessaires, et sont ´egalement pr´evus dans l’espace de t´el´echargement. En outre, un compilateur Fortran et un compilateur C sont n´ecessaires. La compilation de Scilab ne sera pas d´etaill´eedans ce document.
6 Figure 1 – Environnement de travail Scilab sous Windows.
1.3.1 Installer Scilab sous Windows Scilab est distribu´esous forme binaire pour Windows et un programme d’instal- lation est fourni pour que l’installation soit vraiment facile. Si on choisit la langue fran¸caise lors de l’installation, alors Scilab est install´een Fran¸cais. Plus d’informations sur ce th`eme sont donn´eesdans les sections 1.4 et 2.8. L’environnement de travail Scilab est pr´esent´edans la Figure1. Sous Windows, si votre machine est bas´eesur un processeur Intel, la biblio- th`eque Intel Math Kernel Library (MKL) [6] permet `aScilab d’effectuer des calculs num´eriques plus rapides.
1.3.2 Installation de Scilab sous GNU/Linux Sous GNU/Linux, les versions binaires sont disponibles sur le site de Scilab sous la forme d’un fichier .tar.gz. Il n’y a pas besoin de programme d’installation avec Scilab sous GNU/Linux : il suffit de d´ecompresser le fichier dans un r´epertoire cible. Une fois cela fait, le fichier binaire se trouve dans le
7 Pour l’instant, sous GNU/Linux, Scilab est fourni avec une biblioth`eque d’alg`ebre lin´eaire binaire qui garantit la portabilit´e.Sous Linux, Scilab n’est pas fourni avec une version binaire d’ATLAS [1], de sorte que l’alg`ebre lin´eaire est un peu plus lente pour cette plate-forme, par rapport `aWindows.
1.3.3 Installation de Scilab sous Mac OS Sous Mac OS, les versions binaires sont disponibles sur le site de Scilab sous la forme d’un fichier .dmg. Ce binaire fonctionne pour les versions Mac OS `apartir de la version 10.5. Il utilise le programme d’installation de Mac OS, ce qui fournit un processus d’installation classique. Scilab n’est pas disponible sur les syst`emes Power PC. Pour des raisons techniques, la version 5.3 de Scilab pour Mac OS X est livr´ee avec une interface Tcl/Tk d´esactiv´ee.En cons´equence, il y a quelques l´eg`eres li- mitations sur l’utilisation de Scilab sur cette plate-forme. Par exemple, l’interface Scilab/Tcl (TclSci) et l’´editeur graphique ne fonctionnent pas. Ces fonctionnalit´es seront r´e´ecrites en langage Java dans les futures versions de Scilab et ces limitations disparaˆıtront. Pourtant, l’utilisation de Scilab sur un syst`eme Mac OS est facile, et utilise les raccourcis qui sont familiers pour les utilisateurs de cette plate-forme. Par exemple, la console et l’´editeur utilisent la touche Cmd (touche pomme) qui se trouve sur les claviers Mac. En outre, il n’existe aucun clic droit de la souris sur cette plate-forme. A` la place, Scilab est sensible `ala combinaison de touches clavier « Control+clic ». Pour l’instant, sur Mac OS, Scilab est fourni avec une biblioth`eque d’alg`ebre lin´eaire qui est optimis´eeet qui garantit la portabilit´e.Sous Mac OS, Scilab n’est pas fourni avec une version binaire d’ATLAS [1], de sorte que l’alg`ebre lin´eaire est un peu plus lente pour cette plate-forme.
1.4 Comment obtenir de l’aide La fa¸con la plus simple d’obtenir l’aide en ligne int´egr´ee`aScilab est d’utiliser la fonction help. La figure2 pr´esente la fenˆetre d’aide de Scilab. Pour utiliser cette fonction, il suffit de taper ”help” dans la console et d’appuyer sur la touche Entr´ee,comme dans l’exemple suivant : help Supposons que vous vouliez de l’aide sur la fonction optim. Vous pouvez es- sayer de consulter l’aide int´egr´ee,trouver la section ”Optimisation”, puis cliquer sur l’´el´ement optim pour afficher son aide. Une autre possibilit´eest d’utiliser la fonction help, suivie du nom de la fonction, pour laquelle une aide est n´ecessaire, comme ceci : help optim Scilab ouvre automatiquement l’entr´eeassoci´eedans l’aide. Nous pouvons ´egalement utiliser l’aide fournie sur le site Web de Scilab :
http://www.scilab.org/product/man
8 Figure 2 – Fenˆetre d’aide de Scilab.
Cette page contient toujours l’aide de la version mise `ajour du logiciel Scilab. En utilisant la fonction « Recherche » du navigateur, il est possible, la plupart du temps, de trouver rapidement la page d’aide dont on a besoin. Avec cette m´ethode, on peut voir les pages d’aide de plusieurs fonctions Scilab en mˆeme temps (par exemple les pages d’aide des fonctions derivative et optim, afin de pouvoir fournir la fonction de coˆut appropri´ee pour l’optimisation avec optim en calculant les d´eriv´eesavec derivative). Une liste de livres payants et gratuits, de tutoriels en ligne et d’articles est pr´esent´ee sur la page d’accueil Scilab :
http://www.scilab.org/publications
1.5 Listes de diffusion, forum, wiki, rapports de bogue et la Forge La liste de diffusion [email protected] est con¸cue pour toutes les questions d’utilisation de Scilab (les ´echanges ont lieu en anglais). Pour souscrire `acette liste de diffusion, il suffit d’envoyer un e-mail `al’adresse [email protected]. La liste [email protected] est destin´eeaux utilisateurs francophones de Scilab. La liste de diffusion [email protected] se concentre sur le d´eveloppement de Scilab, que ce soit le d´eveloppement du noyau Scilab ou de modules complexes qui interagissent fortement avec le noyau Scilab. Ces listes de diffusion sont archiv´ees`al’adresse :
http://mailinglists.scilab.org
9 Par cons´equent, avant de poser une question, les utilisateurs peuvent regarder dans l’archive si la mˆeme question ou le sujet a d´ej`aobtenu une r´eponse. D’autres listes de diffusions disponible `al’adresse :
http://www.scilab.org/development/ml
Un forum Scilab en fran¸cais est disponible sur Developpez.com `acette adresse : http://www.developpez.net/forums/f1715/environnements-developpement/ autres-edi/scilab
D’autres forums de discussion existent sur Scilab, en particulier le forum anim´e par Equalis :
www.equalis.com ansi que la liste de diffusion Usenet comp.soft-sys.math.scilab, qu’on peut explorer via Google Groupes. Une question peut ˆetre li´ee`aun point technique tr`essp´ecifique, de sorte qu’elle exige une r´eponse qui n’est pas assez g´en´erale pour ˆetre publique. L’adresse sci- [email protected] est pr´evue `acet effet. Les d´eveloppeurs de l’´equipe Scilab fournissent des r´eponses pr´ecises via ce canal de communication. Le wiki Scilab est un outil public pour la lecture et la publication d’informations g´en´erales sur Scilab :
http://wiki.scilab.org
Il est utilis´e`ala fois par les utilisateurs de Scilab et par les d´eveloppeurs pour publier des informations sur Scilab. Du point de vue du d´eveloppeur, il contient un guide ´etape par ´etape des instructions pour compiler Scilab `apartir des sources, les d´ependances de diff´erentes versions de Scilab, les instructions d’utilisation du r´ef´erentiel de code source Scilab, etc. Le ”Scilab’s Bug Tracker” permet de soumettre un rapport `achaque fois qu’un nouveau bogue est trouv´e:
http://bugzilla.scilab.org
Il peut arriver que celui-ci a d´ej`a´et´ed´ecouvert par quelqu’un d’autre. C’est pourquoi il est conseill´ede rechercher dans la base de donn´eesde bogues pour des probl`emes similaires existants avant de signaler un nouveau bogue. Si le bogue n’est pas signal´e `ace jour, c’est une tr`esbonne chose de le signaler, avec un script de test. Ce script de test devrait rester aussi simple que possible pour reproduire le probl`eme et identifier la source du probl`eme. Une fa¸con efficace de se tenir `ajour des informations est d’utiliser des flux RSS. Le flux RSS associ´eavec le site Scilab est
http://www.scilab.org/en/rss_en.xml
Ce canal fournit r´eguli`erement des communiqu´esde presse et les annonces g´en´erales. La Forge Scilab est un outil pour les d´eveloppeurs de modules externes :
10 Figure 3 – Fenˆetre de d´emonstrations.
http://forge.scilab.org
La Forge Scilab est l’endroit o`ul’on peut partager le code source de projets Scilab. Il fournit plusieurs composants pour faciliter le d´eveloppement. La Forge fournit : – un syst`eme de r´evision de code source (SVN ou GIT), – un syst`eme de t´el´echargement (pour distribuer des archives de code source, des documents PDF, des binaires) – des pages documentation (wiki), – un syst`eme de gestion de tickets. Cet outil permet aux d´eveloppeurs de travailler sur un code source commun en tant qu’´equipe, mˆeme si les d´eveloppeurs ne sont pas aux mˆeme endroit physique. En tant qu’utilisateur, on peut utiliser la Forge Scilab pour t´el´echarger des modules ou bien naviguer dans les codes source avec un navigateur internet. En tant que d´eveloppeur, il est obligatoire d’ˆetre familier d’un syst`eme de gestion de version comme SVN ou GIT. Plus de d´etails sont pr´esent´essur [11].
1.6 Obtenir de l’aide `apartir des d´emonstrations Scilab et des macros Le consortium Scilab poss`ede une collection de scripts de d´emonstration, qui sont disponibles `apartir de la console, dans le menu ? > Scilab Demonstrations. La figure3 pr´esente la fenˆetre de d´emonstration. Certaines d´emonstrations sont graphiques, tandis que d’autres sont interactives, ce qui signifie que l’utilisateur doit taper sur la touche
11 o`u
Mais il existe une technique plus simple pour ´editer le code source d’une macro. En effet, on peut utiliser la fonction edit qui, si la fonction pass´eeen argument est une macro, recherche son chemin et ouvre l’´editeur sur le script associ´e.Par exemple, dans le script suivant, on ´edite le code de la fonction derivative : edit derivative Toutefois, cette technique ne fonctionne que sur les macros, et non sur les fonctions qui sont impl´ement´eesdans un code source tel que le C ou le Fortran. La plupart du temps, les macros Scilab sont tr`esbien ´ecrites, en prenant soin de toutes les combinaisons possibles d’arguments d’entr´eeet de sortie et de nombreuses valeurs possibles des arguments d’entr´ee. Souvent, des probl`emes num´eriques diffi- ciles sont r´esolus dans ces scripts. On peut donc s’en inspirer pour l’´elaboration de nos propres scripts, sous r´eserve que cela respecte la licence CeCiLL.
1.7 Exercices Exercice 1.1 (Installer Scilab) Installez la version actuelle du logiciel Scilab sur votre syst`eme (au moment o`uce document est ´ecrit, c’est Scilab v5.4.0). Il est instructif d’installer une version plus ancienne de Scilab, afin de comparer le comportement actuel par rapport `al’ancien. Installez par exemple Scilab 5.3.3 et voyez les diff´erences. Exercice 1.2 (L’aide en ligne : derivative) La fonction derivative calcule la d´eriv´ee d’une fonction num´erique. Le but de cet exercice est de trouver la page d’aide correspondante, par divers moyens. Dans l’aide int´egr´ee, trouvez l’entr´eecorrespondante de la fonction derivative. Trouvez l’entr´ee correspondante dans l’aide en ligne. Utilisez la console pour trouver l’aide. Exercice 1.3 (Poser une question sur le forum) Vous avez probablement d´ej`aune ou plu- sieurs questions. Postez votre question sur le forum Scilab de votre choix ou sur la mailing list [email protected] des utilisateurs.
2 Mise en route
Dans cette section, nous faisons nos premiers pas avec Scilab et nous pr´esentons certaines tˆaches simples que nous pouvons effectuer avec l’interpr´eteur. Il y a plusieurs fa¸cons d’utiliser Scilab et les paragraphes qui suivent pr´esentent trois m´ethodes : – `al’aide de la console en mode interactif ; – en utilisant la fonction exec avec un fichier ; – en utilisant le traitement par lots.
12 Nous pr´esentons ´egalement la gestion des fenˆetres graphiques avec le syst`eme d’ancrage. Enfin, nous pr´esentons deux caract´eristiques principales de Scilab : la localisation, qui fournit des messages et les pages d’aide dans la langue de l’utilisateur et le syst`eme ATOMS, un syst`eme d’empaquetage pour les modules externes.
2.1 La console La premi`ere fa¸con consiste `autiliser Scilab de fa¸coninteractive, en tapant des commandes dans la console, en analysant les r´esultats et en poursuivant ce processus jusqu’`ace que le r´esultat final soit calcul´e.Ce document est con¸cu de telle sorte que les exemples de Scilab qui y sont fournis peuvent ˆetre copi´esdans la console. L’objectif est que le lecteur puisse exp´erimenter le comportement de Scilab par lui- mˆeme. C’est en effet un bon moyen de comprendre le comportement du programme et, la plupart du temps, il s’agit d’un moyen rapide et en douceur d’effectuer le calcul d´esir´e. Dans l’exemple suivant, la fonction disp est utilis´eedans le mode interactif pour imprimer la chaˆıne ”Hello World !”. -->s="Hello World!" s = Hello World! -->disp (s) Hello World! Dans l’exemple pr´ec´edent, nous n’avons pas `asaisir les caract`eres ”-->”qui repr´e- sentent l’invite, g´er´eepar Scilab. Nous tapons simplement la d´eclaration s="Hello World!" avec notre clavier et puis nous appuyons sur la touche Entr´ee. La r´eponse de Scilab est s= ainsi que Hello World!. Puis on tape disp(s) et Scilab r´epond Hello World!. Quand nous saisissons une instruction, nous pouvons utiliser le clavier, comme avec un ´editeur ordinaire. Nous pouvons utiliser les touches fl´ech´ees gauche ← et droite → pour d´eplacer le curseur sur la ligne et utiliser les touches
13 Figure 4 – Autocompl´etion dans la console.
2.2 L’´editeur Scilab fournit un ´editeur pour ´editer facilement les scripts. La figure5 pr´esente l’´editeur lors de l’´edition de l’exemple pr´ec´edent ”Hello World !”. L’´editeur est accessible depuis le menu de la console, sous le menu Applications > Editor, ou depuis la console, comme dans l’exemple suivant : -->editor() Cet ´editeur permet de g`erer plusieurs fichiers en mˆeme temps, comme dans la Figure5, o`ucinq fichiers sont ´edit´esen mˆeme temps. Il y a beaucoup de caract´eristiques qui m´eritent d’ˆetre mentionn´ees`apropos de cet ´editeur. Les caract´eristiques les plus couramment utilis´ees sont dans le menu Execute. – Load into Scilab ex´ecute les instructions dans le fichier courant, comme si on faisait un copier-coller. Ceci implique que les d´eclarations qui ne se terminent pas par un point-virgule ”;” produiront une sortie dans la console ; – Evaluate Selection ex´ecute les instructions qui sont actuellement s´electionn´ees ; – Execute File Into Scilab ex´ecute le fichier, comme si nous avions utilis´ela fonction exec. Les r´esultats qui sont produits dans la console ne sont que ceux qui sont associ´es`ades fonctions d’affichage, comme par exemple la fonction disp. Nous pouvons aussi s´electionner quelques lignes dans le script, faire un clic droit (ou ”Cmd + clic” sous Mac), et obtenir le menu contextuel qui est pr´esent´e`ala Figure6. Le menu Edit fournit une fonctionnalit´etr`esint´eressante. Il s’agit de la fonction Edit > Correct Indentation, qui indente automatiquement la s´election en cours. Cette fonction est tr`espratique, car elle formate les algorithmes, de sorte que les blocs if, for et autres soient faciles `aanalyser. L’´editeur fournit un acc`esrapide `al’aide en ligne. En effet, s´electionnons l’instruc- tion disp, comme dans la figure7. Quand nous faisons un clic droit dans l’´editeur, on obtient le menu contextuel, o`ul’entr´ee Help on selection ouvre la page d’aide associ´ee `ala fonction disp.
14 Figure 5 – The editor.
Figure 6 – Context menu in the editor.
15 Figure 7 – Context help in the editor.
16 Glisser depuis ici et déposer dans la console
Figure 8 – La barre de titre de la fenˆetre source. Afin d’ancrer l’´editeur dans la console, faites glisser la barre de titre de l’´editeur dans la console.
2.3 Ancrage des fenˆetres graphiques L’interface graphique de la version Scilab 5 ont ´et´emis `ajour de sorte que de nombreux composants sont d´esormais bas´essur Java. Cela a un certain nombre d’avantages, notamment la possibilit´ede g´erer l’ancrage des fenˆetres. Le syst`eme d’ancrage 1 des fenˆetres graphiques utilise FlexDock [13], un projet open source fournissant un syst`eme d’ancrage Swing. Supposons que nous ayons `ala fois la console et l’´editeur ouverts dans notre environnement, tel que pr´esent´edans la figure8. Il pourrait ˆetre gˆenant d’avoir deux fenˆetres, car l’une pourrait cacher l’autre, de sorte que nous devions constamment les d´eplacer afin de voir r´eellement ce qui se passe. Le syst`eme FlexDock nous permet de faire glisser et de d´eposer l’´editeur dans la console, pour avoir, finalement, une seule fenˆetre, avec plusieurs sous-fenˆetres. Toutes les fenˆetres Scilab peuvent ˆetre ancr´ees, y compris la console, l’´editeur, le navigateur de variable, l’historique des commandes, l’aide et les fenˆetres de trac´e. Dans la Figure9, nous pr´esentons une situation o`unous avons ancr´equatre fenˆetres dans la fenˆetre de la console. Afin d’ancrer une fenˆetre `aune autre fenˆetre, il faut faire glisser la fenˆetre source et la d´eposer dans la fenˆetre cible (en anglais : ”drag and drop”). Pour ce faire, nous faisons un clic gauche sur la barre de titre de la fenˆetre d’accueil, comme indiqu´edans la figure8. Avant de relˆacher le clic, passons la souris sur la fenˆetre cible et remarquons que la fenˆetre est affich´ee entour´eede pointill´es.Cette fenˆetre ”transparente” indique l’emplacement de la future fenˆetre. Nous pouvons choisir cet emplacement, qui peut ˆetre sur le haut, le bas, la gauche ou la droite de la fenˆetre cible. Une fois que nous avons choisi l’emplacement cible, nous relˆachons le clic, ce qui d´eplace finalement la fenˆetre source dans la fenˆetre cible, comme dans la figure9. Nous pouvons ´egalement lib´erer la fenˆetre source par dessus la fenˆetre de cible,
1. en anglais : docking
17 Cliquer ici pour dé-ancrer Cliquer ici pour fermer la fenêtre
Figure 9 – Actions dans la barre de titre de la fenˆetre d’accueil. La fl`eche ronde dans la barre de titre de la fenˆetre se d´etache de la fenˆetre. La croix ferme la fenˆetre. ce qui cr´eedes onglets, comme dans la figure 10.
2.4 Le navigateur de variable et l’historique des commandes Scilab fournit un navigateur de variable (”variable browser”), qui affiche la liste des variables utilis´ees actuellement dans l’environnement. La figure 11 pr´esente l’´etat de ce navigateur au cours d’une session. Nous pouvons acc´eder `ace navigateur via le menu ”Applications > Variable Browser”, mais la fonction browsevar() a le mˆeme effet. On peut double-cliquer sur une variable, ce qui ouvre l’´editeur de variables, comme dans la Figure 12. On peut alors changer de fa¸con interactive la valeur d’une variable en changeant son contenu dans une cellule. Toutefois, si l’on change le contenu d’une variable `al’int´erieur de la console, il faut actualiser le contenu de la boˆıte de dialogue en appuyant sur le bouton d’actualisation dans la barre d’outils de l’´editeur de variables. La boˆıte de dialogue ”Historique des commandes” permet de naviguer `atravers les commandes que nous avons pr´ec´edemment ex´ecut´ees.Cette boˆıte de dialogue est disponible dans le menu ”Applications > Command History” et est pr´esent´ee dans la Figure 13. On peut s´electionner n’importe quelle commande dans la liste et double-cliquer dessus pour l’ex´ecuter dans la console. Le clic droit ouvre un menu contextuel qui nous permet d’´evaluer la commande ou l’´editer dans l’´editeur.
18 Les onglets des fenêtres ancrées
Figure 10 – Docker des onglets.
Figure 11 – The variable browser.
19 Figure 12 – The variable editor.
Figure 13 – The command history.
20 2.5 Utiliser exec Lorsque plusieurs commandes doivent ˆetre ex´ecut´ees, il peut ˆetre plus commode d’´ecrire ces d´eclarations dans un fichier avec l’´editeur de Scilab. Pour ex´ecuter les commandes situ´ees dans un tel fichier, la fonction exec peut ˆetre utilis´ee,suivie par le nom du script. Ce fichier a g´en´eralement l’extension .sce ou .sci, en fonction de son contenu : – les fichiers ayant l’extension .sci contiennent des fonctions Scilab et ex´ecuter le fichier charge les fonctions dans Scilab (mais n’ex´ecute pas les fonctions) ; – les fichiers ayant l’extension .sce contiennent `ala fois des fonctions Scilab et des instructions ex´ecutables (et ´ex´ecute les instructions). Ex´ecuter un fichier .sce a g´en´eralement pour effet de calculer plusieurs variables et d’afficher les r´esultats dans la console, de cr´eer des trac´es 2D, de lire ou d’´ecrire dans un fichier, etc. Supposons que le contenu du fichier myscript.sce soit le suivant : disp("Hello World !")
Dans la console Scilab, nous pouvons utiliser la fonction exec pour ex´ecuter le contenu de ce script : -->exec("myscript.sce") -->disp("Hello World !") Hello World ! Dans les situations pratiques, telles que le d´ebogage d’un algorithme complexe, le mode interactif est utilis´ela plupart du temps avec une s´equence d’appels aux fonctions exec et disp.
2.6 Commentaires Toute ligne qui commence par deux caract`eres barre oblique ”//” est consid´er´ee par Scilab comme un commentaire et est ignor´ee. // Mon commentaire Dans l’´editeur de Scilab, un commentaire est affich´eavec une couleur et une fonte sp´ecifique. Il est possible de commenter un bloc de plusieurs lignes de code en une seule fois, `al’aide de l’´editeur. Cette fonctionnalit´eest disponible dans le menu ”Format” de l’´editeur : – commenter la s´election (Ctrl+D), – d´ecommenter la s´election (Ctrl+Maj+D).
2.7 Ex´ecution par lot Une autre fa¸cond’utiliser Scilab est depuis la ligne de commande. Plusieurs options de ligne de commande sont disponibles et sont pr´esent´eesdans la figure 14. Quel que soit le syst`eme d’exploitation, les binaires sont situ´esdans le r´eper- toire scilab-X.X.X/bin. Les options de ligne de commande doivent ˆetre jointes `a l’application pour la plate-forme sp´ecifiquement, comme d´ecrit ci-dessous. L’option
21 -nw d´esactive l’affichage de la console graphique. L’option -nwni lance le mode non-graphique : dans ce mode, la console graphique n’est pas affich´eeet les fonc- tionnalit´es graphiques (comme par exemple la fonction plot) sont d´esactiv´ees(les ex´ecuter provoque une erreur). – Sur Windows, deux ex´ecutables binaires sont fournis. Le premier ex´ecutable est WScilex.exe, la console interactive, graphique et usuelle. Cet ex´ecutable correspond `al’icˆone qui se trouve sur le bureau apr`esl’installation de Scilab. Le second ex´ecutable est Scilex.exe, la console non graphique. Avec l’ex´ecutable Scilex.exe, la console Java n’est pas charg´ee et le terminal Windows est utilis´edirectement. Le programme Scilex.exe est sensible aux options -nw et -nwni. – Sur GNU/Linux, le script scilab fournit des options qui configurent son com- portement. Par d´efaut, le mode graphique est lanc´e.Le script scilab est sen- sible aux options -nw et -nwni. Il y a deux ex´ecutables suppl´ementaires sur GNU/Linux : scilab-cli et scilab-adv-cli. L’ex´ecutable scilab-adv-cli est ´equivalent `al’option -nw, tandis que scilab-cli est ´equivalent `al’option -nwni [7]. – Sur Mac OS, le comportement est similaire `ala plate-forme GNU/Linux. Dans la session suivante sur Windows, on lance le programme Scilex.exe avec l’option -nwni. Ensuite, nous ex´ecutons la fonction plot afin de v´erifier que cette fonction n’est pas disponible dans le mode non graphique. C:\Program Files\scilab-5.4.0\bin>Scilex.exe -nwni Initialisation : Chargement de l’environnement de travail -->plot () !-- error 4 Variable non definie : plot L’option de ligne de commande la plus utile est l’option -f, qui ex´ecute les com- mandes depuis un fichier donn´e,une m´ethode g´en´eralement appel´ee traitement par lots (en anglais : ”batch processing”). Supposons que le contenu du fichier myscript2.sce soit le suivant : disp("Hello World !") quit () La fonction quit est ici utilis´eepour sortir de Scilab. En effet, le comportement par d´efaut de Scilab est d’attendre une entr´eeutilisateur : c’est pourquoi la commande quit est utilis´ee,de sorte que la session se termine. Pour ex´ecuter la d´emonstra- tion sous Windows, nous avons cr´e´ele r´epertoire ”C :\scripts” et ´ecrit les instruc- tions dans le fichier C:\scripts\myscript2.sce. La session suivante, ex´ecut´ee`a partir d’un terminal Windows, montre comment utiliser l’option -f pour ex´ecuter le script pr´ec´edent. Notez que nous avons utilis´ele chemin absolu de l’ex´ecutable Scilex.exe. C:\scripts>C:\Program Files\scilab-5.4.0\bin\Scilex.exe -f myscript2.sce Initialisation : Chargement de l’environnement de travail Hello World ! C:\scripts> Pour v´erifier que Scilab reste par d´efaut en mode interactif, nous mettons en commentaire la d´eclaration quit avec la syntaxe ”//”, comme dans le script suivant :
22 -e instruction ex´ecute l’instruction Scilab indiqu´eedans instruction -f fichier ex´ecute le script Scilab donn´edans le fichier -l langue configure la langue de l’utilisateur, par exemple : ”fr” pour le fran¸cais et ”en” pour l’anglais (par d´efaut : ”en”) -mem N d´efinit la taille initiale de la pile -ns si cette option est pr´esente, le fichier de d´emarrage scilab.start n’est pas ex´ecut´e -nb si cette option est pr´esente, alors la banni`ere de bienvenue Scilab ne s’affiche pas -nouserstartup n’ex´ecute pas les fichiers de d´emarrage de l’utilisateur SCIHOME/.scilab ou SCIHOME/scilab.ini -nw d´ebute Scilab en ligne de commande avec des fonctionnalit´es avanc´ees(par exemple graphiques) -nwni d´ebute Scilab en ligne de commande sans fonctionnalit´es avanc´ees(le chargement est plus rapide) -version affiche la version du produit et quitte
Figure 14 – Scilab command line options.
disp("Hello World !") // quit () Si nous tapons la commande Scilex.exe -f myscript2.sce dans le terminal DOS sur Windows, Scilab attendra d´esormais une entr´eeutilisateur, comme pr´evu. Pour quitter, nous tapons interactivement la d´eclaration quit() dans le terminal.
2.8 Localisation Par d´efaut, Scilab fournit ses messages et ses pages d’aide dans la langue anglaise. Mais il peut aussi les fournir en fran¸cais, en chinois, en portugais et en plusieurs autres langues. Dans cette section, nous passons en revue ces ´el´ements et nous voyons leurs effets dans Scilab. Les fonctions de localisation de Scilab changent deux ensembles de fonctionnalit´es diff´erentes dans Scilab : – les messages de l’application de Scilab (menus, messages d’erreur, ...) ; – les pages d’aide. Le tableau 15 pr´esente les langues prises en charge par Scilab pour l’application elle- mˆeme. Pour certaines de ces langues, les pages d’aide de Scilab sont (partiellement) traduites, comme indiqu´eentre parenth`eses. Scilab fournit plusieurs fonctions qui g`erent la localisation. Ces fonctions sont pr´esent´ees dans le tableau 16. Sous Windows, on peut utiliser la fonction setdefaultlanguage, qui prend comme argument d’entr´eeune chaˆıne de caract`eres repr´esentant la langue souhait´ee. Puis nous red´emarrons Scilab pour que les menus de la console soient traduis. Dans l’exemple suivant, nous utilisons la fonction setdefaultlanguage afin de configurer la langue fran¸caise.
23 Messages ca ES catalan - Espagne de DE allemand - Allemagne en US anglais - Etats-Unis´ d’Am´erique es ES espagnol - Castillan - Espagne fr FR fran¸cais - France (avec pages d’aide) it IT italien - Italie ja JP japonais - Japon (avec pages d’aide) pl PL polonais - Pologne pt BR portuguais - Br´esil (avec pages d’aide) ru RU russe - F´ed´eration de Russie uk UA ukrainien - Ukraine zh CN chinois simplifi´e zh TW chinois traditionnel
Figure 15 – Langues support´ees par Scilab.
getdefaultlanguage Renvoie la langue utilis´eepar d´efaut par Scilab. getlanguage Renvoie la langue actuellement utilis´eepar Scilab. setdefaultlanguage D´efinit et enregistre la valeur interne LANGUAGE. setlanguage D´efinit la valeur interne LANGUAGE. dgettext Traduit le texte dans la localisation et le domaine sp´ecifique en cours. gettext Traduit le texte dans la localisation et le domaine en cours. Idem.
Figure 16 – Fonctions pour la localisation.
24 Figure 17 – La page d’aide de bitand en japonais.
setdefaultlanguage("fr_FR") Lorsque nous red´emarrons Scilab, les messages d’erreur sont fournis en fran¸cais : -->1+"foo" !--error 144 Op´eration non d´efinie pour les op´erandes donn´ees. V´erifier ou d´efinir la fonction %s_a_c pour la surcharge. La figure 17 pr´esente la page d’aide de la fonction bitand en japonais. Bien sˆur, la plupart des pages d’aides sont disponibles en fran¸cais, et nous aurions pu regarder la mˆeme page dans la langue de Moli`ere : mais c’est tellement plus spectaculaire avec des kanji ! Sous GNU/Linux, Scilab utilise la langue du syst`eme d’exploitation, de sorte que la plupart des utilisateurs devraient obtenir Scilab dans leur propre langue sans configurer Scilab. Par exemple, dans Ubuntu, l’installation et la configuration de langues peuvent ˆetre faites dans le menu System > Administration > Language Support. Sous GNU/Linux ou Mac OS X, une autre fa¸con de d´emarrer Scilab dans une autre langue est de d´efinir la variable d’environnement LANG. Par exemple, la com- mande suivante dans le terminal Linux lance Scilab en japonais : LANG=ja_JP scilab
25 Pourtant, il peut y avoir des diff´erences entre la langue utilis´eepar GNU/Linux, et la langue utilis´eepar Scilab. Ces diff´erences peuvent provenir d’une mauvaise d´efinition de la langue, o`uScilab ne peut pas trouver le langage qui correspond `acelui attendu. Quand nous lan¸cons Scilab depuis un terminal Linux, le message suivant peut s’afficher : $ Warning: Localization issue. Does not support the locale ’’ (null) C. (process:1516): Gtk-WARNING **: Locale not supported by C library. Using the fallback ’C’ locale. Une cause fr´equente de cette erreur r´eside dans les diff´erentes fa¸cons de d´efinir une langue. Notez, par exemple, qu’il y a une diff´erence entre la langue ”fr”, le fran¸cais, et la langue ”fr FR”, le fran¸cais de France, qui est diff´erent, par exemple, du fran¸cais du Canada, ou encore du fran¸cais de Suisse (parl´een Suisse romande). Dans ce cas, nous devons configurer la langue ”fr FR”, qui est la langue d´etect´eepar Scilab. Une autre raison, en particulier sur la distribution Debian GNU/Linux, est que la locale pourrait ne pas avoir ´et´ecompil´e.Dans ce cas, nous pouvons utiliser la commande dpkg-reconfigure locales dans le terminal Linux. Plus d’informations sur la localisation de Scilab sont fournies `a[8].
2.9 ATOMS, le syst`eme de paquetage de Scilab Dans cette section, nous pr´esentons ATOMS, qui est un ensemble d’outils con¸cus pour installer des boˆıtes `aoutils pr´e-compil´ees. Scilab est con¸cupour ˆetre ´etendu par les utilisateurs, qui peuvent cr´eer de nou- velles fonctions et les utiliser comme si elles ´etaient distribu´eesavec Scilab. Ces extensions sont appel´ees”boˆıtes `aoutils” ou ”modules externes”. La cr´eation d’un nouveau module, avec ses pages d’aide associ´eeset ses tests unitaires, est relative- ment simple et c’est une partie du succ`esde Scilab. Cependant, la plupart des modules ne peuvent pas ˆetre utilis´esdirectement sous forme de source : le module doit ˆetre compil´epour que les fichiers binaires puissent ˆetre charg´es dans Scilab. Cette ´etape de compilation n’est pas simple et peut-ˆetre mˆeme impossible pour les utilisateurs qui veulent utiliser un module bas´esur un code source C ou Fortran et qui n’ont pas de compilateur. C’est l’un des probl`emes qu’a r´esolu ATOMS : les modules sont fournis sous forme binaires, ce qui permet `al’uti- lisateur d’installer un module sans compilation et sans probl`emes de compatibilit´e avec Scilab. Une caract´eristique suppl´ementaire pour l’utilisateur est que la plupart des mo- dules sont disponibles sur toutes les plates-formes : les d´eveloppeurs b´en´eficient de la ferme de compilation du Consortium Scilab et les utilisateurs b´en´eficient d’un module qui est, la plupart du temps, assur´ed’ˆetre multi-plateforme. Lorsqu’un d´e- veloppeur met un nouveau module ATOMS `ala disposition des utilisateurs, on dit qu’il a ATOMiS´e le module 2. ATOMS est le syst`eme de gestion de modules externes de Scilab. Avec cet ou- til, les modules Scilab existants (c’est-`a-dire pr´e-compil´es), peuvent ˆetre t´el´echarg´es,
2. et ¸canous fait toujours rire...
26 Image Processing Design ("IPD") Fonctions par la d´etection d’objets Scilab Image and Video Processing ("SIVP") Traitement d’image et de vid´eo Plotting library ("plotlib") Une librairie graphique similaire `aMatlab Scilab 2 C ("scilab2c") Convertir un code Scilab en C Module Lyc´ee ("module_lycee") Scilab pour les lyc´ees Guimaker ("guimaker") Des interfaces graphiques utilisateur avec un minimum de programmation Time Frequency ("stftb") Analyse de signaux non-stationnaires CelestLab ("celestlab") M´ecanique spatiale Scilab XLL ("Scilab_XLL") Un compl´ementXll pour Excel Wavelet ("swt") Ondelettes
Figure 18 – Les 10 modules ATOMS les plus t´el´echarg´es.
27 install´eset charg´es.Les d´ependances sont g´er´ees, de sorte que si un module A d´e- pend d’un module B, l’installation du module A installe automatiquement le module B. Ceci est similaire au syst`eme de paquetage disponible dans la plupart des dis- tributions GNU/Linux/BSD. Les modules ATOMS sont disponibles sur tous les syst`emes d’exploitation sur lesquels Scilab est disponible, c’est-`a-dire sous Microsoft Windows, GNU/Linux et Mac OS X. Par exemple, lorsqu’un module ATOMS est install´esur Scilab s’ex´ecutant sur un syst`eme d’exploitation MS Windows, le module pr´e-compil´ecorrespondant `ala version de MS Windows du module est automati- quement install´e.Le portail web pour ATOMS est :
http://atoms.scilab.org
Ce portail pr´esente la liste compl`ete des modules ATOMS et laisse les d´evelop- peurs de modules mettre en ligne leurs nouveaux modules. La figure 18 pr´esente les dix modules ATOMS les plus t´el´echarg´es. Cette liste est un choix arbitraire de modules : plus de cent modules sont actuellement disponibles sur ATOMS. Il y a deux fa¸cons d’installer un module ATOMS. La premi`ere m´ethode consiste `autiliser la fonction atomsGui, qui ouvre une interface graphique 3 qui permet de naviguer `atravers tous les modules ATOMS disponibles. Cet outil est ´egalement dis- ponible `apartir du menu ”Applications > Module manager - ATOMS” de la console Scilab. Dans l’interface graphique, nous pouvons lire la description du module et cli- quer simplement sur le bouton ”Installer”. La figure 19 pr´esente l’interface graphique ATOMS. La seconde mani`ere est d’utiliser la fonction atomsInstall, qui prend le nom d’un module comme argument d’entr´ee.Par exemple, pour installer le module ”ma- kematrix”, on peut ex´ecuter l’instruction : atomsInstall("makematrix") Puis Scilab doit ˆetre red´emarr´eet le module ”makematrix” (et ses d´ependances, le cas ´ech´eant) est automatiquement charg´e. Plus de d´etails sur ATOMS sont disponibles `a[9].
2.10 Exercises Exercice 2.1 (La console) Tapez la commande suivante dans la console. atoms Maintenant, tapez sur la touche de tabulation. Que se passe-t-il ? Maintenant, tapez la lettre ”I”, puis tapez `anouveau sur la tabulation. Que se passe-t-il ? Exercice 2.2 (Utiliser exec) Lorsque nous d´eveloppons un script Scilab, nous utilisons souvent la fonction exec en combinaison avec la fonction ls, qui affiche la liste des fichiers et r´epertoires dans le r´epertoire courant. Nous pouvons ´egalement utiliser la commande pwd, qui affiche le r´epertoire courant 4. La variable SCI contient le nom du r´epertoire d’installation de Scilab. Nous l’utilisons tr`essouvent pour ex´ecuter les scripts qui sont fournis dans Scilab. Tapez les instructions suivantes dans la console et voyez ce qui se passe. pwd SCI
3. en anglais, Graphical User Interface 4. en anglais, Print Working Directory
28 Figure 19 – L’interface graphique ATOMS.
29 ls(fullfile(SCI,"modules")) ls(fullfile(SCI,"modules","graphics","demos")) ls(fullfile(SCI,"modules","graphics","demos","2d_3d_plots")) dname = fullfile(SCI,"modules","graphics","demos","2d_3d_plots"); filename = fullfile(dname,"contourf.dem.sce"); exec(filename) exec(filename);
3 Basic elements of the language
Scilab is an interpreted language, which means that we can manipulate variables in a very dynamic way. In this section, we present the basic features of the language, that is, we show how to create a real variable, and what elementary mathematical functions can be applied to a real variable. If Scilab provided only these features, it would only be a super desktop calculator. Fortunately, it is a lot more and this is the subject of the remaining sections, where we will show how to manage other types of variables, that is booleans, complex numbers, integers and strings. It seems strange at first, but it is worth to state it right from the start : in Scilab, everything is a matrix. To be more accurate, we should write : all real, complex, boolean, integer, string and polynomial variables are matrices. Lists and other complex data structures (such as tlists and mlists) are not matrices (but can contain matrices). These complex data structures will not be presented in this document. This is why we could begin by presenting matrices. Still, we choose to present basic data types first, because Scilab matrices are in fact a special organization of these basic building blocks. In Scilab, we can manage real and complex numbers. This always leads to some confusion if the context is not clear enough. In the following, when we write real variable, we will refer to a variable which content is not complex. Complex variables will be covered in section 3.7 as a special case of real variables. In most cases, real variables and complex variables behave in a very similar way, although some extra care must be taken when complex data is to be processed. Because it would make the presentation cumbersome, we simplify most of the discussions by considering only real variables, taking extra care with complex variables only when needed.
3.1 Creating real variables In this section, we create real variables and perform simple operations with them. Scilab is an interpreted language, which implies that there is no need to declare a variable before using it. Variables are created at the moment where they are first set. In the following example, we create and set the real variable x to 1 and perform a multiplication on this variable. In Scilab, the ”=” operator means that we want to set the variable on the left hand side to the value associated with the right hand side (it is not the comparison operator, which syntax is associated with the ”==” operator).
30 + addition - subtraction ∗ multiplication / right division, i.e. x/y = xy−1 \ left division, i.e. x\y = x−1y ˆ power, i.e. xy ∗∗ power (same as ˆ) ’ transpose conjugate
Figure 20 – Scilab elementary mathematical operators.
-->x=1 x = 1. -->x = x * 2 x = 2. The value of the variable is displayed each time a statement is executed. That behavior can be suppressed if the line ends with the semicolon ”;” character, as in the following example. -->y =1; -->y=y *2; All the common algebraic operators presented in figure 20 are available in Scilab. Notice that the power operator is represented by the hat ”ˆ” character so that com- puting x2 in Scilab is performed by the ”xˆ2”expression or equivalently by the ”x**2” expression. The single quote ”’ ” operator will be presented in more depth in sec- tion 3.7, which presents complex numbers. It will be reviewed again in section 4.12, which deals with the conjugate transpose of a matrix.
3.2 Variable names Variable names may be as long as the user wants, but only the first 24 characters are taken into account in Scilab. For consistency, we should consider only variable names which are not made of more than 24 characters. All ASCII letters from ”a” to ”z”, from ”A” to ”Z” and digits from ”0” to ”9” are allowed, with the additional characters ”%”, ”_”, ”#”, ”!”, ”$”, ”?”. Notice though that variable names, whose first letter is ”%”, have a special meaning in Scilab, as we will see in section 3.5, which presents the pre-defined mathematical variables. Scilab is case sensitive, which means that upper and lower case letters are consi- dered to be different by Scilab. In the following script, we define the two variables A and a and check that these two variables are considered to be different by Scilab. -->A = 2 A = 2. -->a = 1 a =
31 1. -->A A = 2. -->a a = 1.
3.3 Comments and continuation lines Any line which begins with two slashes ”//” is considered by Scilab as a comment and is ignored. There is no possibility to comment out a block of lines, such as with the ”/* ... */” comments in the C language. When an executable statement is too long to be written on a single line, the second and subsequent lines are called continuation lines. In Scilab, any line which ends with two dots is considered to be the start of a new continuation line. In the following session, we give examples of Scilab comments and continuation lines. -->// This is my comment. -->x =1.. - - >+2.. - - >+3.. -->+4 x = 10. See the section 3.13 for more details on this topic.
3.4 Elementary mathematical functions Tables 21 and 22 present a list of elementary mathematical functions. Most of these functions take one input argument and return one output argument. These functions are vectorized in the sense that their input and output arguments are matrices. As a consequence, we can compute data with higher performance, without any loop. In the following example, we use the cos and sin functions and check the equality cos(x)2 + sin(x)2 = 1. -->x = cos(2) x = - 0.4161468 -->y = sin(2) y = 0.9092974 -->x ^2+ y^2 ans = 1.
3.5 Pre-defined mathematical variables In Scilab, several mathematical variables are pre-defined variables, whose names begin with a percent ”%” character. The variables which have a mathematical mea-
32 acos acosd acosh acoshm acosm acot acotd acoth acsc acscd acsch asec asecd asech asin asind asinh asinhm asinm atan atand atanh atanhm atanm cos cosd cosh coshm cosm cotd cotg coth cothm csc cscd csch sec secd sech sin sinc sind sinh sinhm sinm tan tand tanh tanhm tanm
Figure 21 – Scilab elementary mathematical functions : trigonometry.
exp expm log log10 log1p log2 logm max maxi min mini modulo pmodulo sign signm sqrt sqrtm
Figure 22 – Scilab elementary mathematical functions : other functions. ning are summarized in figure 23. In the following example, we use the variable %pi to check the mathematical equality cos(x)2 + sin(x)2 = 1. -->c=cos(%pi) c = - 1. -->s=sin(%pi) s = 1.225D -16 -->c ^2+ s^2 ans = 1. The fact that the computed value of sin(π) is not exactly equal to 0 is a conse- quence of the fact that Scilab stores the real numbers with floating point numbers, that is, with limited precision.
3.6 Booleans Boolean variables can store true or false values. In Scilab, true is written with %t or %T and false is written with %f or %F. Figure 24 presents the several comparison operators which are available in Scilab. These operators return boolean values and take as input arguments all basic data types (i.e. real and complex numbers, integers and strings). The comparison operators are reviewed in section 4.14, where the
%i the imaginary number i %e Euler’s number e %pi the mathematical constant π
Figure 23 – Pre-defined mathematical variables.
33 a&b logical and a|b logical or ∼a logical not a==b true if the two expressions are equal a∼=b or a<>b true if the two expressions are different ab true if a is greater than b a<=b true if a is lower or equal to b a>=b true if a is greater or equal to b
Figure 24 – Comparison operators.
real real part imag imaginary part imult multiplication by i, the imaginary unitary isreal returns true if the variable has no complex entry
Figure 25 – Scilab complex numbers elementary functions. emphasis is made on comparison of matrices. In the following example, we perform some algebraic computations with Scilab booleans. -->a=%T a = T -->b = ( 0 == 1 ) b = F -->a&b ans = F
3.7 Complex numbers Scilab provides complex numbers, which are stored as pairs of floating point num- bers. The pre-defined variable %i represents the mathematical imaginary number i which satisfies i2 = −1. All elementary functions previously presented before, such as sin for example, are overloaded for complex numbers. This means that if their input argument is a complex number, the output is a complex number. Figure 25 presents functions which manage complex numbers. In the following example, we set the variable x to 1 + i, and perform several basic operations on it, such as retrieving its real and imaginary parts. Notice how the single quote operator, denoted by ”’ ”, is used to compute the conjugate of a complex number. -->x= 1+ %i x =
34 int8 int16 int32 uint8 uint16 uint32
Figure 26 – Scilab integer data types.
1. + i -->isreal(x) ans = F -->x’ ans = 1. - i -->y=1- %i y = 1. - i -->real (y) ans = 1. -->imag (y) ans = - 1. We finally check that the equality (1+i)(1−i) = 1−i2 = 2 is verified by Scilab. -->x*y ans = 2.
3.8 Integers We can create various types of integer variables with Scilab. The functions that create such integers are presented in figure 26. In this section, we first review the basic features of integers, which are associated with a particular range of values. Then we analyze the conversion between integers. In the final section, we consider the behaviour of integers at the boundaries and focus on portability issues.
3.8.1 Overview of integers There is a direct link between the number of bits used to store an integer and the range of values that the integer can manage. The range of an integer variable depends on the number of its bits. – An n-bit signed integer takes its values from the range [−2n−1, 2n−1 − 1]. – An n-bit unsigned integer takes its values from the range [0, 2n − 1]. For example, an 8-bit signed integer, as created by the int8 function, can store values in the range [−27, 27 − 1], which simplifies to [−128, 127]. The map from the type of integer to the corresponding range of values is presented in figure 27. In the following session, we check that an unsigned 32-bit integer has values inside the range [0, 232 − 1], which simplifies to [0, 4294967295].
35 y=int8(x) a 8-bit signed integer in [−27, 27 − 1] = [−128, 127] y=uint8(x) a 8-bit unsigned integer in [0, 28 − 1] = [0, 255] y=int16(x) a 16-bit signed integer in [−215, 215 − 1] = [−32768, 32767] y=uint16(x) a 16-bit unsigned integer in [0, 216 − 1] = [0, 65535] y=int32(x) a 32-bit signed integer in [−231, 231 − 1] y=uint32(x) a 32-bit unsigned integer in [0, 232 − 1] = [0, 4294967295]
Figure 27 – Scilab integer functions.
iconvert conversion to integer representation inttype type of integers
Figure 28 – Scilab integer conversion functions.
-->format(25) -->n =32 n = 32. -->2^n - 1 ans = 4294967295. -->i = uint32(0) i = 0 -->j=i -1 j = 4294967295 -->k = j+1 k = 0
3.8.2 Conversions between integers There are functions which convert to and from integer data types. These functions are presented in figure 28. The inttype function inquires about the type of an integer variable. Depending on the type, the function returns a corresponding value, as summarised in table 29.
inttype(x) Type 1 8-bit signed integer 2 16-bit signed integer 4 32-bit signed integer 11 8-bit unsigned integer 12 16-bit unsigned integer 14 32-bit unsigned integer
Figure 29 – Types of integers returned by the inttype function.
36 When two integers are added, the types of the operands are analyzed : the re- sulting integer type is the larger, so that the result can be stored. In the following script, we create an 8-bit integer i (which is associated with inttype=1) and a 16-bit integer j (which is associated with inttype=2). The result is stored in k, a 16-bit signed integer. -->i=int8(1) i = 1 -->inttype(i) ans = 1. -->j=int16(2) j = 2 -->inttype(j) ans = 2. -->k=i+j k = 3 -->inttype(k) ans = 2.
3.8.3 Circular integers and portability issues The behaviour of integers at the range boundaries deserves a particular analysis, since it is different from software to software. In Scilab, the behaviour is circular, that is, if an integer at the upper limit is incremented, the next value is at the lower limit. An example of circular behaviour is given in the following session, where -->uint8(0+(-4:4)) ans = 252 253 254 255 0 1 2 3 4 -->uint8(2^8+(-4:4)) ans = 252 253 254 255 0 1 2 3 4 -->int8(2^7+(-4:4)) ans = 124 125 126 127 -128 -127 -126 -125 -124 This is in contrast with other mathematical packages, such as Octave or Matlab. In these packages, if an integer is at the upper limit, the next integer stays at the upper limit. In the following Octave session, we execute the same computations as previously. octave-3.2.4.exe:1> uint8(0+(-4:4)) ans = 0 0 0 0 0 1 2 3 4 octave-3.2.4.exe:5> uint8(2^8+(-4:4)) ans = 252 253 254 255 255 255 255 255 255 octave-3.2.4.exe:2> int8(2^7+(-4:4)) ans =
37 124 125 126 127 127 127 127 127 127 The Scilab circular way gives a greater flexibility in the processing of integers, since we can write algorithms with fewer if statements. But these algorithms must be checked, particularly if they involve the boundaries of the integer range. Moreo- ver, translating a script from another computation system into Scilab may lead to different results.
3.9 Floating point integers In Scilab, the default numerical variable is the double, that is the 64-bit floating point number. This is true even if we write what is mathematically an integer. In [12], Cleve Moler call this number a ”flint”, a short for floating point integer. In practice, we can safely store integers in the interval [−252, 252] into doubles. We emphasize that, provided that all input, intermediate and output integer values are strictly inside the [−252, 252] interval, the integer computations are exact. For example, in the following example, we perform the exact addition of two large integers which remain in the ”safe” interval. -->format(25) -->a= 2^40 - 12 a = 1099511627764. -->b= 2^45 + 3 b = 35184372088835. -->c = a + b c = 36283883716599. Instead, when we perform computations outside this interval, we may have unex- pected results. For example, in the following session, we see that additions involving terms slightly greater than 253 produce only even values. -->format(25) -->(2^53 + (1:10))’ ans = 9007199254740992. 9007199254740994. 9007199254740996. 9007199254740996. 9007199254740996. 9007199254740998. 9007199254741000. 9007199254741000. 9007199254741000. 9007199254741002. In the following session, we compute 252 using the floating point integer 2 in the first case, and using the 16-bit integer 2 in the second case. In the first case, no overflow occurs, even if the number is at the limit of 64-bit floating point numbers. In the second case, the result is completely wrong, because the number 252 cannot be represented as a 16-bit integer.
38 - - >2^52 ans = 4503599627370496. -->uint16(2^52) ans = 0 In section 4.15, we analyze the issues which arise when indexes involved to access the elements of a matrix are doubles.
3.10 The ans variable Whenever we make a computation and do not store the result into an output variable, the result is stored in the default ans variable. Once it is defined, we can use this variable as any other Scilab variable. In the following session, we compute exp(3) so that the result is stored in the ans variable. Then we use its content as a regular variable. -->exp (3) ans = 20.08553692318766792368 -->t = log(ans) t = 3. In general, the ans variable should be used only in an interactive session, in order to progress in the computation without defining a new variable. For example, we may have forgotten to store the result of an interesting computation and do not want to recompute the result. This might be the case after a long sequence of trials and errors, where we experimented several ways to get the result without taking care of actually storing the result. In this interactive case, using ans may save some human (or machine) time. Instead, if we are developing a script used in a non-interactive way, it is a bad practice to rely on the ans variable and we should store the results in regular variables.
3.11 Strings Strings can be stored in variables, provided that they are delimited by double quotes ”" ”. The concatenation operation is available from the ”+” operator. In the following Scilab session, we define two strings and then concatenate them with the ”+” operator. -->x = " foo " x = foo -->y=" bar " y = bar -->x+y ans = foobar There are many functions which process strings, including regular expressions. We will not give further details about this topic in this document.
39 3.12 Dynamic type of variables When we create and manage variables, Scilab changes the variable type dynami- cally. This means that we can create a real value, and then put a string variable in it, as presented in the following session. -->x=1 x = 1. -->x+1 ans = 2. -->x=" foo " x = foo -->x+" bar " ans = foobar We emphasize here that Scilab is not a typed language, that is, we do not have to declare the type of a variable before setting its content. Moreover, the type of a variable can change during the life of the variable.
3.13 Notes and references The coding style that we presented in this section and that we will use in the remaining of the document is standard in the context of Scilab. This style is based on common practices and on the document [10], which defines code conventions for the Scilab programming language. The convention defines the way of defining new functions (e.g. their names, the name of the arguments, etc...), the indentation style, the quotes, the line length, the loop indices, the number of statements per line, and many other details. In the section 3.3, we presented the way to define comments and continuation lines and stated that any line which ends with two dots is a continuation line. In fact, the interpreter considers that any line which ends with more that two dots is a continuation line. This implies that we can use continuation lines with three dots, or more. This feature is maintained only for backward compatibility, does not correspond to the Scilab coding style and should not be used in new Scilab scripts. In the section 3.11, we presented the double quote ”" ” to defined strings. In fact, the interpreter can also use strings defined with single quotes. But this may lead to bugs, because there might be a confusion with the transpose operator (see section 4.12). This feature is maintained for backward compatibility and should not be used in new scripts.
3.14 Exercises Exercice 3.1 (Precedence of operators) What are the results of the following computations (think about it before trying in Scilab) ? 2 * 3 + 4 2 + 3 * 4 2 / 3 + 4
40 2 + 3 / 4
Exercice 3.2 (Parentheses) What are the results of the following computations (think about it before trying in Scilab) ? 2 * (3 + 4) (2 + 3) * 4 (2 + 3) / 4 3 / (2 + 4)
Exercice 3.3 (Exponents) What are the results of the following computations (think about it before trying in Scilab) ? 1.23456789d10 1.23456789e10 1.23456789e-5
Exercice 3.4 (Functions) What are the results of the following computations (think about it before trying in Scilab) ? sqrt (4) sqrt (9) sqrt ( -1) sqrt ( -2) exp (1) log(exp(2)) exp(log(2)) 10^2 log10(10^2) 10^log10(2) sign (2) sign ( -2) sign (0)
Exercice 3.5 (Trigonometry) What are the results of the following computations (think about it before trying in Scilab) ? cos (0) sin (0) cos ( %pi ) sin ( %pi ) cos(%pi/4) - sin(%pi/4)
4 Matrices
In the Scilab language, matrices play a central role. In this section, we introduce Scilab matrices and present how to create and query matrices. We also analyze how to access the elements of a matrix, either element by element, or by higher-level operations.
4.1 Overview In Scilab, the basic data type is the matrix, which is defined by : – the number of rows,
41 – the number of columns, – the type of data. The data type can be real, integer, boolean, string and polynomial. When two ma- trices have the same number of rows and columns, we say that the two matrices have the same shape. In Scilab, vectors are a particular case of matrices, where the number of rows (or the number of columns) is equal to 1. Simple scalar variables do not exist in Scilab : a scalar variable is a matrix with 1 row and 1 column. This is why in this chapter, when we analyze the behavior of Scilab matrices, there is the same behavior for row or column vectors (i.e. n×1 or 1×n matrices) as well as scalars (i.e. 1×1 matrices). It is fair to say that Scilab was designed mainly for matrices of real variables, with the goal of performing linear algebra operations within a high-level language. By design, Scilab was created to be able to perform matrix operations as fast as possible. The building block for this feature is that Scilab matrices are stored in an internal data structure which can be managed at the interpreter level. Most basic linear algebra operations, such as addition, subtraction, transpose or dot product are performed by a compiled, optimized, source code. These operations are performed with the common operators ”+”, ”-”, ”*” and the single quote ”’ ”, so that, at the Scilab level, the source code is both simple and fast. With these high-level operators, most matrix algorithms do not require to use loops. In fact, a Scilab script which performs the same operations with loops is typically from 10 to 100 times slower. This feature of Scilab is known as the vec- torization. In order to get a fast implementation of a given algorithm, the Scilab developer should always use high-level operations, so that each statement processes a matrix (or a vector) instead of a scalar. More complex tasks of linear algebra, such as the resolution of systems of li- near equations Ax = b, various decompositions (for example Gauss partial pivotal PA = LU), eigenvalue/eigenvector computations, are also performed by compiled and optimized source codes. These operations are performed by common operators like the slash ”/” or backslash ”\” or with functions like spec, which computes ei- genvalues and eigenvectors.
4.2 Create a matrix of real values There is a simple and efficient syntax to create a matrix with given values. The following is the list of symbols used to define a matrix : – square brackets ”[” and ”]” mark the beginning and the end of the matrix, – commas ”,” separate the values in different columns, – semicolons ”;” separate the values of different rows. The following syntax can be used to define a matrix, where blank spaces are optional (but make the line easier to read) and ”...” denotes intermediate values : A = [a11, a12, ..., a1n; ... ; an1, an2, ..., ann]. In the following example, we create a 2 × 3 matrix of real values. -->A=[1 ,2,3;4,5,6] A = 1. 2. 3.
42 eye identity matrix linspace linearly spaced vector ones matrix made of ones zeros matrix made of zeros testmatrix generate some particular matrices grand random number generator rand random number generator
Figure 30 – Functions which generate matrices.
4. 5. 6. A simpler syntax is available, which does not require to use the comma and semicolon characters. When creating a matrix, the blank space separates the columns while the new line separates the rows, as in the following syntax : A = [a11 a12 ... a1n a21 a22 ... a2n ... an1 an2 ... ann] This lightens considerably the management of matrices, as in the following session. -->A = [1 2 3 -->4 5 6] A = 1. 2. 3. 4. 5. 6. The previous syntax for matrices is useful in the situations where matrices are to be written into data files, because it simplifies the human reading (and checking) of the values in the file, and simplifies the reading of the matrix in Scilab. Several Scilab commands create matrices from a given size, i.e. from a given number of rows and columns. These functions are presented in figure 30. The most commonly used are eye, zeros and ones. These commands take two input argu- ments, the number of rows and columns of the matrix to generate. -->A = ones(2,3) A = 1. 1. 1. 1. 1. 1.
4.3 The empty matrix [] An empty matrix can be created by using empty square brackets, as in the following session, where we create a 0 × 0 matrix. -->A =[] A = [] This syntax deletes the content of a matrix, so that the associated memory is freed.
43 -->A = ones(100,100); -->A = [] A = []
4.4 Query matrices The functions in figure 31 query or update a matrix. The size function returns the two output arguments nr and nc, which are the number of rows and the number of columns. -->A = ones(2,3) A = 1. 1. 1. 1. 1. 1. -->[nr,nc]=size(A) nc = 3. nr = 2. The size function is of important practical value when we design a function, since the processing that we must perform on a given matrix may depend on its shape. For example, to compute the norm of a given matrix, different algorithms may be used depending on if the matrix is a column vector with size nr × 1 and nr > 0, a row vector with size 1 × nc and nc > 0, or a general matrix with size nr × nc and nr, nc > 1. The size function has also the following syntax nr = size( A , sel ) which gets only the number of rows or the number of columns and where sel can have the following values – sel=1 or sel="r", returns the number of rows, – sel=2 or sel="c", returns the number of columns. – sel="*", returns the total number of elements, that is, the number of columns times the number of rows. In the following session, we use the size function in order to compute the total number of elements of a matrix. -->A = ones(2,3) A = 1. 1. 1. 1. 1. 1. -->size(A,"*") ans = 6.
4.5 Accessing the elements of a matrix There are several methods to access the elements of a matrix A : – the whole matrix, with the A syntax,
44 size size of objects matrix reshape a vector or a matrix to a different size matrix resize_matrix create a new matrix with a different size
Figure 31 – Functions which query or modify matrices.
– element by element with the A(i,j) syntax, – a range of subscript indices with the colon ”:” operator. The colon operator will be reviewed in the next section. To make a global access to all the elements of the matrix, the simple variable name, for example A, can be used. All elementary algebra operations are available for matrices, such as the addition with ”+”, subtraction with ”-”, provided that the two matrices have the same size. In the following script, we add all the elements of two matrices. -->A = ones(2,3) A = 1. 1. 1. 1. 1. 1. -->B = 2 * ones(2,3) B = 2. 2. 2. 2. 2. 2. -->A+B ans = 3. 3. 3. 3. 3. 3. One element of a matrix can be accessed directly with the A(i,j) syntax, pro- vided that i and j are valid subscripts. We emphasize that, by default, the first subscript of a matrix is 1. This contrasts with other languages, such as the C language for instance, where the first subscript is 0. For example, assume that A is an nr × nc matrix, where nr is the number of rows and nc is the number of columns. Therefore, the value A(i,j) has a sense only if the subscript i and j satisfy 1 ≤ i ≤ nr and 1 ≤ j ≤ nc. If the subscript are not valid, an error is generated, as in the following session. -->A = ones(2,3) A = 1. 1. 1. 1. 1. 1. -->A(1 ,1) ans = 1. -->A (12 ,1) !-- error 21 Invalid index. -->A(0 ,1) !-- error 21 Invalid index. Direct access to matrix elements with the A(i,j) syntax should be used only when no other higher-level Scilab commands can be used. Indeed, Scilab provides
45 many features which produce simpler and faster computations, based on vectori- zation. One of these features is the colon ”:” operator, which is very important in practical situations.
4.6 The colon ”:” operator The simplest syntax of the colon operator is the following : v = i:j where i is the starting subscript and j is the ending subscript with i ≤ j. This creates the vector v = (i, i + 1, . . . , j). In the following session, we create a vector of subscripts from 2 to 4 in one statement. -->v = 2:4 v = 2. 3. 4. The complete syntax configures the increment used when generating the sub- scripts, i.e. the step. The complete syntax for the colon operator is v = i:s:j where i is the starting subscript, j is the ending subscript and s is the step. This command creates the vector v = (i, i + s, i + 2s, . . . , i + ns) where n is the greatest integer such that i + ns ≤ j. If s divides j − i, then the last subscript in the vector of subscripts is j. In other cases, we have i + ns < j. While in most situations, the step s is positive, it might also be negative. In the following session, we create a vector of increasing subscripts from 3 to 10 with a step equal to 2. -->v = 3:2:10 v = 3. 5. 7. 9. Notice that the last value in the vector v is i + ns = 9, which is smaller than j = 10. In the following session, we present two examples where the step is negative. In the first case, the colon operator generates decreasing subscripts from 10 to 4. In the second example, the colon operator generates an empty matrix because there are no values lower than 3 and greater than 10 at the same time. -->v = 10:-2:3 v = 10. 8. 6. 4. -->v = 3:-2:10 v = [] With a vector of subscripts, we can access the elements of a matrix in a given range, as with the following simplified syntax A(i:j,k:l) where i,j,k,l are starting and ending subscripts. The complete syntax is A(i:s:j,k:t:l),
46 where s and t are the steps. For example, suppose that A is a 4 × 5 matrix, and that we want to access the elements ai,j for i = 1, 2 and j = 3, 4. With the Scilab language, this can be done in just one statement, by using the syntax A(1:2,3:4), as showed in the following session. -->A = testmatrix("hilb",5) A =
25. -300. 1050. -1400. 630. - 300. 4800. - 18900. 26880. - 12600. 1050. - 18900. 79380. - 117600. 56700. - 1400. 26880. - 117600. 179200. - 88200. 630. - 12600. 56700. - 88200. 44100. -->A(1:2,3:4) ans = 1050. - 1400. - 18900. 26880. In some circumstances, it may happen that the subscripts are the result of a com- putation. For example, the algorithm may be based on a loop where the subscripts are updated regularly. In these cases, the syntax A(vi ,vj), where vi,vj are vectors of subscripts, can be used to designate the elements of A whose subscripts are the elements of vi and vj. That syntax is illustrated in the following example. -->A = testmatrix("hilb",5) A =
25. -300. 1050. -1400. 630. - 300. 4800. - 18900. 26880. - 12600. 1050. - 18900. 79380. - 117600. 56700. - 1400. 26880. - 117600. 179200. - 88200. 630. - 12600. 56700. - 88200. 44100. -->vi =1:2 vi = 1. 2. -->vj =3:4 vj = 3. 4. -->A(vi,vj) ans = 1050. - 1400. - 18900. 26880. -->vi=vi +1 vi = 2. 3. -->vj=vj +1 vj = 4. 5. -->A(vi,vj) ans = 26880. - 12600. - 117600. 56700.
47 A the whole matrix A(:,:) the whole matrix A(i:j,k) the elements at rows from i to j, at column k A(i,j:k) the elements at row i, at columns from j to k A(i,:) the row i A(:,j) the column j
Figure 32 – Access to a matrix with the colon ”:” operator.
There are many variations on this syntax, and figure 32 presents some of the possible combinations. For example, in the following session, we use the colon operator in order to interchange two rows of the matrix A. -->A = testmatrix("hilb",3) A = 9. - 36. 30. - 36. 192. - 180. 30. - 180. 180. -->A([1 2],:) = A([2 1],:) A = - 36. 192. - 180. 9. - 36. 30. 30. - 180. 180. We could also interchange the columns of the matrix A with the statement A(:,[3 1 2]). In this section we have analyzed several practical use of the colon operator. Indeed, this operator is used in many scripts where performance matters, since it accesses many elements of a matrix in just one statement. This is associated with the vectorization of scripts, a subject which is central to the Scilab language and is reviewed throughout this document.
4.7 The eye matrix The eye function creates the identity matrix with the size which depends on the context. Its name has been chosen in place of I in order to avoid the confusion with a subscript or with the imaginary number. In the following session, we add 3 to the diagonal elements of the matrix A. -->A = ones(3,3) A = 1. 1. 1. 1. 1. 1. 1. 1. 1. -->B = A + 3*eye() B = 4. 1. 1. 1. 4. 1. 1. 1. 4.
48 In the following session, we define an identity matrix B with the eye function de- pending on the size of a given matrix A. -->A = ones(2,2) A = 1. 1. 1. 1. -->B = eye(A) B = 1. 0. 0. 1. Finally, we can use the eye(m,n) syntax in order to create an identity matrix with m rows and n columns.
4.8 Matrices are dynamic The size of a matrix can grow or reduce dynamically. This adapts the size of the matrix to the data it contains. Consider the following session where we define a 2 × 3 matrix. -->A = [1 2 3; 4 5 6] A = 1. 2. 3. 4. 5. 6. In the following session, we insert the value 7 at the indices (3, 1). This creates the third row in the matrix, sets the A(3, 1) entry to 7 and fills the other values of the newly created row with zeros. -->A(3,1) = 7 A = 1. 2. 3. 4. 5. 6. 7. 0. 0. The previous example showed that matrices can grow. In the following session, we see that we can also reduce the size of a matrix. This is done by using the empty matrix ”[]” operator in order to delete the third column. -->A(:,3) = [] A = 1. 2. 4. 5. 7. 0. We can also change the shape of the matrix with the matrix function. The matrix function reshapes a source matrix into a target matrix with a different size. The transformation is performed column by column, by stacking the elements of the source matrix. In the following session, we reshape the matrix A, which has 3×2 = 6 elements into a row vector with 6 columns. -->B = matrix(A,1,6) B = 1. 4. 7. 2. 5. 0.
49 A(i,$) the element at row i, at column nc A($,j) the element at row nr, at column j A($-i,$-j) the element at row nr − i, at column nc − j
Figure 33 – Access to a matrix with the dollar ”$” operator. The ”$” operator signifies ”the last subscript”.
4.9 The dollar ”$” operator Usually, we make use of subscript to make reference from the start of a ma- trix. By opposition, the dollar ”$” operator references elements from the end of the matrix. The ”$” operator signifies ”the subscript corresponding to the last” row or column, depending on the context. This syntax is associated with an algebra, so that the subscript $-i corresponds to the subscript ` − i, where ` is the number of corresponding rows or columns. Various uses of the dollar operator are presented in figure 33. In the following example, we consider a 3 × 3 matrix and we access the element A(2,1) = A(nr-1,nc-2) = A($-1,$-2) because nr = 3 and nc = 3. -->A=testmatrix("hilb",3) A = 9. - 36. 30. - 36. 192. - 180. 30. - 180. 180. -->A($-1,$-2) ans = - 36. The dollar ”$” operator adds elements dynamically at the end of matrices. In the following session, we add a row at the end of the Hilbert matrix. -->A($+1,:) = [1 2 3] A = 9. - 36. 30. - 36. 192. - 180. 30. - 180. 180. 1. 2. 3. The ”$” operator is used most of the time in the context of the ”$+1” statement, which adds to the end of a matrix. This can be convenient, since it avoids the need of updating the number of rows or columns continuously ; it should be used with care, only in situations where the number of rows or columns cannot be known in advance. The reason is that the interpreter has to internally re-allocate memory for the entire matrix and to copy the old values to the new destination. This can lead to performance penalties and this is why we should be warned against bad uses of this operator. All in all, the only good use of the ”$+1” statement is when we do not know in advance the final number of rows or columns.
50 4.10 Low-level operations All common algebra operators, such as ”+”, ”-”, ”*”and ”/”, are available with real matrices. In the next sections, we focus on the exact signification of these operators, so that many sources of confusion are avoided. The rules for the ”+”and ”-”operators are directly applied from the usual algebra. In the following session, we add two 2 × 2 matrices. -->A = [1 2 -->3 4] A = 1. 2. 3. 4. -->B =[5 6 -->7 8] B = 5. 6. 7. 8. -->A+B ans = 6. 8. 10. 12. When we perform an addition of two matrices, if one operand is a 1 × 1 matrix (i.e., a scalar), the value of this scalar is added to each element of the second matrix. This feature is shown in the following session. -->A = [1 2 -->3 4] A = 1. 2. 3. 4. -->A + 1 ans = 2. 3. 4. 5. The addition is possible only if the two matrices are conformable to addition. In the following session, we try to add a 2 × 3 matrix with a 2 × 2 matrix and check that this is not possible. -->A = [1 2 -->3 4] A = 1. 2. 3. 4. -->B = [1 2 3 -->4 5 6] B = 1. 2. 3. 4. 5. 6. -->A+B !-- error 8 Inconsistent addition. Elementary operators which are available for matrices are presented in figure 34. The Scilab language provides two division operators, that is,the right division ”/”
51 + addition .+ elementwise addition - subtraction .- elementwise subtraction ∗ multiplication .∗ elementwise multiplication / right division ./ elementwise right division \ left division .\ elementwise left division ˆ or ∗∗ power, i.e. xy .ˆ elementwise power ’ transpose and conjugate .’ transpose (but not conjugate)
Figure 34 – Matrix operators and elementwise operators. and the left division ”\”. The right division ”/” is so that X = A/B = AB−1 is the solution of XB = A. The left division ”\” is so that X = A\B = A−1B is the solution of AX = B. The left division A\B computes the solution of the associated least square problem if A is not a square matrix. Figure 34 separates the operators which treat the matrices as a whole and the elementwise operators, which are presented in the next section.
4.11 Elementwise operations If a dot ”.” is written before an operator, it is associated with an elementwise operator, i.e. the operation is performed element-by-element. For example, with the usual multiplication operator ”*”, the content of the matrix C=A*B is cij = P k=1,n aikbkj. With the elementwise multiplication ”.*” operator, the content of the matrix C=A.*B is cij = aijbij. In the following session, two matrices are multiplied with the ”*” operator and then with the elementwise ”.*” operator, so that we can check that the results are different. -->A = ones(2,2) A = 1. 1. 1. 1. -->B = 2 * ones(2,2) B = 2. 2. 2. 2. -->A*B ans = 4. 4. 4. 4. -->A.*B ans = 2. 2. 2. 2.
4.12 Conjugate transpose and non-conjugate transpose There might be some confusion when the elementwise single quote ”.’ ” and the regular single quote ”’ ” operators are used without a careful knowledge of
52 their exact definitions. With a matrix of doubles containing real values, the single quote ”’ ” operator only transposes the matrix. Instead, when a matrix of doubles containing complex values is used, the single quote ”’ ” operator transposes and conjugates the matrix. Hence, the operation A=Z’ produces a matrix with entries 2 Ajk = Xkj − iYkj, where i is the imaginary number such that i = −1 and X and Y are the real and imaginary parts of the matrix Z. The elementwise single quote ”.’ ” always transposes without conjugating the matrix, be it real or complex. Hence, the operation A=Z.’ produces a matrix with entries Ajk = Xkj + iYkj. In the following session, an non-symetric matrix of doubles containing complex values is used, so that the difference between the two operators is obvious. -->A = [1 2;3 4] + %i * [5 6;7 8] A = 1.+5.i 2.+6.i 3.+7.i 4.+8.i -->A’ ans = 1.-5.i 3.-7.i 2.-6.i 4.-8.i -->A.’ ans = 1.+5.i 3.+7.i 2.+6.i 4.+8.i In the following session, we define an non-symetric matrix of doubles containing real values and see that the results of the ”’ ” and ”.’ ” are the same in this particular case. -->B = [1 2;3 4] B = 1. 2. 3. 4. -->B’ ans = 1. 3. 2. 4. -->B.’ ans = 1. 3. 2. 4. Many bugs are created due to this confusion, so that it is mandatory to ask yourself the following question : what happens if my matrix is complex ? If the answer is ”I want to transpose only”, then the elementwise quote ”.’ ” operator is to be used.
4.13 Multiplication of two vectors
Let u ∈ Rn be a column vector and vT ∈ Rn be a column vector. The matrix T A = uv has entries Aij = uivj. In the following Scilab session, we multiply the column vector u by the row vector v and store the result in the variable A. -->u = [1 -->2
53 and(A,"r") rowwise ”and” and(A,"c") columnwise ”and” or(A,"r") rowwise ”or” or(A,"c") columnwise ”or”
Figure 35 – Special comparison operators for matrices. The usual operators ”<”, ”&”, ”|”are also available for matrices, but the and and or functions allow performing rowwise and columnwise operations.
-->3] u = 1. 2. 3. -->v = [4 5 6] v = 4. 5. 6. -->u*v ans = 4. 5. 6. 8. 10. 12. 12. 15. 18. This might lead to some confusion because linear algebra textbooks consider column vectors only. We usually denote by u ∈ Rn a column vector, so that the corresponding row vector is denoted by uT . In the associated Scilab implementation, a row vector can be directly stored in the variable u. It might also be a source of bugs, if the expected vector is expected to be a row vector and is, in fact, a column vector. This is why any algorithm which works only on a particular type of matrix (row vector or column vector) should check that the input vector has indeed the corresponding shape and generate an error if not.
4.14 Comparing two real matrices Comparison of two matrices is only possible when the matrices have the same shape. The comparison operators presented in figure 24 are indeed performed when the input arguments A and B are matrices. When two matrices are compared, the result is a matrix of booleans. This matrix can then be combined with operators such as and, or, which are presented in figure 35. The usual operators ”&”, ”|” are also available for matrices, but the and and or allow performing rowwise and columnwise operations. In the following Scilab session, we create a matrix A and compare it against the number 3. Notice that this comparison is valid because the number 3 is compared element by element against A. We then create a matrix B and compare the two matrices A and B. Finally, the or function is used to perform a rowwise comparison so that we get the columns where one value in the column of the matrix A is greater than one value in the column of the matrix B. -->A = [1 2 7
54 -->6 9 8] A = 1. 2. 7. 6. 9. 8. -->A >3 ans = FFT TTT -->B =[4 5 6 -->7 8 9] B = 4. 5. 6. 7. 8. 9. -->A>B ans = FFT FTF -->or(A>B,"r") ans = FTT
4.15 Issues with floating point integers In this section, we analyze the problems which arise when we use integers which are stored as floating point numbers. If used without caution, these numbers can lead to disastrous results, as we are going to see. Assume that the matrix A is a square 2 × 2 matrix. -->A = testmatrix("hilb",2) A = 4. - 6. - 6. 12. In order to access the element (2,1) of this matrix, we can use a constant subscript, such as A(2,1), which is safe. In order to access the element of the matrix, we can use variables i and j and use the statement A(i,j), as in the following session. -->i = 2 i = 2. -->j = 1 j = 1. -->A(i,j) ans = - 6. In the previous session, we emphasize that the variables i and j are doubles, that is, binary floating point values. This is why the following statement is valid. -->A( 2 , [1.0 1.1 1.5 1.9] ) ans = -6. -6. -6. -6. The previous session shows that the floating point values 1.0, 1.1, 1.5 and 1.9 are all converted to the integer 1, as if the floor function had been used to convert the
55 floating point number into an integer. Indeed, the floor function returns the floating point number storing the integer part of the given floating point number : in some sense, it rounds toward zero. For example, floor(1.0), floor(1.1), floor(1.5) and floor(1.9) all return 1. This is what makes this language both simple and efficient. But it can also have unfortunate consequences, sometimes leading to unexpected results. For example, consider the following session. -->ones(1,1) ans = 1. -->ones(1,(1-0.9)*10) ans = [] If the computations were performed in exact arithmetic, the result of (1 − 0.9) ∗ 10 is equal to 1. Instead, the statement ones(1,(1-0.9)*10) creates an empty matrix, because the floating point result of the expression (1-0.9)*10 is not exactly equal to 1. In the following session, we check that the integer part of (1-0.9)*10 is 0. -->floor((1-0.9)*10) ans = 0. Indeed, the decimal number 0.9 cannot be exactly represented as a double precision floating point number. This leads to a rounding, so that the floating point represen- tation of 1-0.9 is slightly smaller than 0.1. When the multiplication (1-0.9)*10 is performed, the floating point result is therefore slightly smaller than 1, as presented in the following session. -->format(25) -->1-0.9 ans = 0.0999999999999999777955 -->(1-0.9)*10 ans = 0.9999999999999997779554 Then the floating point number 0.999999999999999 is considered as the integer zero, which makes the ones function return an empty matrix. The origin of this issue is the use of the binary floating point number representing 0.1, which must be used with caution. There is a way to fix this issue, by forcing the way that the expression is rounded to the integer value. For example, we can use the round function prior to the call to the ones function. -->n=round((1-0.9)*10); -->ones(1,n) ans = 1. Indeed, the round function rounds to the nearest integer. In the following session, we check that n is exactly equal to 1. -->n ==1 ans =
56 T It is an unfortunate effect of the use of doubles which creates this kind of issues. On the other hand, this simplifies most expressions, so that this turns out to be a major advantage in most situations. We could as well blame the interpretor for silently converting a double with a fractional content into an integer, without gene- rating (at least) a warning. In practice, it is a safe practice to round a double prior to the call of a function which actually expects an integer value.
4.16 More on elementary functions In this section, we analyse several elementary functions, especially degree-based trigonometry functions, logarithm functions and matrix-based elementary functions. Trigonometry functions such as sin and cos are provided with the classical input argument in radian. But some other trigonometry functions, such as the cosd function for example, are taking an input argument in degree. This means that, in the mathematical sense tand(x) = tan(xπ/180). These functions can be easily identified because their name ends with the letter ”d”, e.g. cosd, sind among others. The key advantage for the degree-based elementary functions is that they provide exact results when their argument has special mathematical values, such as multiples of 90◦. Indeed, the implementation of the degree-based functions is based on an argument reduction which is exact for integer values. This gets exact floating point results for special cases. In the following session, we compute sin(π) and sind(180), which are mathema- tically equal, but are associated with different floating point results. -->sin(%pi) ans = 1.225D -16 -->sind(180) ans = 0. The fact that sin(π) is not exactly zero is associated with the limited precision of floating point numbers. Indeed, the argument π is stored in memory with a limited number of significant digits, which leads to rounding. Instead, the argument 180 is represented exactly as a floating point number, because it is a small integer. Hence, the value of sind(180) is computed by the sind function as sin(0). Once again, the number zero is exactly represented by a floating point number. Moreover, the sin function is represented in the [−π/2, π/2] interval by a polynomial of the form p(x) = x+x3q(x2) where q is a low degree polynomial. Hence, we get sind(180)=sin(0)=0, which is the exact result. The log function computes the natural logarithm of the input argument, that is, the inverse of the function exp= ex, where e is Euler’s number. In order to compute the logarithm function for other bases, we can use the functions log10 and log2, associated with bases 10 and 2 respectively. In the following session, we compute the values of the log, log10 and log2 functions for some specific values of x. -->x = [exp(1) exp(2) 1 10 2^1 2^10] x =
57 2.7182818 7.3890561 1. 10. 2. 1024. -->[x’ log(x’) log10(x’) log2(x’)] ans = 2.7182818 1. 0.4342945 1.442695 7.3890561 2. 0.8685890 2.8853901 1. 0. 0. 0. 10. 2.3025851 1. 3.3219281 2. 0.6931472 0.30103 1. 1024. 6.9314718 3.0103 10. The first column in the previous table contains various values of x. The column number 2 contains various values of log(x), while the columns 3 and 4 contains various values of log10(x) and log2(x). Most functions are elementwise, that is, given an input matrix, apply the same function for each entry of the matrix. Still, some functions have a special meaning with respect to linear algebra. For example, the matrix exponential of a function X P 1 k is defined by e = k=0,∞ k! X , where X is a square n × n matrix. In order to compute the exponential of a matrix, we can use the expm function. Obviously, the elementwise exponential function exp does not return the same result. More generally, the functions which have a special meaning with respect to matrices have a name which ends with the letter ”m”, e.g. expm, sinm, among others. In the following session, we define a 2 × 2 matrix containing specific multiples of π/2 and use the sin and sinm functions. -->A = [%pi/2 %pi; 2*%pi 3*%pi/2] A = 1.5707963 3.1415927 6.2831853 4.712389 -->sin (A) ans = 1. 1.225D-16 - 2.449D-16 - 1. -->sinm (A) ans = - 0.3333333 0.6666667 1.3333333 0.3333333
4.17 Higher-level linear algebra features In this section, we briefly introduce higher-level linear algebra features of Scilab. Scilab has a complete linear algebra library, which is able to manage both dense and sparse matrices. A complete book on linear algebra would be required to make a description of the algorithms provided by Scilab in this field, and this is obviously out of the scope of this document. Figure 36 presents a list of the most common linear algebra functions.
4.18 Exercises
Exercice 4.1 (Plus one) Create the vector (x1 + 1, x2 + 1, x3 + 1, x4 + 1) with the following x. x = 1:4;
58 chol Cholesky factorization companion companion matrix cond condition number det determinant inv matrix inverse linsolve linear equation solver lsq linear least square problems lu LU factors of Gaussian elimination qr QR decomposition rcond inverse condition number spec eigenvalues svd singular value decomposition testmatrix a collection of test matrices trace trace
Figure 36 – Some common functions for linear algebra.
Exercice 4.2 (Vectorized multiplication) Create the vector (x1y1, x2y2, x3y3, x4y4) with the following x and y. x = 1:4; y = 5:8;
Exercice 4.3 (The infamous dot) Analyze the following session and explain why we might not get the expected result. -->expected=[1/2 1/3 1/4] expected = 0.5 0.3333333 0.25 -->1./[2 3 4] ans = 0.0689655 0.1034483 0.1379310 Exercice 4.4 (Vectorized invert) Create the vector 1 , 1 , 1 , 1 with the following x. x1 x2 x3 x4 x = 1:4; Exercice 4.5 (Vectorized division) Create the vector x1 , x2 , x3 , x4 with the following x and y1 y2 y3 y4 y. x = 12*(6:9); y = 1:4;