Lecture 3: Visualization and Programming
-
Upload
smee-kam-chann -
Category
Technology
-
view
103 -
download
0
Transcript of Lecture 3: Visualization and Programming
MATLAB
Dr. Keang Sè POUV
Phnom Penh Printemps, 2015
Institut de Technologie du Cambodge
2
Plan du cours
Dr. Keang Sè POUV
1. Introduction2. Premières notions3. Matrices4. Chaînes de caractères5. Ecriture des instructions6. Scripts et fonctions7. Opérateurs relationnels et logiques8. Fonctions prédéfinies9. Calcul formel10.Graphiques en 2D11.Graphiques en 3D12.Structure de contrôle
3
Chapitre 1
Introduction
Dr. Keang Sè POUV
4
1. Introduction
Dr. Keang Sè POUV
Qu’est ce que MATLAB ?
Développé par la société The MathWorks, MATLAB (MATrix LABoratory) est un langage de programmation adapté pour les problèmes scientifiques et d’ingénierie. MATLAB est un interpréteur de commandes: les instructions sont interprétées et exécutées ligne par ligne (pas de compilation avant de les exécuter).
Modes de fonctionnement1. mode interactif: MATLAB exécute les instructions au fur et à mesure qu'elles
sont données par l'usager.2. mode exécutif: MATLAB exécute ligne par ligne un fichier ".m" (programme
en langage MATLAB).
Les avantages :- Facilité d’utilisation, prise en main rapide - Existence de toolboxes utiles pour l’ingénieur- Possibilité de l’interfacer avec d’autres langages (C, C++, Fortran)- Permet de faire du calcul parallèle.
Désavantages :- Limitation en mémoire- Payant
5
Chapitre 2
Premières notions
Dr. Keang Sè POUV
6
2. Premières notions
Dr. Keang Sè POUV
Lancement de MATLAB
Current Folder:Liste de fichiers
Command Window:Fenêtre principale pour l'exécution des instructions
Workspace:Contenu des variables
Command History:Historique des commandes
7
2. Premières notions
Dr. Keang Sè POUV
Documentation MATLAB
• Commande Help
Exemple : pour avoir de la documentation sur la commande plot
>> help plot
• Pour une documentation plus complète : Help/Documentation
8
2. Premières notions
Dr. Keang Sè POUV
Ligne de commande, mode immédiat
Il y a deux types de commande :
1. Expression : formule permettant de calculer immédiatement un résultat
Exemples d’expressions :
Tous les éléments de l’expression doivent être connus au moment de son évaluation par l’interpréteur.
2. Instruction : ensemble structuré d’expressions
Exemples d’instructions :
Remarque : le point-virgule (;) est un inhibiteur d’affichage.
9
2. Premières notions
Dr. Keang Sè POUV
Nombres
Les nombres réels peuvent être sous différents formats :
2 -1.0235 0.5124E-12 25.61e6 0.001234
Les nombres complexes peuvent être écrits sous forme cartésienne ou polaire :
Forme cartésienne : 0.5+i*2.7 -1.2+j*0.163 2.5+6.8iForme polaire : 1.25*exp(j*0.142)
Formats d’affichage
Pour choisir le format d’affichage pour les nombres, on utilise l’instruction format :
format défaut (même que format short)format short 0.1234format long 0.12345678901234format short e 1.2345E+002format long e 0.123456789012345E+002format hex ABCDEF0123456789
10
2. Premières notions
Dr. Keang Sè POUV
Opérations arithmétiques
+ Addition- Soustraction* Multiplication/ Division à droite\ Division à gauche^ Puissance
Exemples :
>> format short>> 3.5+1.2ans =
4.7000>> 10\2ans =
0.2000>> 3^2+0.4*10ans =
13
11
Chapitre 3
Matrices
Dr. Keang Sè POUV
12
3. Matrices
Dr. Keang Sè POUV
Définitions
- Matrice : Tableau rectangulaire (m lignes et n colonnes)- Vecteur : Matrice comportant 1 ligne et plusieurs colonnes) - Scalaire : Matrice comportant 1 ligne et 1 colonne
Sous Matlab, les données sont généralement définies comme des matrices, i.e. des tableaux à 1, 2 … n dimensions. On ne considérera ici que des tableaux à 1 ou 2 dimensions.
Exemples :
>> A=224 (on définit une variable A correspondant à une matrice àA = 1 ligne et 1 colonne contenant le nombre 224)
224>> B=[12 15 138] (on définit une variable B correspondant à une matrice à B = 1 ligne et 3 colonnes. Les espaces ou les virgules , entre
12 15 138 les nombres permettent de délimiter les colonnes.)>> C=[1,13,24]C =
1 13 24
13
3. Matrices
Dr. Keang Sè POUV
Définitions
Exemples :
>> D=[1 3 4; 7 2 5] (on définit une matrice D à 2 lignes et 3 colonnes. Les D = caractères ; permettent de passer à la ligne)
1 3 47 2 5
>> E=[1 3]E =
1 3>> F=[2 8]F =
2 8>> G=[E F] (concaténation les varaibles E et F en une seule)G =
1 3 2 8>> H=[E;F]H =
1 32 8
14
3. Matrices
Dr. Keang Sè POUV
Variables scalaires
• Définition des variables
>> a = 2 ;>> b = 2.5 ;>> c = a * b ;
• Liste des variables : commande who
>> a = 2 ; ---- Définition des variables a et b
>> b = 5 ;>> who ---- a b
• Suppression des variables : commande clear
>> clear a ---- Supprime la variable a>> clear all ---- Supprime toutes les variables
• Variables (constantes prédéfinies) : pi, 1i
15
3. Matrices
Dr. Keang Sè POUV
Eléments d’une matrice
Chaque élément d'une matrice est accessible à condition de spécifier sa place dans la matrice. Pour cela, il suffit de donner le numéro de ligne et de colonne entre ().
Exemples :
>> A=[1 5 2 6];>> A(1,2)ans =
5>> A(2) (car la matrice A ne contient qu’une seule ligne)ans =
5>> B=[1 5 6; 2 3 4]; (la variable end permet de récupérer le dernier élément.)>> B(2,2)ans =
3>> B(end)ans =
4
16
3. Matrices
Dr. Keang Sè POUV
Eléments d’une matrice
Pour récupérer plusieurs éléments d'une matrice, il suffit de préciser l'ensemble des numéros de lignes et de colonnes des éléments à prélever. En particulier, pour récupérer l'ensemble des éléments d'une ligne ou d'une colonne on utilise le caractère ' :'.
Exemples :
>> A=[1 2 4 0; 3 -2 6 8; 1 -3 5 4; 0 2 4 5];>> AA =
1 2 4 03 -2 6 81 -3 5 40 2 4 5
>> A(2,[1 2])ans =
3 -2>> A(3,:)ans =
1 -3 5 4
17
3. Matrices
Dr. Keang Sè POUV
Eléments d’une matrice
>> A(:,2)ans =
2-2-32
>> A([1 3],[1 3])ans =
1 41 5
>> A([1:3],[1:3])ans =
1 2 43 -2 61 -3 5
18
3. Matrices
Dr. Keang Sè POUV
Tailles d’un vecteur, dimension d’une matrice
19
3. Matrices
Dr. Keang Sè POUV
Création et construction de vecteurs
20
3. Matrices
Dr. Keang Sè POUV
Création et construction de matrices
Les fonctions ones, eye, zeros, et rand créent des matrices avec des remplissages divers.
ones : matrice des unseye : matrice d’identitézeros : matrice des zérosrand : matrice des chiffres aléatoiresrandn : matrice des chiffres aléatoires normalement distribués (Gaussien)diag : matrice diagonalemagic : matrice carré
Exemples :
21
3. Matrices
Dr. Keang Sè POUV
Création et construction de matrices
Exemples :
>> zeros(3,3)ans =
0 0 00 0 00 0 0
>> A=rand(3,2)A =
0.8147 0.91340.9058 0.63240.1270 0.0975
>> B=rand(3,2)B =
0.2785 0.96490.5469 0.15760.9575 0.9706
22
3. Matrices
Dr. Keang Sè POUV
Création et construction de matrices
Exemples :
>> A=[1 2 3 4]A =
1 2 3 4>> diag(A) (application de diag à un vecteur)ans =
1 0 0 00 2 0 00 0 3 00 0 0 4
>> B=[1 2 3 4; 5 6 7 8; 9 10 11 12] B =
1 2 3 45 6 7 89 10 11 12
>> diag(B) (application de diag à une matrice)ans =
16
11
23
3. Matrices
Dr. Keang Sè POUV
Création et construction de matrices
Les crochets carrés [], et la fonction repmat permettent d’empiler les matrices
Exemples :
24
3. Matrices
Dr. Keang Sè POUV
Création et construction de matrices
reshape : changement de la dimension de la matrice
Exemples :
>> A=[1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]A =
1 2 3 45 6 7 89 10 11 12
13 14 15 16>> reshape(A,1,16)ans =
1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16>> reshape(A,2,8)ans =
1 9 2 10 3 11 4 125 13 6 14 7 15 8 16
m x n : dimension initiale de la matrice Ap x q : nouvelle dimension de la matrice A (p x q = m x n), reshape(A,p,q)
25
3. Matrices
Dr. Keang Sè POUV
Opérations sur les matrices
Opérateurs arithmétiques logiques termes à termes
+, - addition et soustraction.*, ./ multiplication et divisions termes à termes.^ puissance terme à terme
Exemples :
>> A=[2 5 0];>> B=[1 2 3];>> A+Bans = 3 7 3>> A-Bans = 1 3 -3>> A.*Bans = 2 10 0>> A./Bans = 2.0000 2.5000 0>> A.^Bans = 2 25 0
26
3. Matrices
Dr. Keang Sè POUV
Opérations sur les matrices
Opérateurs algébriques
* multiplication matricielle^ puissance/, \ résolution de systèmes linéaires
Exemples :
>> a=[2 1 1; 1 3 2]; >> b=[0 6; 1 5; 4 1];>> a*bans =
5 18 (2*0+1*1+1*4=5, 2*6+1*5+1*1=18,11 23 (1*0+3*1+2*4=11, 1*6+3*5+2*1=23)
>> b*aans =
6 18 127 16 119 7 6
Note : a(m,n)*b(n,p)=c(m,p)
27
3. Matrices
Dr. Keang Sè POUV
Exemples :
>> A=[2 4; 1 1];>> A^2ans =
8 123 5
Note : a(m,m)^i=A(m,m) (matrice carrée m x m)
>> A=[2 4; 1 1];>> B=[1 0; 2 1];>> A/B (=A*B-1, inv(B)=B-1)ans =
-6 4-1 1
>> A\B (=A-1*B)ans =
3.5000 2.0000-1.5000 -1.0000
Note : A(m,n)/B(n,n)=C(m,n), A(m,m)\B(m,n)=D(m,n)
28
3. Matrices
Dr. Keang Sè POUV
Opérateurs de transposition
Exemples :
>> a=[1 2; 9 3]a =
1 29 3
>> a'ans =
1 92 3
>> a.'ans =
1 92 3
29
3. Matrices
Dr. Keang Sè POUV
Nombres complexes
real : partie réelleimag : partie imaginaireabs : valeur absolue ou moduleconj : conjugé
Exemples :
>> a=3-4i;>> real(a)ans =
3>> imag(a)ans =
-4>> abs(a) >> abs(-20)ans = ans =
5 20 >> conj(a)ans =
3.0000 + 4.0000i
30
3. Matrices
Dr. Keang Sè POUV
Nombres complexes
angle : phase angle (entre -π et π)
r = abs(z)phi = angle(z)z = |z|.*exp(i*arg(z)) = r.*exp(i*phi)
Exemples :
>> angle(3)ans =
0>> angle(1)ans =
0>> angle(-0.5)ans =
3.1416>> angle(-1)ans =
3.1416
31
3. Matrices
Dr. Keang Sè POUV
Nombres complexes
>> z=[1-1i 1i 2+2i; 3-2i 1+1i -1i; 4+2i -2+1i 2i]>> angle(z)ans =
-0.7854 1.5708 0.7854-0.5880 0.7854 -1.57080.4636 2.6779 1.5708
>> angle(z)*180/pians =
-45.0000 90.0000 45.0000-33.6901 45.0000 -90.000026.5651 153.4349 90.0000
Note:angle(a+bi)=arctan(b/a)*pi/180 (argument d’un complexe)
32
3. Matrices
Dr. Keang Sè POUV
Constantes importantes
ans : dernier résultat de calculinf : infiniNaN : Not a Number, résultat d’un calcul indéfini
pi : constante π
Exemples :
>> 2/0ans =
Inf>> 0/0ans =
NaN>> pians =
3.1416>> 2*pians =
6.2832
33
3. Matrices
Dr. Keang Sè POUV
Transformations de matrices
fliplr : Flip matrix in left/right direction.fliplr(X) returns X with row preserved and columns flippedin the left/right direction.
Exemples :
>> A=[1 2 3; 4 5 6]A =
1 2 34 5 6
>> fliplr(A)ans =
3 2 16 5 4
34
3. Matrices
Dr. Keang Sè POUV
Transformations de matrices
flipud : Flip matrix in up/down direction.flipud(X) returns X with columns preserved and rows flippedin the up/down direction.
Exemples :
>> A=[1 4; 2 5; 3 6]A =
1 42 53 6
>> flipud(A)ans =
3 62 51 4
35
3. Matrices
Dr. Keang Sè POUV
Transformations de matrices
rot90 : Rotate matrix 90 degrees.rot90(A) is the 90 degree counter-clockwise rotation of matrix A.
Exemples :
>> A=[1 2 3; 4 5 6]A =
1 2 34 5 6
>> rot90(A)ans =
3 62 51 4
36
3. Matrices
Dr. Keang Sè POUV
Transformations de matrices
tril : Extract lower triangular part.
>> X=[1 2 3 4; 5 6 7 8]X =
1 2 3 45 6 7 8
>> tril(X)ans =
1 0 0 05 6 0 0
>> Y=[1 2 3; 4 5 6; 7 8 9]Y =
1 2 34 5 67 8 9
>> tril(Y)ans =
1 0 04 5 07 8 9
37
3. Matrices
Dr. Keang Sè POUV
Transformations de matrices
triu : Extract upper triangular part.
>> X=[1 2 3 4; 5 6 7 8]X =
1 2 3 45 6 7 8
>> triu(X)ans =
1 2 3 40 6 7 8
>> Y=[1 2 3; 4 5 6; 7 8 9]Y =
1 2 34 5 67 8 9
>> triu(Y)ans =
1 2 30 5 60 0 9
38
3. Matrices
Dr. Keang Sè POUV
Exercices
Exercice 1 :La formule permettant de calculer rapidement la valeur de la somme des n premiers entiers naturels est la suivante : sn=1+2+3+…+n=n(n+1)/2. Vérifier cette formule pour différentes valeurs de n : n=100, n=100 000.
Exercice 2 :1. Générer un vecteur x à 1 ligne et 30 colonnes rempli de 3 en utilisant la
fonction ones().2. Calculer la somme cumulée de x (fonction cumsum()) et l’affecter à la
variable y.3. Prélever un échantillon sur 9 de y et placer ces échantillons dans un vecteur
z.
Exercice 3 :1. Générer un vecteur x à 1 colonne et 1000 lignes rempli de nombre aléatoires
distribués uniformément entre 0 et 1 en utilisant la fonction rand().2. Calculer la moyenne et l’écart type du vecteur x en utilisant mean() et
std().
39
3. Matrices
Dr. Keang Sè POUV
Exercices
Exercice 4 :Résoudre les systèmes AX=b et AY=b+δb
Exercice 5 :On a :M=[1 4 7 -2; 3 5 10 0; 8 2 4 1; -2 4 5 1];
En utilisant la matrice d’identité, vérifier que :M-1=[0.0628 -0.0921 0.1464 -0.0209
0.4310 -0.6987 0.3389 0.5230-0.2343 0.4770 -0.2134 -0.2552-0.4268 0.2259 0.0042 0.1423]
40
Chapitre 4
Chaînes de caractères
Dr. Keang Sè POUV
41
4. Chaînes de caractères
Dr. Keang Sè POUV
Définition d’une chaîne de caractère
Les chaînes de caractères sont les matrices de caractères.
Pour définir une chaîne de caractère on utilise les apostrophes.
Exemple :
>> nom='POUV'nom =POUV>> phrase='Ceci est une phrase'phrase =Ceci est une phrase>> Couple=['homme';'femme']Couple =hommefemme
42
4. Chaînes de caractères
Dr. Keang Sè POUV
Eléments d’une chaîne de caractère
Pour récupérer certains caractères d'une chaîne de caractères, il suffit de préciser les indices des numéros de lignes et de colonnes correspondant.
Exemple :
>> nom_du_capitaine='Archibald Haddock';
Pour prélever son prénom et le mettre dans la variable prenom_du_capitaine, on peut faire :
>> prenom_du_capitaine=nom_du_capitaine(1:9)prenom_du_capitaine =Archibald
1:9 détermine la longueur de la chaîne de caractère correspondant au prénom.
43
4. Chaînes de caractères
Dr. Keang Sè POUV
Opération sur les chaînes de caractères
Concaténation : pour concaténer 2 chaînes de caractères, on peut utiliser les symbole [].
>> a=‘Un oiseau';>> b='fait son nid';>> c=[a b]c =Un oiseaufait son nid>> d=' fait son nid';>> e=[a d]e =Un oiseau fait son nid
Transposition : on peut transposer une chaîne de caractères avec le symbole ‘.
>> A='abc';>> A'ans =abc
44
Chapitre 5
Ecriture des instructions
Dr. Keang Sè POUV
45
5. Ecriture des instructions
Dr. Keang Sè POUV
Syntaxe simplifiée
1. Définition des variables (e.g. Nom_variable=valeur ou expression)2. Exécution et affichage des résultats intermédiaires.3. Exécution et affichage des résultats finaux.
Exemples :
>> g=-9.81; >> alpha=pi/3;>> b=g*cos(alpha)b =
-4.9050
Les variables g et alpha sont déjà initialisées, cos est une fonction.Si on utilise une variable non définie, Matlab affiche un message d’erreur.
>> c=b*dUndefined function or variable 'd'.
46
5. Ecriture des instructions
Dr. Keang Sè POUV
Résultats
On définit le résultat par l’initialisation d’une variable de sortie. Si force est la variable de sortie, le résultat est donné par :
force=expression
Exercice 6 :
On lance une pierre verticalement vers le haut avec une vitesse initiale de 5 m/s.Calculer la hauteur maximal de la pierre.
47
Chapitre 6
Scripts et fonctions
Dr. Keang Sè POUV
48
6. Scripts et fonctions
Dr. Keang Sè POUV
Pour écrire plusieurs instructions à la fois, il est utile d’utiliser des fichiers scripts ou des fonctions. Les scripts exécutent une série de déclaration MATLAB. Les fonctions acceptent les arguments d’entrée et produisent les résultats. Les scripts et les fonctions contiennent les codes MATLAB et sont stockés dans les fichiers textes d’extension .m. Pourtant, les fonctions sont plus flexibles et plus facilement extensibles.
Script
- suite d’instructions- pas de paramètre d’entrée- ne renvoie aucune valeur- appels à d’autres scripts ou d’autres fonctions
Fonction
- peut prendre des arguments d’entrée- retourne une ou plusieurs valeurs- les variables locales inaccessibles depuis l’extérieur- contrainte syntaxique : seule la fonction portant le nom du M-fichier est
accessible
49
6. Scripts et fonctions
Dr. Keang Sè POUV
Créer des fichier scripts ou des fonctions / Editeur Matlab
50
6. Scripts et fonctions
Dr. Keang Sè POUV
Exemples de script
Fichier exScript.m
x=1;y=2;z=x+y;
Dans la fenêtre de commande :
>> exScript Exécution du script stocké dans le fichier exScript.m>> x Renvoie les valeurs des variables x, y et z.
>> y Les variables déclarées dans le script sont connues>> z
NB : Le fichier exScript.m doit être dans le répertoire courant.
51
6. Scripts et fonctions
Dr. Keang Sè POUV
Exemples de fonction
Fichier SommeEtProduit.m
function [s,p]=SommeEtProduit(x,y)s=x+y;p=x*y;(end function)
NB : s et p sont les arguments de sortie. x et y sont les arguments d’entrée.
Dans la fenêtre de commande :(sans besoins de compiler dans le fichier SommeEtProduit.m)
>> a=1; Définition des variables a et b
>> b=2;>> [c,d]=SommeEtProduit(a,b) Appel et exécution de la fonction
SommeEtProduit (c=3, d=2)>> x Erreur, x n’est pas connue
NB: Le fichier SommeEtProduit.m doit être dans le répertoire courant.Le nom du fichier .m et le nom de la fonction doivent être les mêmes.
52
6. Scripts et fonctions
Dr. Keang Sè POUV
Exercices
Exercice 7 : Renommage de nom du fichier.Soit la variable nom_fich=‘fichier_1.txt’ :1. Définir une variable contenant le nom du fichier sans son extension2. Ajouter à cette variable le suffixe ‘_new.txt’ par concaténation de chaîne de
caractère.3. Générer une fonction change_extension qui accepte une variable d’entrée des
chaînes de caractère de type nom_de_fichier.extension et qui transforme automatiquement le nom de l’extension (à 3 caractères) en « dat ». La valeur de la sortie étant alors nom_de_fichier.dat.
Exercice 8 : Gestion de matrices de chaînes de caractères.Générer une variable nom_fichier contenant sur 3 lignes 3 noms de fichiers : toto_1.txt, toto_2.txt, toto_3.txt.Que se passe t’il si l’on y concatène la chaîne ‘toto_10.txt’?
53
Chapitre 7
Opérateurs relationnels et logiques
Dr. Keang Sè POUV
54
7. Opérateurs relationnels et logiques
Dr. Keang Sè POUV
Opérateurs relationnels
< strictement inférieur> strictement supérieur<= inférieur ou égal>= supérieur ou égal== égal~= différent (non égal)
Exemples :
>> 2>3ans =
0>> 3>1ans =
1
NB:Valeur logique 0 = FauxValeur logique 1 = Vrai
55
7. Opérateurs relationnels et logiques
Dr. Keang Sè POUV
Opérateurs relationnels
Exemples :
>> a=magic(4)a =
16 2 3 135 11 10 89 7 6 124 14 15 1
>> b=repmat(magic(2),2,2)b =
1 3 1 34 2 4 21 3 1 34 2 4 2
>> a==bans =
0 0 0 00 0 0 00 0 0 01 0 0 0
>> a<=bans =
0 1 0 00 0 0 00 0 0 01 0 0 1
56
7. Opérateurs relationnels et logiques
Dr. Keang Sè POUV
Opérateurs logiques
& : logique AND| : logique OR
Exemples :
>> a=3;>> b=6;>> a>2 & b>3ans =
1>> a>4 | b<5ans =
0>> x=[1 2 4];>> y=[3 4 5];>> x>0 & y<4ans =
1 0 0>> x>0 | y<4ans =
1 1 1
57
7. Opérateurs relationnels et logiques
Dr. Keang Sè POUV
Opérateurs logiques
~ : logique NONxor : logique EXCLUSIVE OR
Exemples :
>> a=[1 0 4];>> b=~a (~a = not(a))b =
0 1 0 >> x=5;>> y=12;>> xor(x>4,y<16)ans =
0>> xor(x>5,y<16)ans =
1
xor : The result is logical 1 (TRUE) where either S or T, but not both, is nonzero.
58
Chapitre 8
Fonctions prédéfinies
Dr. Keang Sè POUV
59
8. Fonctions prédéfinies
Dr. Keang Sè POUV
Fonctions trigonométriques de base
Exemples :
>> sin(pi/2)ans =
1>> asin(1)*180/pians =
90>> sinh(0)ans =
0>> cosh(0)ans =
1
sin cos tan asin acos atan
sihh cosh tanh asinh acosh atanh
60
8. Fonctions prédéfinies
Dr. Keang Sè POUV
Fonctions mathématiques de base
Exemples :
>> exp(1)ans =
2.7183>> log2(4)ans =
2>> sqrt(100)ans =
10>> log(exp(5))ans =
5
exp
exponentiel
log
logarithme àbase e
log10
logarithme à base 10
log2
logarithme à base 2
pow2
puissance 2
sqrt
racine carrée
61
8. Fonctions prédéfinies
Dr. Keang Sè POUV
Fonctions mathématiques de base
Exemples :
>> A=[2 1.2 -4.5 8];>> a=min(A)a =
-4.5000>> round(A)ans =
2 1 -5 8>> fix(A)ans =
2 1 -4 8
min
valeur minimale
max
valeur maximale
mean
valeur moyenne
std
écart type
cov
covariance
sum
somme
round
arrondir
fix
arrondir (vers zéro)
floor
arrondir (vers -∞)
ceil
arrondir (vers ∞)
rem
reste
mod
module
>> mean(A)ans =
1.6750>> sum(A)ans =
6.7000>> cov(A)ans =
26.1558
62
8. Fonctions prédéfinies
Dr. Keang Sè POUV
Fonctions mathématiques de base
rem : reste de la divisionrem(x,y) est x-n*y où n=fix(x./y) si y~=0 (x et y ont les mêmes dimensions)rem(x,0) est xrem(x,y) a la même signe que xrem(x,y)=mod(x,y) si x et y ont la même signemod : module après divisionmod(x,y) est x-n*y où n=floor(x./y) si y~=0 (x et y ont les mêmes dimensions)mod(x,0) est xmod(x,y) a la même signe que y
Exemples :
>> rem(9,-3.5)ans =
2>> rem(9,3.5)ans =
2>> rem(-10,3)ans =
-1
>> mod(9,-3.5)ans =
-1.5000>> mod(9,3.5)ans =
2>> mod(-10,3)ans =
2
63
8. Fonctions prédéfinies
Dr. Keang Sè POUV
Fonctions mathématiques de base
Exemples :
>> M=[1 4; 4 1]M =
1 44 1
>> inv(M)ans =
-0.0667 0.26670.2667 -0.0667
>> transpose(M)ans =
1 44 1
inv
inversion de matrice carrée
transpose
transpositionde matrice
det
déterminant de matrice
size
dimension de matrice
rank
rang de matrice
>> det(M)ans =
-15>> rank(M)ans =
2>> [i j]=size(M)i =
2j =
2
64
8. Fonctions prédéfinies
Dr. Keang Sè POUV
Fonctions mathématiques de base
Exemples :
>> M=magic(3)M =
8 1 63 5 74 9 2
>> sum(M)ans =
15 15 15>> cumsum(M)ans =
8 1 611 6 1315 15 15
sum
somme des éléments
cumsum
somme cumulative
prod
produit des éléments
cumprod
produit cumulative
norm
norme matriceou vecteur
>> P=prod(M)P =
96 45 84>> normM=sqrt(sum(P))normM =
15>> norm(M)ans =
15.0000>> cumprod(M)ans =
8 1 624 5 4296 45 84
65
8. Fonctions prédéfinies
Dr. Keang Sè POUV
Exercices
Exercice 9 :1. Déterminer les valeurs arrondies de x, y, z et t en degré à partir des
équations suivantes : sin(2x2)=0.4; cos(y3)=0.5; tan(z/1.4)=2; t=3ln(xyz).2. Déterminer la moyenne arithmétique entre les valeurs de x, y, z et t.
Exercice 10 : On a une matrice M suivante :M =
16 2 3 135 11 10 89 7 6 124 14 15 1
1. Supprimer la troisième colonne de la matrice M.2. Supprimer la dernière ligne de la matrice M.3. Déterminer les dimensions m et n de la nouvelle matrice M.4. Déterminer le déterminant de la nouvelle matrice M.
66
Chapitre 9
Calcul formel
Dr. Keang Sè POUV
67
9. Calcul formel
Dr. Keang Sè POUV
Différence et différentiation
diff : Difference and approximate derivativediff(X), for a vector X, is [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)].diff(X), for a matrix X, is the matrix of row differences, [X(2:n,:) - X(1:n-1,:)].
Exemples :
>> V=[1 4 5 3];>> DV=diff(V)DV =
3 1 -2>> M=[1 4 5; 2 5 8; 3 6 1]M =
1 4 52 5 83 6 1
>> DM=diff(M)DM =
1 1 31 1 -7
68
9. Calcul formel
Dr. Keang Sè POUV
Différence et différentiation
diff : Difference and approximate derivativediff(X,N) applies diff recursively n times, resulting in the nth difference.diff(X,N,DIM) is the Nth difference function along dimension DIM. If N >= size(X,DIM), diff returns an empty array.
Exemples :
>> V=[1 4 5 3];>> DV=diff(V,2)DV =
-2 -3>> DM1=diff(M,1,1)DM1 =
1 1 31 1 -7
>> DM1=diff(M,1,2)DM1 =
3 13 33 -5
69
9. Calcul formel
Dr. Keang Sè POUV
Différence et différentiation
La fonction diff peut être utilisée pour calculer symboliquement la dérivée.
Exemples :
>> syms a x (symbolic math toolbox est nécessaire)>> y=a*x^3+xy =a*x^3 + x>> dydx=diff(y) (=dy/dx)dydx =3*a*x^2 + 1>> dyda=diff(y,a) (=dy/da)dyda =x^3>> dydx2=diff(y,x,2) (=d2y/dx2)dydx2 =6*a*x>> dydx2=diff(y,a,2) (=d2y/da2)dydx2 =0
70
9. Calcul formel
Dr. Keang Sè POUV
Intégration
int : Integrateint(S) : indefinite integral of S with respect to its symbolic variable.int(S,v) : indefinite integral of S with respect to v. v is scalar SYM.int(S,a,b) : definite integral of S with respect to its SYM variable from a to b.int(S,v,a,b) : definite integral of S with respect to v from a to b.
Exemples :
>> syms x n>> p=sin(2*x);>> int(p)ans =sin(x)^2>> y=x^n;>> int(y,n)ans =x^n/log(x)>> int(y,x)ans =piecewise([n == -1, log(x)], [n ~= -1, x^(n + 1)/(n + 1)])
71
9. Calcul formel
Dr. Keang Sè POUV
Intégration
int : Integrateint(S) : indefinite integral of S with respect to its symbolic variable.int(S,v) : indefinite integral of S with respect to v. v is scalar SYM.int(S,a,b) : definite integral of S with respect to its SYM variable from a to b.int(S,v,a,b) : definite integral of S with respect to v from a to b.
Exemples :
>> syms x n>> y=n*sin(x);>> y1=int(y,pi/3,pi/2)y1 =n/2>> y2=int(y1,5,10)y2 =75/4>> y3=int(y,n,1,4)y3 =(15*sin(x))/2
72
9. Calcul formel
Dr. Keang Sè POUV
Simplification d’une expression symbolique
simple : search for simplest form of symbolic expressionsimple(S) : applies different algebraic simplification functions and displays all resulting forms of S, and then returns the shortest form.r = simple(S) : tries different algebraic simplification functions without displaying the results, and then returns the shortest form of S.[r,how] = simple(S) : tries different algebraic simplification functions without displaying the results, and then returns the shortest form of S and a string describing the corresponding simplification method. Some common strings for simplification method: collect, expand, horner, factor and simplify.
S represent symbolic expression or symbolic matrix. r is a symbolic object representing the shortest form of S. how is a string describing the simplification method that gives the shortest form of S.
Exemples :
>> syms x>> y=cos(x)^2+sin(x)^2+3;>> r=simple(y)r =4
73
9. Calcul formel
Dr. Keang Sè POUV
Simplification d’une expression symbolique
collect(f) : views f as a polynomial in its symbolic variable, say x, and collects all the coefficients with the same power of x.
Exemples :
>> syms x>> f=(x-1)*(x-2)*(x-3)f =(x - 1)*(x - 2)*(x - 3)>> collect(f)ans =x^3 - 6*x^2 + 11*x - 6>> syms x t>> f=(1+x)*t+x*tf =t*x + t*(x + 1)>> collect(f)ans =(2*t)*x + t
74
9. Calcul formel
Dr. Keang Sè POUV
Simplification d’une expression symbolique
expand(f) : distributes products over sums and applies other identities involving functions of sums.
Exemples :
>> syms a x y>> f=a*(x+y);>> expand(f)ans =a*x + a*y>> syms x>> f=(x-1)*(x-2)*(x-3);>> expand(f)ans =x^3 - 6*x^2 + 11*x - 6>> syms a b>> f=exp(a+b);>> expand(f)ans =exp(a)*exp(b)
75
9. Calcul formel
Dr. Keang Sè POUV
Simplification d’une expression symbolique
factor(f) : expresses f as a product of polynomials of lower degree with rational coefficients (f is a polynomial with rational coefficients). If f cannot be factored over the rational numbers, the result is f itself.factor(N) : returns a vector containing the prime factors of N.
Exemples :
>> syms x y>> f=x^3-6*x^2+11*x-6;>> factor(f)ans =(x - 3)*(x - 1)*(x - 2)>> g=y^3-6*y^2+11*y-5;>> factor(g)ans =y^3 - 6*y^2 + 11*y - 5>> h=x^2-1;>> factor(h)ans =(x - 1)*(x + 1)
>> factor(110)ans =
2 5 11>> factor(1111)ans =
11 101
76
9. Calcul formel
Dr. Keang Sè POUV
Simplification d’une expression symbolique
simplify : can be applied with a number of algebraic identities involving sums, integral powers, square roots and other fractional powers, as well as a number of functional identities involving exponential and log functions, Bessel functions...
Exemples :
>> syms x a>> f=2*(1-x^2)/(1+x);>> simplify(f)ans =2 - 2*x>> f=(1/a^3+1/a^2+12/a+8)^(1/3);>> simplify(f)ans =((8*a^3 + 12*a^2 + a + 1)/a^3)^(1/3)>> f=2*(cos(a)^2-(1/2))/sin(2*a);>> simplify(f)ans =cos(2*a)/sin(2*a)
77
9. Calcul formel
Dr. Keang Sè POUV
Simplification d’une expression symbolique
limit : limit of an expression.limit(F,x,a) takes the limit of the symbolic expression F as x a.
limit(F,a) uses symvar(F) as the independent variable.limit(F) uses a = 0 as the limit point.limit(F,x,a,'right') or limit(F,x,a,'left') specify the direction of a one-sided limit.
Exemples :
>> syms x t>> limit(sin(x)/x)ans =1>> limit(x^2/(x+1),2)ans =4/3>> limit((1+t/x)^(3*x),x,inf)ans =exp(3*t)>> limit(1/t,t,0,'left')ans =-Inf
78
9. Calcul formel
Dr. Keang Sè POUV
Simplification d’une expression symbolique
symsum : symbolic summationsymsum(f,x) evaluates the sum of a series, where expression f defines the terms of a series, with respect to the symbolic variable x.symsum(f,x,a,b) evaluates the sum of a series, where expression f defines the terms of a series, with respect to the symbolic variable x. The value of the variable x changes from a to b.
Exemples :
>> syms x k n>> symsum(k)ans =k^2/2 - k/2>> symsum(k,0,n)ans =(n*(n + 1))/2>> symsum(x^k,k,0,inf)ans =piecewise([1 <= x, Inf], [abs(x) < 1, -1/(x - 1)])
79
Chapitre 10
Graphiques en 2D
Dr. Keang Sè POUV
80
10. Graphiques en 2D
Dr. Keang Sè POUV
Graphiques en coordonnées cartésiennes
plot(X,Y) : plots vector Y versus vector XVarious line types, plot symbols and colors may be obtained with plot(X,Y,S)where S is a character string made from one element from any or all the following 3 columns:
b blue . point - solidg green o circle : dottedr red x x-mark -. dashdot c cyan + plus -- dashed m magenta * star (none) no liney yellow s squarek black d diamondw white v triangle (down)
^ triangle (up)< triangle (left)> triangle (right)p pentagramh hexagram
For example, plot(X,Y,'c+:') plots a cyan dotted line with a plus at each data point; plot(X,Y,'bd') plots blue diamond at each data point but does not draw any line.
81
10. Graphiques en 2D
Dr. Keang Sè POUV
Graphiques en coordonnées cartésiennes
Exemples :
>> x = linspace(-2*pi, 2*pi, 400);>> y=sin(x);
>> plot(x,y,'gs')>> plot(x,y,'g')
82
10. Graphiques en 2D
Dr. Keang Sè POUV
Propriétés du graphe
Lineseries properties
'Color' : Color'LineStyle' : Line style'LineWidth' : Line width'Marker' : Marker symbol'MarkerEdgeColor' : Marker edge color'MarkerFaceColor' : Marker face color'MarkerSize' : Marker size
Exemples :
>> x=-10:0.1:10;>> y=x.*sin(x);>> plot(x,y,'-mo','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','y', 'MarkerSize',7)
83
10. Graphiques en 2D
Dr. Keang Sè POUV
Propriétés du graphe
Formatting the graph
grid ON adds major grid lines to the current axes.grid OFF removes major and minor grid lines from the current axes. grid MINOR toggles the minor grid lines of the current axes.title('text') adds text at the top of the current axis.xlabel('text') adds text beside the X-axis on the current axis.ylabel('text') adds text beside the Y-axis on the current axis.text(X,Y,'string') adds the text in the quotes to location (X,Y) on the current axes.legend(string1,string2,string3, ...) puts a legend on the current plot using the specified strings as labels.
Les propriétés du graphe peuvent également être modifiées directement sur la fenêtre de Figure.
84
10. Graphiques en 2D
Dr. Keang Sè POUV
Symboles et caractères spéciaux
α \alpha υ \upsilon ~ \sim
∠ \angle Φ \phi ≤ \leq
* \ast χ \chi ∞ \infty
β \beta ψ \psi ♣ \clubsuit
γ \gamma ω \omega ♦ \diamondsuit
δ \delta Γ \Gamma ♥ \heartsuit
ɛ \epsilon Δ \Delta ♠ \spadesuit
ζ \zeta Θ \Theta ↔ \leftrightarrow
η \eta Λ \Lambda ← \leftarrow
θ \theta Ξ \Xi ⇐ \Leftarrow
ϑ \vartheta Π \Pi ↑ \uparrow
ι \iota Σ \Sigma → \rightarrow
κ \kappa ϒ \Upsilon ⇒ \Rightarrow
λ \lambda Φ \Phi ↓ \downarrow
µ \mu Ψ \Psi º \circ
ν \nu Ω \Omega ± \pm
ξ \xi ∀ \forall ≥ \geq
π \pi ∃ \exists ∝ \propto
ρ \rho ∍ \ni ∂ \partial
σ \sigma ≅ \cong • \bullet
ς \varsigma ≈ \approx ÷ \div
τ \tau ℜ \Re ≠ \neq
≡ \equiv ⊕ \oplus ℵ \aleph
ℑ \Im ∪ \cup ℘ \wp
⊗ \otimes ⊆ \subseteq ∅ \oslash
∩ \cap ∈ \in ⊇ \supseteq
⊃ \supset ⌈ \lceil ⊂ \subset
∫ \int · \cdot ο \o
⌋ \rfloor ¬ \neg ∇ \nabla
⌊ \lfloor x \times ... \ldots
⊥ \perp √ \surd ´ \prime
∧ \wedge ϖ \varpi ∅ \0
⌉ \rceil 〉 \rangle | \mid
∨ \vee 〈 \langle © \copyright
α \alpha υ \upsilon ~ \sim
∠ \angle Φ \phi ≤ \leq
* \ast χ \chi ∞ \infty
β \beta ψ \psi ♣ \clubsuit
γ \gamma ω \omega ♦ \diamondsuit
δ \delta Γ \Gamma ♥ \heartsuit
ɛ \epsilon Δ \Delta ♠ \spadesuit
ζ \zeta Θ \Theta ↔ \leftrightarrow
η \eta Λ \Lambda ← \leftarrow
θ \theta Ξ \Xi ⇐ \Leftarrow
ϑ \vartheta Π \Pi ↑ \uparrow
ι \iota Σ \Sigma → \rightarrow
κ \kappa ϒ \Upsilon ⇒ \Rightarrow
λ \lambda Φ \Phi ↓ \downarrow
µ \mu Ψ \Psi º \circ
ν \nu Ω \Omega ± \pm
ξ \xi ∀ \forall ≥ \geq
π \pi ∃ \exists ∝ \propto
ρ \rho ∍ \ni ∂ \partial
σ \sigma ≅ \cong • \bullet
ς \varsigma ≈ \approx ÷ \div
τ \tau ℜ \Re ≠ \neq
≡ \equiv ⊕ \oplus ℵ \aleph
ℑ \Im ∪ \cup ℘ \wp
⊗ \otimes ⊆ \subseteq ∅ \oslash
∩ \cap ∈ \in ⊇ \supseteq
⊃ \supset ⌈ \lceil ⊂ \subset
∫ \int · \cdot ο \o
⌋ \rfloor ¬ \neg ∇ \nabla
⌊ \lfloor x \times ... \ldots
⊥ \perp √ \surd ´ \prime
∧ \wedge ϖ \varpi ∅ \0
⌉ \rceil 〉 \rangle | \mid
∨ \vee 〈 \langle © \copyright
85
10. Graphiques en 2D
Dr. Keang Sè POUV
Superposition de plusieurs graphes
hold : Hold current graphhold ON holds the current plot and all axis properties so that subsequent graphing commands add to the existing graph.hold OFF returns to the default mode whereby PLOT commands erase the previous plots and reset all axis properties before drawing new plots.
Exemples :
>> x=linspace(-2*pi,2*pi,100);>> y1=sin(x);>> plot(x,y1,'k:')>> hold on>> y2=cos(x);>> plot(x,y2,'r')
C’est équivalent à :
>> x=linspace(-2*pi,2*pi,100);>> y1=sin(x);>> y2=cos(x);>> plot(x,y1,'k:',x,y2,'r')
86
10. Graphiques en 2D
Dr. Keang Sè POUV
Superposition de plusieurs graphes
Exemples :
>> x=linspace(-2*pi,2*pi,100);>> y1=sin(x);>> y2=cos(x);>> plot(x,y1,'k:',x,y2,'r')>> title('Graph of Sine and Cosine for -2\pi \leq x \leq 2\pi')>> xlabel('x')>> ylabel('y1,y2')>> legend('y1=sin(x)','y2=cos(x)')>> text(-6.5,-0.05,‘Premier point')
87
10. Graphiques en 2D
Dr. Keang Sè POUV
Plusieurs graphiques dans une même figure
subplot : create axes in tiled positions.subplot(m,n,p) divides the current figure into an m-by-n grid and creates an axes in the grid position specified by p.
Exemples :
>> x=-5:0.1:5;>> figure>> subplot(2,2,1)>> y1=sin(x);>> plot(x,y1)>> subplot(2,2,2)>> y2=cos(x);>> plot(x,y2)>> subplot(2,2,3)>> y3=x.^2;>> plot(x,y3)>> subplot(2,2,4)>> y4=x.^3;>> plot(x,y4)
88
10. Graphiques en 2D
Dr. Keang Sè POUV
Graphiques en coordonnées polaires
polar : graphiques en coordonnées polairespolar(THETA, RHO) makes a plot using polar coordinates of the angle THETA, in radians, versus the radius RHO.polar(THETA, RHO, S) uses the linestyle specified in string S.
Exemples :
>> theta=0:0.01:2*pi;>> r=sin(theta).*cos(theta);>> figure>> polar(theta,r,'--r')
89
10. Graphiques en 2D
Dr. Keang Sè POUV
Echelles logarithmiques
loglog : log-log scale plotsemilogx : semi-log scale plot (logarithmic scale for the x-axis).semilogy : semi-log scale plot (logarithmic scale for the y-axis).
Exemples :
>> x=logspace(-1,2);>> y=exp(2*x);>> figure>> loglog(x,y,'-s');>> grid on
90
10. Graphiques en 2D
Dr. Keang Sè POUV
Echelles logarithmiques
loglog : log-log scale plotsemilogx : semi-log scale plot (logarithmic scale for the x-axis).semilogy : semi-log scale plot (logarithmic scale for the y-axis).
Exemples :
>> x=0:1000;>> y=log(x);>> figure>> semilogx(x,y)>> grid on
91
10. Graphiques en 2D
Dr. Keang Sè POUV
Autres représentations du graphique
Histogramme
hist(data) creates a histogram bar plot of data. Elements in data are sorted into 10 equally spaced bins along the x-axis. Bins are displayed as rectangles such that the height of each rectangle indicates the number of elements in the bin.hist(data,nbins) sorts data into the number of bins specified by the scalar nbins.
Exemples :
>> figure>> data = [0,2,9,2,5,8,7,3,1,9,4,3,5,8,10,0,1,2,9,5,10];>> hist(data)
hist sorts the values in data among 10 equally spaced bins between 0 and 10, the minimum and maximum values.
92
10. Graphiques en 2D
Dr. Keang Sè POUV
Autres représentations du graphique
Histogramme
hist(data) creates a histogram bar plot of data. Elements in data are sorted into 10 equally spaced bins along the x-axis. Bins are displayed as rectangles such that the height of each rectangle indicates the number of elements in the bin.hist(data,nbins) sorts data into the number of bins specified by the scalar nbins.
Exemples :
>> data=randn(50,2);>> nbins=5;>> hist(data,nbins)
randn : Normally distributed pseudorandom numbers.
93
10. Graphiques en 2D
Dr. Keang Sè POUV
Autres représentations du graphique
Barre
bar(Y) draws one bar for each element in Y.bar(x,Y) draws bars for each column in Y at locations specified in x.bar(___,style) specifies the style of the bars and can include any of the input arguments in previous syntaxes.
Exemples :
>> x=1990:2000;>> y=[200 250 270 300 340 410 440 450 600 620 810];>> figure>> bar(x,y)
Notice that the length(x) and length(y) have to be same.
94
10. Graphiques en 2D
Dr. Keang Sè POUV
Autres représentations du graphique
Escalier
stairs(Y) draws a stairstep graph of the elements in Y.stairs(X,Y) plots the elements in Y at the locations specified in X. The inputs X and Y must be vectors or matrices of the same size.
Exemples :
>> x=linspace(0,4*pi,50)';>> y=[0.5*cos(x), 2*cos(x)];>> figure>> stairs(x,y)
The first vector input, X, determines the x-axis positions for both data series.
95
10. Graphiques en 2D
Dr. Keang Sè POUV
Autres représentations du graphique
Escalier
stem(Y) plots the data sequence, Y, as stems that extend from a baseline along the x-axis. The data values are indicated by circles terminating each stem.stem(X,Y) plots the data sequence, Y, at values specified by X. The X and Y inputs must be vectors or matrices of the same size.
Exemples :
>> figure>> x=linspace(-10,10,30);>> y=x.^2-20;>> stem(x,y)
96
Chapitre 11
Graphiques en 3D
Dr. Keang Sè POUV
97
11. Graphiques en 3D
Dr. Keang Sè POUV
Courbes en 3D
The plot3 function displays a three-dimensional plot of a set of data points.plot3(X1,Y1,Z1,...), where X1, Y1, Z1 are vectors or matrices, plots one or more lines in three-dimensional space through the points whose coordinates are the elements of X1, Y1, and Z1.
Exemples :
>> x=-pi:pi/50:pi;>> y=cos(x);>> z=cos(x).*sin(x);>> plot3(y,z,x)
98
11. Graphiques en 3D
Dr. Keang Sè POUV
Surface en 3D
[X,Y] = meshgrid(xgv,ygv) replicates the grid vectors xgv and ygv to produce a full grid. This grid is represented by the output coordinate arrays X and Y. [X,Y,Z] = meshgrid(xgv,ygv,zgv) produces three-dimensional coordinate arrays.
Exemples :
>> [x,y]=meshgrid(10:13,1:3)x =
10 11 12 1310 11 12 1310 11 12 13
y =1 1 1 12 2 2 23 3 3 3
>> z=x+yz =
11 12 13 1412 13 14 1513 14 15 16
>> [x,y]=meshgrid(1:3,10:13)x =
1 2 31 2 31 2 31 2 3
y =10 10 1011 11 1112 12 1213 13 13
99
11. Graphiques en 3D
Dr. Keang Sè POUV
Surface en 3D
mesh(X,Y,Z) draws a wireframe mesh with color determined by Z, so color is proportional to surface height. If X and Y are vectors, length(X) = n and length(Y) = m, where [m,n] = size(Z). If X and Y are matrices, (X(i,j), Y(i,j), Z(i,j)) are the intersections of the wireframe grid lines.mesh(Z) draws a wireframe mesh using X = 1:n and Y = 1:m, where [m,n] = size(Z). The height, Z, is a single-valued function defined over a rectangular grid.
Exemples :
>> u=-5:.5:5;>> v=u;>> t=2*u.^2+2*v.^2;>> mesh(u,v,t);Error using mesh (line 79)Z must be a matrix, not a scalar or vector>> [u,v]=meshgrid(u,v);>> t=2*u.^2+2*v.^2;>> mesh(u,v,t)>> xlabel('u')>> ylabel('v')>> zlabel('t')
100
11. Graphiques en 3D
Dr. Keang Sè POUV
Surface en 3D
meshz : plot a curtain around mesh plot.
Exemples :
>> u=-5:.5:5;>> v=u;>> [u v]=meshgrid(u,v);>> t=2*u.^2+2*v.^2;>> meshz(u,v,t)>> xlabel('u');>> ylabel('v');>> zlabel('t');
101
11. Graphiques en 3D
Dr. Keang Sè POUV
Surface en 3D
Meshc : plot a contour graph under mesh graph
Exemples :
>> figure>> [x,y]=meshgrid(-3:.125:3);>> z=peaks(x,y);>> meshc(z);
peaks is a function of two variables, obtained by translatingand scaling Gaussian distributions.
102
11. Graphiques en 3D
Dr. Keang Sè POUV
Surface en 3D
surf : 3D shaded surface plot
Exemples :
>> [x,y,z]=sphere(30);>> figure>> surf(x,y,z)>> t=0:pi/10:2*pi;>> [x,y,z]=cylinder(2+cos(t));>> surf(x,y,z)
[X,Y,Z] = sphere(N) generates three (N+1)-by-(N+1) matrices so that SURF(X,Y,Z) produces a unit sphere.
[X,Y,Z] = cylinder(r) returns the x, y and zcoordinates of a cylinder using r to define a profile curve. cylinder treats each element in r as a radius at equally spaced heights along the unit height of the cylinder.
103
11. Graphiques en 3D
Dr. Keang Sè POUV
Surface en 3D
surfl : surface plot with colour map-based lighting.surfc : contour plot under a 3-D shaded surface plot.
Exemples :
surfl(x,y,z) surfc(x,y,z)
104
11. Graphiques en 3D
Dr. Keang Sè POUV
Contour
contour(X,Y,Z), contour(X,Y,Z,n), and contour(X,Y,Z,v) draw contour plots of Z using X and Y to determine the x- and y-axis limits. If X and Y are vectors, then the length of X must equal the number of columns in Z and the length of Y must equal the number of rows in Z. If X and Y are matrices, then their sizes must equal the size of Z.
Exemples :
>> x=-2:0.2:2;>> y=-2:0.2:3;>> [X,Y]=meshgrid(x,y);>> Z=X.*exp(-X.^2-Y.^2);>> figure>> contour(X,Y,Z,'ShowText','on')
Surf(X,Y,Z)
105
11. Graphiques en 3D
Dr. Keang Sè POUV
Contour
contour3 is the same as contour except that:• the contours are drawn at their corresponding Z level.• multiple patch objects are created instead of a contour group.• contour3 does not accept property-value pairs. Use SET instead on the patch
handles.
Exemples :
>> x=-2:0.2:2;>> y=-2:0.2:3;>> [X,Y]=meshgrid(x,y);>> Z=X.*exp(-X.^2-Y.^2);>> figure>> contour3(X,Y,Z,40)
N=40 est le nombre de lignesde contours selon Z.
106
11. Graphiques en 3D
Dr. Keang Sè POUV
Axes
axis : définit les échelles et l’apparence des axes. axis([xmin xmax ymin ymax]) sets the limits for the 2D axes of the current axes.axis([xmin xmax ymin ymax zmin zmax]) sets the limits for the 3D axes.axis auto sets default axes limits, based on the values of x, y, and z data. axis manual and axis(axis) freezes the scaling at the current limits, so that if hold is on, subsequent plots use the same limits.axis tight sets the axis limits to the range of the data.axis xy draws the graph in the default Cartesian axes format with the coordinate system origin in the lower left corner.axis equal sets the aspect ratio so that the data units are the same in every direction.axis square makes the current axes region square (or cubed when three-dimensional).axis normal automatically adjusts the aspect ratio of the axes and the relative scaling of the data units so that the plot fits the figure's shape as well as possible.axis off turns off all axis lines, tick marks, and labels.axis on turns on all axis lines, tick marks, and labels.
107
11. Graphiques en 3D
Dr. Keang Sè POUV
Axes
Exemples :
>> x=0:.01:pi/2;>> y=x.*sin(1./x);>> figure>> plot(x,y,'-')>> axis([0,pi/6,-0.3,0.3])
108
Chapitre 12
Structure de contrôle
Dr. Keang Sè POUV
109
12. Structure de contrôle
Dr. Keang Sè POUV
Fonctions d’entrée/sortie
Ouverture et fermeture de fichiers
fileID = fopen(filename) : opens the file, filename, for binary read access, and returns an integer file identifier equal to or greater than 3. If fopen cannot open the file, then fileID is -1.fclose(fileID) : closes an open file. fileID is an integer file identifier obtained from fopen.fclose('all') : closes all open files.
Exemple:>> fileID=fopen('Ex1.m')fileID =
3>> fileID=fclose('Ex1.m')fileID =
0
110
12. Structure de contrôle
Dr. Keang Sè POUV
Fonctions d’entrée/sortie
Entrées/sorties formatées
fprintf(formatSpec,A1,...,An) : formats data and displays the results on the screen.
Example: Print multiple numeric values and literal text to the screen.>> A1=[9.9,9900];>> A2=[8.8,8800];>> formatSpec='X is %4.2f meters or %8.3f mm\n';>> fprintf(formatSpec,A1,A2)X is 9.90 meters or 9900.000 mmX is 8.80 meters or 8800.000 mm
%4.2f in the formatSpec input specifies that the first value in each line of output is a floating-point number with a field width of four digits, including two digits after the decimal point. %8.3f in the formatSpec input specifies that the second value in each line of output is a floating-point number with a field width of eight digits, including three digits after the decimal point. \n is a control character that starts a new line. If you plan to read the file with Microsoft® Notepad, use '\r\n' instead of '\n' to move to a new line.
111
12. Structure de contrôle
Dr. Keang Sè POUV
Fonctions d’entrée/sortie
Entrées/sorties formatées
fscanf : Read data from text file.
Example: Create a sample text file that contains floating-point numbers.
>> x=100*rand(8,1);>> fileID=fopen('num.txt','w');>> fprintf(fileID,'%4.4f\r\n',x);>> fclose(fileID);>> type num.txt81.472490.579212.698791.337663.23599.754027.849854.6882w means write.
Open the file for reading, and obtain the file identifier, fileID.
>> fileID=fopen('num.txt','r');>> formatSpec='%f';>> A=fscanf(fileID,formatSpec)A =
81.472490.579212.698791.337663.23599.754027.849854.6882
>> fclose(fileID);
112
12. Structure de contrôle
Dr. Keang Sè POUV
Fonctions d’entrée/sortie
Entrées/sorties formatées
formatSpec : Format the output fields, specified as a string.The string can include a percent sign followed by a conversion character. The following table lists the available conversion characters and subtypes.
113
12. Structure de contrôle
Dr. Keang Sè POUV
Fonctions d’entrée/sortie
Entrées/sorties formatées
formatSpec : Format the output fields, specified as a string.The string can include a percent sign followed by a conversion character. The following table lists the available conversion characters and subtypes.
114
12. Structure de contrôle
Dr. Keang Sè POUV
Instruction « for »
for : Execute statements specified number of times.
Syntaxfor index = values
program statementsendDescriptionThis syntax repeatedly executes one or more MATLAB statements in a loop.
Examples:>> k=3;>> for m=1:kfor n=1:kM(m,n)=m+2*n;endend>> MM =
3 5 74 6 85 7 9
>> n=5;>> x=[];>> for i=1:nx=[x,sqrt(i)]end>> xx =
1.0000 1.4142 1.7321 2.0000 2.2361
115
12. Structure de contrôle
Dr. Keang Sè POUV
Instruction « while »
while : Repeatedly execute statements with an indefinite number of times while condition is true.
Syntaxwhile expression
statementsend
DescriptionThis syntax repeatedly executes one or more MATLAB program statements in a loop as long as an expression remains true.An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false.Expressions can include relational operators (such as < or ==) and logical operators (such as &&, ||, or ~). MATLAB evaluates compound expressions from left to right, adhering to operator precedence rules.
116
12. Structure de contrôle
Dr. Keang Sè POUV
Instruction « while »
while : Repeatedly execute statements with an indefinite number of times while condition is true.
Example:>> d=1;>> while d<8d=2*d+1endd =
3d =
7d =
15>> dd =
15
When d=1 then d=3Since d=3 is smaller than 8, the execution continues. So we replace d=3 in the equation and obtain d=7.Since d=7 is still smaller than 8, the execution continues.So we replace d=7 in the equation and obtain d=15.Since d=15 is bigger than 8, the execution stops.So the final answer is d=15.
117
12. Structure de contrôle
Dr. Keang Sè POUV
Instruction « while »
while : Repeatedly execute statements with an indefinite number of times while condition is true.
Example:>> n=5;>> year=2000;>> while n<40n=2*n+5;year=year+1;end>> nn =
75>> yearyear =
2003
118
12. Structure de contrôle
Dr. Keang Sè POUV
Instruction « break »
break : Terminate execution of f o r or w h i l e loop.
Syntaxbreak
Descriptionbreak terminates the execution of a for or while loop. Statements in the loop that appear after the break statement are not executed.
Example:
for k=-10:1:10if (k^2-50<0)
break;endval=k^2-50;
fprintf('\n k=%g val=%g',k,val);end
119
12. Structure de contrôle
Dr. Keang Sè POUV
Instruction « if »
if : Conditionally execute statements.
SyntaxIf expression
statementselseif expression
statementselse
statementsend
Description:i f e x p r e s s i o n , s t a t e m e n t s , e n d evaluates an expression, and executes a group of statements when the expression is true.
e l s e i f and e l s e are optional, and execute statements only when previous expressions in the i f block are false. An i f block can include multiple e l s e i fstatements.
120
12. Structure de contrôle
Dr. Keang Sè POUV
Instruction « if »
if : Conditionally execute statements.
Examples:% Preallocate a matrixnrows = 10;ncols = 10;myData = ones(nrows, ncols);% Loop through the matrixfor r = 1:nrows
for c = 1:ncolsif r == c
myData(r,c) = 2;elseif abs(r - c) == 1
myData(r,c) = -1;else
myData(r,c) = 0;end
endend
>> data(3,2)ans =
-1>> data(2,4)ans =
0>> data(5,5)ans =
2
121
12. Structure de contrôle
Dr. Keang Sè POUV
Instruction « save »
save : Save workspace variables to file.
Examples:
1. Save specific variable to MAT-File
p = rand(1,10);q = ones(10);save('pqfile.mat','p','q')
2. Save data to ASCII file
p = rand(1,10);q = ones(10);save('pqfile.txt','p','q','-ascii')type('pqfile.txt')
122
Références
Dr. Keang Sè POUV
[1] B. Delourme, Initiation aux projets numériques, 2014[2] H. Ly., Matlab, 2012[3] Mathworks, Release notes R2015a, 2015[4] J.L. Merrien, Analyse numérique avec Matlab, DUNOD, 2007[5] C. Vilain, Formation Initiation à Matlab, 2014
“Apprendre sans réfléchir est vain. Réfléchirsans apprendre est dangereux.”
Confucius(Chinese teacher, editor, politician and
philosopher, 551-479 BC)