poly mat lab

51
2008–2009

Upload: nisrine-rahmani

Post on 13-Apr-2015

34 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Poly Mat Lab

2008–2009

Page 2: Poly Mat Lab
Page 3: Poly Mat Lab

ecrins% matlab -nojvm

< M A T L A B >Copyright 1984-2006 The MathWorks, Inc.

Version 7.3.0.298 (R2006b)August 03, 2006

This is a Classroom License for instructional use only.Research and commercial use is prohibited.

To get started, type one of these: helpwin, helpdesk, or demo.For product information, visit www.mathworks.com.

>> quitecrins%

1

Page 4: Poly Mat Lab

>> help sin

SIN Sine.SIN(X) is the sine of the elements of X.

Overloaded methodshelp sym/sin.m

>> sin(2)

ans =

0.9093

>> SIN(2)??? Undefined variable or capitalized internal function SIN;Caps Lock may be on.

>> help

HELP topics:

matlab/general - General purpose commands.matlab/ops - Operators and special characters.matlab/lang - Programming language constructs.matlab/elmat - Elementary matrices and matrix manipulation.matlab/elfun - Elementary math functions.matlab/specfun - Specialized math functions.matlab/matfun - Matrix functions - numerical linear algebra.matlab/datafun - Data analysis and Fourier transforms.matlab/polyfun - Interpolation and polynomials.matlab/funfun - Function functions and ODE solvers.matlab/sparfun - Sparse matrices.matlab/graph2d - Two dimensional graphs.matlab/graph3d - Three dimensional graphs.matlab/specgraph - Specialized graphs.matlab/graphics - Handle Graphics.matlab/uitools - Graphical user interface tools.matlab/strfun - Character strings.matlab/iofun - File input/output.matlab/timefun - Time and dates.

2

Page 5: Poly Mat Lab

matlab/datatypes - Data types and structures.matlab/demos - Examples and demonstrations.toolbox/compiler - MATLAB Compilerimages/images - Image Processing Toolbox.images/imdemos - Image Processing Toolbox --- demos and sample imagestoolbox/local - Preferences.nnet/nnet - Neural Network Toolbox.nnet/nndemos - Neural Network Demonstrations.toolbox/optim - Optimization Toolbox.toolbox/signal - Signal Processing Toolbox.toolbox/stats - Statistics Toolbox.toolbox/symbolic - Symbolic Math Toolbox.toolbox/tour - MATLAB TourGraphics/MatDraw - MatDraw GUI Toolbox

For more help on directory/topic, type "help topic".

>> help matfun

>> a=2

a =

2

>> whosName Size Bytes Class

a 1x1 8 double array

Grand total is 1 elements using 8 bytes

>> clear>> whos>>

3

Page 6: Poly Mat Lab

>> x=[ 1 2 3 ]

x =

1 2 3

>> y=[ 2, 3, 4]

y =

2 3 4

>> z=[ 5 ; 6 ; 7]

z =

567

>> A=[1 2 ; 5 6 ; 7 8]

A =

1 25 67 8

>> b=[ 1 2 3 ] ; % Ceci est un commentaire pour souligner l’effet de ";">> whos

Name Size Bytes Class

A 3x2 48 double arrayb 1x3 24 double arrayx 1x3 24 double arrayy 1x3 24 double arrayz 3x1 24 double array

Grand total is 18 elements using 144 bytes

>> x

x =

4

Page 7: Poly Mat Lab

1 2 3

>> x+y

ans =

3 5 7

>> y + [ 4 5 7]

ans =

6 8 11

>> x=2.6

x =

2.6000

>> pi

ans =

3.1416>> 1/0

Warning: Divide by zero.

ans =

5

Page 8: Poly Mat Lab

Inf>> ans+1

ans =

Inf>> 0/0

Warning: Divide by zero.

ans =

NaN

>> i

ans =

0+ 1.0000i

>> sqrt(-1)

ans =

0+ 1.0000i

>> j

ans =

0+ 1.0000i>> j+1

ans =

1.0000+ 1.0000i

>> [ real(2+i) ; imag(2+i)]

ans =

2

6

Page 9: Poly Mat Lab

1

>> v=[ 2+i ; 4+7i]

v =

2.0000+ 1.0000i4.0000+ 7.0000i

>> [ real(v) imag(v)]

ans =

2 14 7

>> help isreal

ISREAL True for real array.ISREAL(X) returns 1 if all elements in X have zeroimaginary part and 0 otherwise.

˜ISREAL(X) detects complex arrays (i.e., arrays that havea non-zero real part).

See also REAL, IMAG, I, J.

>> 9ˆ1/2

ans =

4.5000

>> 9ˆ(1/2)

ans =

7

Page 10: Poly Mat Lab

3

Relational operators.eq - Equal ==ne - Not equal ˜=lt - Less than <gt - Greater than >le - Less than or equal <=ge - Greater than or equal >=

Logical operators.and - Logical AND &or - Logical OR |not - Logical NOT ˜xor - Logical EXCLUSIVE ORany - True if any element of vector is nonzeroall - True if all elements of vector are nonzero

>> (1>2) | 1

ans =

1

>>

8

Page 11: Poly Mat Lab

>> format % valeur par defaut (short)>> 137/7

ans =

19.5714

>> format long>> 137/7

ans =

19.57142857142857

>> format short e>> 137/7

ans =

1.9571e+01

>> format long e>> 137/7

ans =

1.957142857142857e+01

>>

>> v=[ 10 11 12 ]

v =

10 11 12

>> v(1)

ans =

10

9

Page 12: Poly Mat Lab

>> A=[ 1 2 3 ; 4 5 6 ; 7 8 9]

A =

1 2 34 5 67 8 9

>> A(3,2)

ans =

8

>> A(2,2)=45

A =

1 2 34 45 67 8 9

>> A(:)

ans =

1472

458369

>> A(5)

ans =

45

>> A(1,:)

ans =

1 2 3

10

Page 13: Poly Mat Lab

>> A(:,3)

ans =

369

>> A(3,:)=v

A =

1 2 34 45 6

10 11 12

>> length(v)

ans =

3

>> size(A)

ans =

3 3>> [nbligne,nbcol]=size(A)

nbligne =

3

nbcol =

3>> size(A,2)

ans =

3

11

Page 14: Poly Mat Lab

>> B=zeros(2,2)

B =

0 00 0

>> B=zeros(size(A))

B =

0 0 00 0 00 0 0

>> D=eye(3)

D =

1 0 00 1 00 0 1

>> E=diag(v)

E =

10 0 00 11 00 0 12

>> C=ones(size(B,1),size(B,2),size(A,1))

C(:,:,1) =

1 1 11 1 11 1 1

C(:,:,2) =

12

Page 15: Poly Mat Lab

1 1 11 1 11 1 1

C(:,:,3) =

1 1 11 1 11 1 1

>> alea=rand(4,3)

alea =

0.9501 0.8913 0.82140.2311 0.7621 0.44470.6068 0.4565 0.61540.4860 0.0185 0.7919

>> x=[3:7] % ou x=3:7

x =

3 4 5 6 7

>> x=[2:2:14]

x =

2 4 6 8 10 12 14

>> x=[0:0.1:1]

x =

Columns 1 through 7

0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000

Columns 8 through 11

0.7000 0.8000 0.9000 1.0000

13

Page 16: Poly Mat Lab

>> A=[ 2 3 4; 4 5 6]

A =

2 3 44 5 6

>> A’

ans =

2 43 54 6

>> B=[ 1 2 ; 3 4 ; 8 9]

B =

1 23 48 9

>> B+A’

ans =

3 66 9

12 15

>> A*B % produit de matrices de tailles compatibles

ans =

43 5267 82

>> A*B’??? Error using ==> *Inner matrix dimensions must agree.

>> 1+A

14

Page 17: Poly Mat Lab

ans =

3 4 55 6 7

>> A+ones(size(A))

ans =

3 4 55 6 7

>> B*2 % multiplication par un scalaire

ans =

2 46 8

16 18>> B= eye(2)

B =

1 00 1

>> B=B+1;>> B

B =

2 11 2

>> Bˆ2

ans =

5 44 5

>> A

A =

2 3 4

15

Page 18: Poly Mat Lab

4 5 6

>> C=[ 1 2 1 ; 1 2 1];>> A.*C % terme a terme

ans =

2 6 44 10 6

>> A.ˆ2 % terme a terme

ans =

4 9 1616 25 36

>> A./rand(size(A)) % terme a terme

ans =

2.1696 17.0197 4.27595.4185 12.3242 6.5438

>> v=rand(2)

v =

0.4103 0.05790.8936 0.3529

>> v<0.40

ans =

0 10 1

>> b=(v >= 0.7);>> cos(b)

ans =

1.0000 1.00000.5403 1.0000

>> help min

16

Page 19: Poly Mat Lab

MIN Smallest component.For vectors, MIN(X) is the smallest element in X. For matrices,MIN(X) is a row vector containing the minimum element from eachcolumn. For N-D arrays, MIN(X) operates along the firstnon-singleton dimension.

[Y,I] = MIN(X) returns the indices of the minimum values in vector I.If the values along the first non-singleton dimension contain morethan one minimal element, the index of the first one is returned.

MIN(X,Y) returns an array the same size as X and Y with thesmallest elements taken from X or Y. Either one can be a scalar.

[Y,I] = MIN(X,[],DIM) operates along the dimension DIM. SupposeX=[2 8 4;7 3 9] then min(X,[],1) is [2 3 4] and min(X,[],2) is [2,3].

When complex, the magnitude MIN(ABS(X)) is used. NaN’s are ignoredwhen computing the minimum.

Example: If X = [2 8 4 then min(X,[],1) is [2 3 4],7 3 9]

min(X,[],2) is [2 and min(X,5) is [2 5 43], 5 3 5].

See also MAX, MEDIAN, MEAN, SORT.

>> v= randperm(10)

v =

4 1 6 10 8 2 5 9 7 3

>> [vtri,indices]=sort(v)

vtri =

1 2 3 4 5 6 7 8 9 10

indices =

2 6 10 1 7 3 9 5 8 4

17

Page 20: Poly Mat Lab

>> A=rand(4,4)

A =

0.8132 0.1987 0.0153 0.46600.0099 0.6038 0.7468 0.41860.1389 0.2722 0.4451 0.84620.2028 0.1988 0.9318 0.5252

>> A(2:3,3:4)

ans =

0.7468 0.41860.4451 0.8462

>> A(:,2)

ans =

0.19870.60380.27220.1988

>> A([1 3],[4,2])

ans =

0.4660 0.19870.8462 0.2722

>> B=A(1:2,:)

B =

0.8132 0.1987 0.0153 0.46600.0099 0.6038 0.7468 0.4186

>> B=A(1:2,1:2)

B =

0.8132 0.19870.0099 0.6038

>> B(:)

18

Page 21: Poly Mat Lab

ans =

0.81320.00990.19870.6038

>> [i,j]=find(B>0.5)

i =

12

j =

12

>> l=find(B>0.5)

l =

14

>> B(l)=ones(size(B(l)))

B =

1.0000 0.19870.0099 1.0000

>> A(1:2,1:2)=B % retour a l’envoyeur apres modifs

A =

1.0000 0.1987 0.0153 0.46600.0099 1.0000 0.7468 0.41860.1389 0.2722 0.4451 0.84620.2028 0.1988 0.9318 0.5252

>> A=[1 2 3; 4 5 6]

A =

1 2 3

19

Page 22: Poly Mat Lab

4 5 6

>> b=reshape(A,3,2)

b =

1 54 32 6

v =

1 2 3

>> l=[v v]

l =

1 2 3 1 2 3

>> m=[]

m =

[]

>> m=[m; [ 3 4]]

m =

3 4

>> m=[m; [ 3 5]]

m =

3 43 5

>> A=rand(2,2);>> B=A+rand;>> A

A =

0.2987 0.28440.6614 0.4692

20

Page 23: Poly Mat Lab

>> B

B =

0.3635 0.34920.7262 0.5340

>> C=[A B]

C =

0.2987 0.2844 0.3635 0.34920.6614 0.4692 0.7262 0.5340

>> a11=rand(2,2);>> a12=rand(2,2);>> a21=rand(3,2);>> a22=rand(3,2);>> ma=[ a11 a12 ; ...

a21 a22]

ma =

0.8214 0.6154 0.9218 0.17630.4447 0.7919 0.7382 0.40570.9355 0.8936 0.8132 0.20280.9169 0.0579 0.0099 0.19870.4103 0.3529 0.1389 0.6038

>> A=rand(3,3)

A =

21

Page 24: Poly Mat Lab

0.3046 0.6822 0.15090.1897 0.3028 0.69790.1934 0.5417 0.3784

>> b=rand(3,1)

b =

0.86000.85370.5936

>> x=A\b

x =

3.9958-0.61270.4031

>> A*x-b

ans =

1.0e-15 *

0.11100.11100.1110

22

Page 25: Poly Mat Lab

x =

0 1 2 3 4 5

>> y=2*x+4

y =

4 6 8 10 12 14

>> plot(x,y,’r+’)>> hold on>> plot(x,y)

0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 54

5

6

7

8

9

10

11

12

13

14

>> grid>> xlabel(’x’)>> ylabel(’axe y’)>> title(’ mon affichage’);

>> z=rand(5,5)

z =

23

Page 26: Poly Mat Lab

0.5341 0.3704 0.6213 0.1730 0.73730.7271 0.7027 0.7948 0.9797 0.13650.3093 0.5466 0.9568 0.2714 0.01180.8385 0.4449 0.5226 0.2523 0.89390.5681 0.6946 0.8801 0.8757 0.1991

>> mesh(z)

12

34

5

1

2

3

4

50

0.2

0.4

0.6

0.8

1

>> x=-pi:pi/10:pi;>> y=x;>> [X,Y]=meshgrid(x,y);>> Z=(-X.ˆ2+Y.ˆ2/4)/2;>> figure>> mesh(X,Y,Z);>> xlabel(’x’)>> ylabel(’y’)>> zlabel(’z’)>> title(’paraboloide hyperbolique : 2z=(-xˆ2+yˆ2/4)’);>> hold on>> plot3(X,Y,Z,’k*’)

24

Page 27: Poly Mat Lab

−4−2

02

4

−4

−2

0

2

4−5

−4

−3

−2

−1

0

1

2

x

paraboloide hyperbolique : 2z=(−x2+y2/4)

y

z

SUBPLOT Create axes in tiled positions.SUBPLOT(m,n,p), or SUBPLOT(mnp), breaks the Figure window intoan m-by-n matrix of small axes, selects the p-th axes forfor the current plot, and returns the axis handle. The axesare counted along the top row of the Figure window, then thesecond row, etc. For example,

SUBPLOT(2,1,1), PLOT(income)SUBPLOT(2,1,2), PLOT(outgo)

plots income on the top half of the window and outgo on thebottom half.

>> figure>> subplot(2,2,1),plot3(X,Y,Z,’b+’)>> subplot(2,2,2),plot(X,Z,’b+’)>> subplot(2,2,3),mesh(X,Y,Z)>> subplot(2,2,4),surf(X,Y,Z)

25

Page 28: Poly Mat Lab

−50

5

−5

0

5−5

0

5

−4 −2 0 2 4−5

−4

−3

−2

−1

0

1

2

−50

5

−5

0

5−5

0

5

−50

5

−5

0

5−5

0

5

>> a=[ 2 3 4 ; ...5 6 7 ]

a =

2 3 45 6 7

>> a=10; b=56;

26

Page 29: Poly Mat Lab

>> a = 4

a =

4

>> b= 6

b =

6

>> save toto a b>> ls % ou dir pour examiner le contenu du repertoire courantans =

toto.mat

>> clear>> who>> load toto>> who

Your variables are:

a b

>>

MATLAB C or Fortran Description’char’ ’char*1’ character, 8 bits’uchar’ ’unsigned char’ unsigned character, 8 bits’schar’ ’signed char’ signed character, 8 bits’int8’ ’integer*1’ integer, 8 bits.

27

Page 30: Poly Mat Lab

’int16’ ’integer*2’ integer, 16 bits.’int32’ ’integer*4’ integer, 32 bits.’int64’ ’integer*8’ integer, 64 bits’uint8’ ’integer*1’ unsigned integer, 8 bits.’uint16’ ’integer*2’ unsigned integer, 16 bits.’uint32’ ’integer*4’ unsigned integer, 32 bits.’uint64’ ’integer*8’ unsigned integer, 64 bits’float32’ ’real*4’ floating point, 32 bits.’float64’ ’real*8’ floating point, 64 bits.

>> help diary

DIARY Save text of MATLAB session.DIARY file_name causes a copy of all subsequent terminal inputand most of the resulting output to be written on the namedfile. DIARY OFF suspends it. DIARY ON turns it back on.DIARY, by itself, toggles the diary state.

Use the functional form of DIARY, such as DIARY(’file’),when the file name is stored in a string.

>> monscript

28

Page 31: Poly Mat Lab

>> help function

FUNCTION Add new function.New functions may be added to MATLAB’s vocabulary if theyare expressed in terms of other existing functions. Thecommands and functions that comprise the new function mustbe put in a file whose name defines the name of the newfunction, with a filename extension of ’.m’. At the top ofthe file must be a line that contains the syntax definitionfor the new function. For example, the existence of a fileon disk called STAT.M with:

function [mean,stdev] = stat(x)n = length(x);mean = sum(x) / n;stdev = sqrt(sum((x - mean).ˆ2)/n);

defines a new function called STAT that calculates themean and standard deviation of a vector. The variableswithin the body of the function are all local variables.See SCRIPT for procedures that work globally on the work-space.

Normally functions return when the end of the functionis reached. A RETURN statement can be used to force an earlyreturn.

See also SCRIPT, RETURN, VARARGIN, VARARGOUT, NARGIN, NARGOUT,INPUTNAME.

29

Page 32: Poly Mat Lab

global a

a=2;

[b,c]=fonc(a);

[b,c]=fonc2(a); %4,1

monscript.mfonc.m

function [d,e]=fonc(pformel)a=3; % locale par defaut

d=a+pformel;e=a-1;

fonc2.m

function [d,e]=fonc2(pformel)global a

d=a+pformel;e=a-1;

%5,2

IF IF statement condition.The general form of the IF statement is

IF expressionstatements

ELSEIF expressionstatements

ELSEstatements

END

The statements are executed if the real part of the expressionhas all non-zero elements. The ELSE and ELSEIF parts are optional.Zero or more ELSEIF parts can be used as well as nested IF’s.The expression is usually of the form expr rop expr whererop is ==, <, >, <=, >=, or ˜=.

Exampleif I == J

A(I,J) = 2;

30

Page 33: Poly Mat Lab

elseif abs(I-J) == 1A(I,J) = -1;

elseA(I,J) = 0;

end

FOR Repeat statements a specific number of times.The general form of a FOR statement is:

FOR variable = expr, statement, ..., statement END

The columns of the expression are stored one at a time inthe variable and then the following statements, up to theEND, are executed. The expression is often of the form X:Y,in which case its columns are simply scalars. Some examples(assume N has already been assigned a value).

FOR I = 1:N,FOR J = 1:N,

A(I,J) = 1/(I+J-1);END

END

FOR S = 1.0: -0.1: 0.0, END steps S with increments of -0.1FOR E = EYE(N), ... END sets E to the unit N-vectors.

The BREAK statement can be used to terminate the loop prematurely.

Un exemple de boucle while : E = 0*A; F = E + eye(size(E)); N = 1;while norm(E+F-E,1) > 0,

E = E + F;F = A*F/N;N = N + 1;

end

31

Page 34: Poly Mat Lab

>> chaine=’bonjour monsieur’

chaine =

bonjour monsieur

>> chaine(2)=’i’

chaine =

binjour monsieur>> v=[’bonjour’ ’monsieur’]

v =

bonjourmonsieurv=[’bonjour’ ’ ’ ’monsieur’]v =

bonjour monsieur>> v==chaine

ans =

Columns 1 through 12

1 0 1 1 1 1 1 1 1 1 1 1

Columns 13 through 16

1 1 1 1

>> v=’ janvier’

v =

32

Page 35: Poly Mat Lab

janvier>> u=[v ’8’ ; ’ tonton’]??? All rows in the bracketed expression must have the samenumber of columns.

>> u=[v ’8’ ; ’ tonton 9’]

u =

janvier8tonton 9

>> help num2str

NUM2STR Convert number to string.T = NUM2STR(X) converts the matrix X into a string representation Twith about 4 digits and an exponent if required. This is useful forlabeling plots with the TITLE, XLABEL, YLABEL, and TEXT commands.

T = NUM2STR(X,N) converts the matrix X into a string representationwith a maximum N digits of precision. The default number of digits isbased on the magnitude of the elements of X.

T = NUM2STR(X,FORMAT) uses the format string FORMAT (see SPRINTF fordetails).

Example:num2str(randn(2,2),3) produces the string matrix

’-0.433 0.125’’ -1.67 0.288’

>> eval(’1+2’)

ans =

3>> x=3

x =

3

33

Page 36: Poly Mat Lab

>> expression=’x+7’

expression =

x+7

>> eval(expression)

ans =

10>> feval(’zeros’,2,2)

ans =

0 00 0

>> A=[0 0 1 ; 1 0 2 ; 0 -3 0]

A =

0 0 11 0 20 -3 0

>> S=sparse(A)

S =

(2,1) 1(3,2) -3(1,3) 1(2,3) 2

>> whosName Size Bytes Class

A 3x3 72 double arrayS 3x3 64 sparse array

Grand total is 13 elements using 136 bytes

34

Page 37: Poly Mat Lab

>> A=sparse(3,2)

A =

All zero sparse: 3-by-2

>> A(1,2)=9

A =

(1,2) 9

>> A(3,2)=5

A =

(1,2) 9(3,2) 5

>>

function fx = f(x)fx.Value=(x(1)-1)ˆ2+x(1)*x(2);fx.Gradient = [2*(x(1)-1)+x(2); x(1)];fx.Hessien = [2 1 ; 1 0];

35

Page 38: Poly Mat Lab

>> x = [2;1]x =

21

>> f(x)

ans =

Value: 3Gradient: [2x1 double]Hessien: [2x2 double]

>> whosName Size Bytes Class

ans 1x1 428 struct arrayx 2x1 16 double array

Grand total is 12 elements using 444 bytes>> gx=f(x);>> gx

gx =

Value: 3Gradient: [2x1 double]Hessien: [2x2 double]

>> fieldnames(gx)

ans =

’Value’’Gradient’’Hessien’

>> gx.Value=9 %affectation

gx =

Value: 9Gradient: [2x1 double]Hessien: [2x2 double]

36

Page 39: Poly Mat Lab

>> A{1}=x;>> A{2}=gx;>> A

A =

[2x1 double] [1x1 struct]>> B={x,gx,4}

B =

[2x1 double] [1x1 struct] [4]>> s={{},{8},9}

s =

{} {1x1 cell} [9]>> s{2}

ans =

[8]

37

Page 40: Poly Mat Lab

void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])

ptr = mxGetPr(prls[i]) renvoie un pointeur sur le parametre i (partiereelle)

ptr=mxGetPi(prls[i]) renvoie un pointeur sur le parametre i (partieimaginaire)

m=mxGetM(prls[i]) nombre de ligne du parametre im=mxGetN(prls[i]) nombre de colonne du parametre imat=mxCreateDoubleMatrix(m,n,mxReal) creation d’une matrice de reels double

precisionmxCalloc mxMalloc mxFree mxDestryArray allocation liberation d’espace memoire

38

Page 41: Poly Mat Lab

mxIs{Double,Char,COmplex,Real) test de typemexPrintf affichage

void mexCallMATLAB( int nlhs, mxArray *plhs[],int nrhs,const mxArray *prhs[],char *fun)

%% Test de la fonction exemple_mex compilee avec mex% pour compiler exemple_mex.c en exemple_mex.mexsol% on utilise la commande ’mex -inline exemple_mex.c’%

IN = zeros(4,3);

[OUT1,OUT2,OUT3]=exemple_mex(IN);INOUT1OUT2OUT3

/* Fichier d’exemple d’utilisation d’un fichier C destine a etre compile en me/* La fonction est appellee sous MATLAB de la maniere suivante :*//* [OUT1,OUT2,OUT3]=exemple_mex(IN), avec OUT1, OUT2, OUT3 et IN de meme taill/* Le fonctionnement de l’interfacage entre les parametres MATLAB et les param/* 4 parametres sont passees a la fonction mexFunction *//* void mexFunction(/* int nlhs, mxArray *plhs[],*//* int nrhs, const mxArray *prhs[]*//* ) *//* nlhs : nombre de parametres en sortie *//* nrhs : nombre de parametres en entree *//* plhs[i] : ieme parametre en sortie *//* prhs[i] : ieme parametre en entree *//* La routine mxGetPr permet de recuperer un pointeur vers un des parametres :/* ptr_in_i = mxGetPr(prhs[i]); : pointeur vers le ieme parametre en entree *//* Attention, le type de ptr_in_i doit etre un pointeur sur un type compatible/* Cas des matrices : *//* Les matrices sont converties lors du passage de parametre de MATLAB vers C

39

Page 42: Poly Mat Lab

/* deux cas d’utilisation sont presentes : *//* utilisation du vecteur et utilisation d’une matrice intermediaire *//* Fonctionnement de la routine testee : *//* [OUT1,OUT2,OUT3] = exemple_mex(IN) avec IN:4*3, OUT1:4*3, OUT2:4*3, OUT3:4*/* OUT_1=IN+1+increment ; *//* OUT_2=IN+1+increment ; *//* OUT_3=IN+1+increment ; *//* Si on supprime la declaration de matrices statiques *//* les tailles des matrices en parametre peuvent etre *//* quelconques */

#include <math.h>#include "mex.h"

#define VECT_IN prhs[0] /* Pointeur vers le premier parametre en entree */#define VECT_OUT_1 plhs[0] /* Pointeur vers le premier parametre en sortie */#define VECT_OUT_2 plhs[1] /* Pointeur vers le deuxieme parametre en sortie */#define VECT_OUT_3 plhs[2] /* Pointeur vers le troisieme parametre en sortie *

void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]

){double *vect_in; /* Pointeur vers le vecteur interne d’entree */double *vect_out_1;/* Pointeur vers le premier vecteur de sortie */double *vect_out_2;/* Pointeur vers le second vecteur de sortie */double *vect_out_3;/* Pointeur vers le troisieme vecteur de sortie */double mat_in_aux[4][3]; /* Matrice intermediaire en entree */double mat_out_aux[4][3]; /* Matrice intermediaire en sortie */double **mat_in_aux_dyn; /* Matrice allouee dynamiquement en entree */double **mat_out_aux_dyn; /* Matrice allouee dynamiquement en sortie */

int m,n;int i,j;

/********************************************//* Recuperation de la taille des matrices */

/* Nombre de lignes du tableau en entree */m=mxGetM(VECT_IN);/* Nombre de colonnes du tableau en entree */n=mxGetN(VECT_IN);

40

Page 43: Poly Mat Lab

/* le pointeur pointe vers le vecteur MATLAB passe en entree */vect_in = mxGetPr(VECT_IN);

/********************************************//* Utilisation du vecteur */

/* Creation d’un vecteur de taille mn en sortie */VECT_OUT_1 = mxCreateDoubleMatrix(m,n,mxREAL);/* le premier pointeur pointe vers le vecteur MATLAB passe en sortie */vect_out_1 = mxGetPr(VECT_OUT_1);

/* Passage du vecteur d’entree au vecteur de sortie */for(i=0;i<m*n;i++)

vect_out_1[i] = vect_in[i]+1+i;

/********************************************//* Utilisation de la matrice intermediaire */

/* Creation d’un vecteur de taille mn en sortie */VECT_OUT_2 = mxCreateDoubleMatrix(m,n,mxREAL);

/* le deuxieme pointeur pointe vers le vecteur MATLAB passe en sortie */vect_out_2 = mxGetPr(VECT_OUT_2);

/* Passage du vecteur d’entree a la matrice d’entree */for(j=0;j<n;j++)for(i=0;i<m;i++)mat_in_aux[i][j]=vect_in[j*m+i];

/* Passage de la matrice d’entree a la matrice de sortie */for(i=0;i<m;i++)for(j=0;j<n;j++)mat_out_aux[i][j]=mat_in_aux[i][j]+2;

/* Passage de la matrice de sortie au vecteur de sortie */for(j=0;j<n;j++)for(i=0;i<m;i++)vect_out_2[j*m+i]=mat_in_aux[i][j]+1+j*m+i;

/********************************************//* Utilisation de l’allocation dynamique */

/* La matrice pointe vers un vecteur de pointeurs sur des doubles */mat_in_aux_dyn= malloc(m*sizeof(double*));for(i=0;i<m;i++)/* Chaque element du vecteur precedent pointe vers une ligne de doubles*/

41

Page 44: Poly Mat Lab

mat_in_aux_dyn[i] = malloc(n*sizeof(double));

/* La matrice pointe vers un vecteur de pointeurs sur des doubles */mat_out_aux_dyn= malloc(m*sizeof(double*));for(i=0;i<m;i++)/* Chaque element du vecteur precedent pointe vers une ligne de doubles*/mat_out_aux_dyn[i] = malloc(n*sizeof(double));

/* Creation d’un vecteur de taille mn en sortie */VECT_OUT_3 = mxCreateDoubleMatrix(m,n,mxREAL);

/* le troisieme pointeur pointe vers le vecteur MATLAB passe en sortie */vect_out_3 = mxGetPr(VECT_OUT_3);

/* Passage du vecteur d’entree a la matrice d’entree */for(j=0;j<n;j++)for(i=0;i<m;i++)mat_in_aux_dyn[i][j]=vect_in[j*m+i];

/* Passage de la matrice d’entree a la matrice de sortie */for(i=0;i<m;i++)for(j=0;j<n;j++)mat_out_aux_dyn[i][j]=mat_in_aux_dyn[i][j]+2;

/* Passage de la matrice de sortie au vecteur de sortie */for(j=0;j<n;j++)for(i=0;i<m;i++)vect_out_3[j*m+i]=mat_in_aux_dyn[i][j]+1+j*m+i;

return;}

SUBROUTINE MEXFUNCTION(NLHS,PLHS,LRHS,PRHS)INTEGER*4 NLHS,NRHSINTEGER*4 PLHS(*), PRHS(*)

42

Page 45: Poly Mat Lab

%% Test de la fonction exemple_mex compilee avec mex% pour compiler exemple_mex.c en exemple_mex.mexsol% on utilise la commande ’mex -inline exemple_mex.c’%

IN = zeros(4,3);for i=1:4,for j=1:3,IN(i,j) = rand(1); % on aurait mieux fait d’utiliser rand(4,3) !end

end

[OUT]=exemple_mex_g(IN);INOUT

SUBROUTINE EXEMPLE_MEX(OUT,IN,M,N)REAL*8 OUT(4,3), IN(4,3)INTEGER*4 M,NINTEGER*4 I, J

DO 10 I=1,MDO 20 J=1,NOUT(I,J) = IN(I,J)+IWRITE(*,100) OUT(I,J)

100 FORMAT(F7.5)20 CONTINUE10 CONTINUE

RETURNEND

43

Page 46: Poly Mat Lab

CC

SUBROUTINE MEXFUNCTION(NLHS, PLHS, NRHS, PRHS)C-----------------------------------------------------C (pointer) Replace integer by integer*8 on the DEC Alpha andC the SGI 64-bit platformsC

INTEGER*4 PLHS(*), PRHS(*)

C-----------------------------------------------------C

INTEGER*4 NLHS, NRHSCC-----------------------------------------------------C (pointer) Replace integer by integer*8 on the DEC Alpha andC the SGI 64-bit platformsC

INTEGER*4 MXCREATEFULL, MXGETPR

C-----------------------------------------------------C

INTEGER*4 MXGETM, MXGETNCC KEEP THE ABOVE SUBROUTINE, ARGUMENT, AND FUNCTION DECLARATIONSC FOR USE IN ALL YOUR FORTRAN MEX FILES.C-----------------------------------------------------CC-----------------------------------------------------C (pointer) Replace integer by integer*8 on the DEC Alpha andC the SGI 64-bit platformsC

INTEGER*4 OUT, IN

C-----------------------------------------------------C

INTEGER*4 M, N

44

Page 47: Poly Mat Lab

CM = MXGETM(PRHS(1))N = MXGETN(PRHS(1))

CC CREATE A MATRIX FOR RETURN ARGUMENTC

PLHS(1) = MXCREATEFULL(M,N,0)CC ASSIGN POINTERS TO THE VARIOUS PARAMETERSC

OUT = MXGETPR(PLHS(1))C

IN = MXGETPR(PRHS(1))CC DO THE ACTUAL COMPUTATIONS IN A SUBROUTINEC CREATED ARRAYS.C

CALL EXEMPLE_MEX(%VAL(OUT),%VAL(IN),M,N)CC COPY OUTPUT WHICH IS STORED IN LOCAL ARRAY TO MATRIX OUTPUTC

RETURNEND

>> help sym

--- help for sym/sym.m ---

SYM Construct symbolic numbers, variables and objects.S = SYM(A) constructs an object S, of class ’sym’, from A.If the input argument is a string, the result is a symbolic numberor variable. If the input argument is a numeric scalar or matrix,the result is a symbolic representation of the given numeric values.

x = sym(’x’) creates the symbolic variable with name ’x’ and storesthe result in x. alpha = sym(’alpha’) and r = sym(’Rho’) are otherexamples. etc...

>> a=sym(’x’)

a =

x

>> whos

45

Page 48: Poly Mat Lab

Name Size Bytes Class

a 1x1 126 sym object

Grand total is 2 elements using 126 bytes

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Calcul Symbolique%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

x = sym (’[x(1) x(2) x(3)]’)

% Copier - Coller a partir de l’expression de la fonction% de Brown interpretable en MATLAB

fdex = ...sqrt( (x(1)ˆ2) ˆ (x(2)ˆ2 + 1) ...

+(x(2)ˆ2) ˆ (x(1)ˆ2 + 1) ...+(x(2)ˆ2) ˆ (x(3)ˆ2 + 1) ...+(x(3)ˆ2) ˆ (x(2)ˆ2 + 1) ...

)

% On transforme les x(i) en xi grace au "subs"

syms x1 x2 x3fdex = subs (fdex , {sym(’x(1)’), sym(’x(2)’),sym(’x(3)’)} , {x1,x2,x3})

dfdex = jacobian (fdex ,[x1,x2,x3])

% On transforme les xi en x(i) grace au "subs" inverse

dfdex = subs (dfdex,{x1,x2,x3} , {sym(’x(1)’), sym(’x(2)’),sym(’x(3)’)})

% Et voici le resultat que l’on peut copier-coller dans la fonction grad_brown% simplify transforme log(xi ˆ2) en 2*log(xi)!!!

dfdex = ...[1/2/((x(1)ˆ2)ˆ(x(2)ˆ2+1)+(x(2)ˆ2)ˆ(x(1)ˆ2+1)+(x(2)ˆ2)ˆ(x(3)ˆ2+1)+(x(3)ˆ2)ˆ(x(2)ˆ2+1))ˆ(1/2)*(2*(x(1)ˆ2)ˆ(x(2)ˆ2+1)*(x(2)ˆ2+1)/x(1)+2*(x(2)ˆ2)ˆ(x(1)ˆ2+1)*x(1)*log(x(2)ˆ2)),1/2/((x(1)ˆ2)ˆ(x(2)ˆ2+1)+(x(2)ˆ2)ˆ(x(1)ˆ2+1)+(x(2)ˆ2)ˆ(x(3)ˆ2+1)+

(x(3)ˆ2)ˆ(x(2)ˆ2+1))ˆ(1/2)*(2*(x(1)ˆ2)ˆ(x(2)ˆ2+1)*x(2)*log(x(1)ˆ2)+2*(x(2)ˆ2)ˆ(x(1)ˆ2+1)*(x(1)ˆ2+1)/x(2)+2*(x(2)ˆ2)ˆ(x(3)ˆ2+1)*(x(3)ˆ2+1)/x(2)+2*(x(3)ˆ2)ˆ(x(2)ˆ2+1)*x(2)*log(x(3)ˆ2)),1/2/((x(1)ˆ2)ˆ(x(2)ˆ2+1)+(x(2)ˆ2)ˆ(x(1)ˆ2+1)+(x(2)ˆ2)ˆ(x(3)ˆ2+1)+(x(3)ˆ2)ˆ(x(2)ˆ2+1))ˆ(1/2)*(2*(x(2)ˆ2)ˆ(x(3)ˆ2+1)*x(3)*log(x(2)ˆ2)+2*(x(3)ˆ2)ˆ(x(2)ˆ2+1)*(x(2)ˆ2+1)/x(3))]

46

Page 49: Poly Mat Lab

pretty (dfdex)

>> help menu

MENU Generate a menu of choices for user input.K = MENU(’Choose a color’,’Red’,’Blue’,’Green’) displays onthe screen:

----- Choose a color -----

1) Red2) Blue3) Green

Select a menu number:

The number entered by the user in response to the prompt isreturned. On machines that support it, the local menu systemis used. The maximum number of menu items is 32.

See also UIMENU.

47

Page 50: Poly Mat Lab

>> help uitools

Graphical user interface tools.

GUI functions.uicontrol - Create user interface control.uimenu - Create user interface menu.ginput - Graphical input from mouse.dragrect - Drag XOR rectangles with mouse.rbbox - Rubberband box.selectmoveresize - Interactively select, move, resize, or copy objects.waitforbuttonpress - Wait for key/buttonpress over figure.waitfor - Block execution and wait for event.uiwait - Block execution and wait for resume.uiresume - Resume execution of blocked M-file.

GUI design tools.guide - Design GUI.align - Align uicontrols and axes.cbedit - Edit callback.menuedit - Edit menu.propedit - Edit property.

Dialog boxes.dialog - Create dialog figure.axlimdlg - Axes limits dialog box.errordlg - Error dialog box.helpdlg - Help dialog box.inputdlg - Input dialog box.listdlg - List selection dialog box.menu - Generate menu of choices for user input.msgbox - Message box.questdlg - Question dialog box.warndlg - Warning dialog box.uigetfile - Standard open file dialog box.uiputfile - Standard save file dialog box.uisetcolor - Color selection dialog box.uisetfont - Font selection dialog box.pagedlg - Page position dialog box.printdlg - Print dialog box.waitbar - Display wait bar.

Menu utilities.makemenu - Create menu structure.menubar - Computer dependent default setting for MenuBar property.umtoggle - Toggle "checked" status of uimenu object.winmenu - Create submenu for "Window" menu item.

48

Page 51: Poly Mat Lab

Toolbar button group utilities.btngroup - Create toolbar button group.btnstate - Query state of toolbar button group.btnpress - Button press manager for toolbar button group.btndown - Depress button in toolbar button group.btnup - Raise button in toolbar button group.

User-defined figure/axes property utilities.clruprop - Clear user-defined property.getuprop - Get value of user-defined property.setuprop - Set user-defined property.

49