Sunteți pe pagina 1din 16

Limbajeavansatedeprogramare MATLAB

CURS1

PREZENTAREGENERAL
MATLAB=Limbajdenaltperformanpentruproiectareaasistatdecalculator. MATLAB este n acelai timp un limbaj de programare i un sistem de dezvoltare care integreaz calculul, vizualizarea i programarea ntrun mediu uor de utilizat (easytouse), problemele i soluiileacestorproblemefiindexprimatentrunlimbajmatematicaccesibil. Domeniideutilizare:

Matematicicalculnumeric; Dezvoltareaalgoritmilor; Modelare,simulareitestareaprototipurilor; Analizaivizualizareadatelor; Graficainginereascidintiineleaplicate; Dezvoltareadeaplicaii,inclusivGUI(GraphicalUserInterface).

MATLAB=sistem interactiv care are ca element de baz tabloul, matricea, ceea ce permite rezolvarea problemelor de calcul numeric, n special cele care necesit prelucrarea de vectori saumatrici; Numele MATLAB provine de la Matrix laboratory. Firma productoare este The MathWorks, Inc.,SUA; MATLABulaevoluat:

n mediul universitar, unde este pachetul standard pentru cursurile introductive i avansatedematematic,inginerieitiine; n mediul economic, unde este utilizat pentru cercetarea de nalt randament, dezvoltareiproducie.

MATLABul permite dezvoltarea unei familii de aplicaii sub forma toolboxurilor. Aceste toolboxuri permit nvarea i aplicarea tehnologiilor specializate din diverse domenii. Sunt disponibiletoolboxuripentrudiversedomenii.

Limbajeavansatedeprogramare MATLAB

SistemulMATLABconstncincipriprincipale:

LimbajulMATLAB MediuldelucruMATLAB HandleGraphics BibliotecadefunciimatematicealeMATLABului InterfaadeaplicaiiprogramaMATLABului(API)

LimbajulMATLAB:Reprezintunlimbajdenivelnaltdetipmatrice/tabloucuinstruciunidecontrol al salturilor, funcii, structuri de date, intrri/ieiri i cu proprieti de programare orientat pe obiecte 1 .Facilitiledeprogramaresuntorganizatepe6directoare:
ops

Operatorsandspecialcharacters(Operatoriicaractere speciale) Programminglanguageconstructs(Construcialimbajuluide programare) Characterstrings(iruridecaractere) Fileinput/output(Fiieruldeintrare/ieire) Timeanddates(Oridate) Datatypesandstructures(Tipuridedateistructuri)

Lang Strfun Iofun Timefun Datatypes

Mediul de lucru MATLAB: Reprezint un set de faciliti care permit manevrarea variabilelor n spaiul de lucru, importul i exportul de date, dezvoltarea, manipularea, editarea i depanarea fiierelorMATLAB(.m)iaaplicaiilorMATLAB.Acestefacilitisuntorganizatendirectorul:
general

Generalpurposecommands(Comenzideuzgeneral)

Programareaorientatpeobiectesteunuldinceimaiimportanipaifcuinevoluialimbajelordeprogramarespreo maiputernicabstractizarenimplementareaprogramelor.Eaaaprutdinnecesitateaexprimriiproblemeintrunmod mai natural fiinei umane. Astfel, unitile care alctuiesc un program se apropie mai mult de modul nostru de a gndi dectmoduldelucrualcalculatorului.
1

Limbajeavansatedeprogramare MATLAB

Handle Graphics: Reprezint sistemul grafic al MATLABului. Cuprinde comenzi de nalt nivel pentru vizualizarea datelor bi i tridimensional, procesarea imaginilor, animaie, prezentri de grafice. Permite de asemenea utilizarea unor comenzi pentru crearea unor interfee grafice GUI. Funciile graficesuntorganizaten5directoare:
Graph2d Graph3d Specgraph Graphics Uitools

Twodimensionalgraphs(Graficebidimensionale) Threedimensionalgraphs(Graficetridimensionale) Specializedgraphs(Graficedespecialitate) HandleGraphics(Manipulareagraficelor) Graphicaluserinterfacetools(Instrumentedeinterfa graficpentruutilizator)

Biblioteca de funcii matematice a MATLABului: Reprezint o colecie complex de algoritmi de calcul pornind de la funcii elementare (sinus, cosinus etc.) pn la funcii sofisticate (inversarea de matrice,valoriproprii,funciiBessel,FFTetc.).Funciilematematicesuntorganizaten8directoare:
elmat

Elementarymatricesandmatrixmanipulation(Matrice elementareimanipularealor) Elementarymathfunctions(Funciimatematice elementare) Specializedmathfunctions(Funciimatematice specializate) Matrixfunctions numericallinearalgebra(Funciide matricealgebrliniarnumeric) DataanalysisandFouriertransforms(Analizadatelori transformriFourier) Interpolationandpolynomials(Interpolaresipolinoame) Functionfunctionsand ODEsolvers(Funciile defunciii derezolvareaecuaiilordiferenialeordinare) Sparsematrices(Matricerare)

Elfun

Specfun

Matfun

Datafun Polyfun Funfun Sparfun

Interfaa de aplicaii program a MATLABului (API) este o bibliotec care permite scrierea de programe n C sau Fortran care interacioneaz cu MATLABul. Include faciliti pentru apelarea rutinelor din MATLAB, apelarea MATLABului ca main de calcul, scriereai citirea fiierelor de tip .MAT.

Limbajeavansatedeprogramare MATLAB

PachetulSIMULINK

SIMULINK este un pachet software ataat MATLABuluii reprezint un sistem interactiv pentrusimulareadinamiciisistemelor.Esteconceputsubformauneiinterfeegraficecare permite crearea unui model prin trasarea schemei bloc a sistemului i apoi simularea dinamiciisistemului; SIMULINKpoatelucracusistemeliniare,neliniare,continue,discrete,multivariabileetc.; SIMULINK beneficiaz de aanumitele Blockseturi care sunt de fapt biblioteci suplimentare care conin aplicaii specializate din domenii cum ar fi: comunicaii, procesareasemnaleloretc.; Realtime Workshop este un program foarte important care permite generarea unui cod C pentru schemele bloc create n SIMULINKi prin urmare permite rularea de aplicaii n timprealdeomarediversitate.

ToolboxurileMATLAB

Toolboxurile reprezint o familie de aplicaii care permit nvarea i aplicarea tehnologiilor specializate din diverse domenii. Aceste toolboxuri sunt colecii de funcii MATLAB (functions) (Mfiles) care extind mediul MATLAB pentru rezolvarea unor clase particularedeprobleme.

Ctevadincelemaiutilizateaplicaiisuntprezentatenfiguraurmtoare.

Limbajeavansatedeprogramare MATLAB

Limbajeavansatedeprogramare MATLAB

FUNDAMENTELEPROGRAMRIINMATLAB
1. Expresiifundamentale MATLABullucreazcuexpresiimatematicecaicelelaltelimbajedeprogramare,darspredeosebire demajoritateaacestorlimbaje,acesteexpresiiimpliclucrulcumatricilascarlarg. Expresiilesuntalctuitecuajutorulurmtoarelortipuri: Variabile Numere Operatori Funcii Variabile MATLABul nu necesit declararea dimensiunii variabilelor, deoarece la ntlnirea unui nou nume de variabil genereaz automat variabila respectiv i aloc spaiul necesar de memorie. Numele unei variabile este o liter, urmat de un numr orict de mare de litere, cifre sau simboluri.Dinacestnumrorictdemaresuntopriteprimele31decaractere. MATLABulestecasesensitivefacedistincientreliterelemiciicelemari. Exemplu:
a = 30

creeaz o matrice 1x1 cu numele a i stocheaz valoarea acesteia, 30, ntro singur locaie corespunztoaresinguruluielementalmatricei. Numere MATLABul utilizeaz notaia zecimal, cu punct zecimal opional i cu semn + sau . Se utilizeaz i notaia tiinific cu litera e pentru a specifica o putere a lui 10. Reprezentarea numerelorimaginareesterealizatculiteraisaujcasufix. Exemple:
3 9.6397238 1i -99 1.60210e-20 -3.14159j 0.0001 6.02252e23 3e5i

Toate numerele sunt stocate intern utiliznd formatul long specificat de standardul IEEE (Organizaia internaional Institute of Electrical and Electronics Engineers) n virgul mobil (preciziede16zecimalesemnificativendomeniul10308la10+308).

Limbajeavansatedeprogramare MATLAB

Operatori Expresiileutilizeazoperatoriaritmeticiuzuali:
+ * / \ ^ '

Adunare Scdere Multiplicare mprireladreapta mprirelastnga Ridicarealaoputere Transpusacomplexconjugat

( ) Operatoruldespecificareaordiniideevaluare

Funcii MATLABul furnizeaz un mare numr de funcii matematice elementare standard (abs, sqrt, exp, sin ). Exist i funcii matematice avansate (funcii Bessel, gama etc.), multe dintre acestea acceptndargumentecomplexe. Pentruvizualizareafunciilorelementaresepoatetasta:
help elfun

Pentruavedealistafunciiloravansatesepoatetasta:
help specfun help elmat

O parte din funcii (cum ar fi sqrt, sin) sunt de tip builtin, adic sunt o parte a nucleului MATLAB,auomareeficien,dardetaliileconstructivenusuntaccesibileutilizatorului. AltefunciisuntimplementatecafiiereMATLAB(Mfiles)ipotfichiarmodificate. Ctevafunciifurnizeazvalorileunorconstanteuniversale:
pi i j eps realmin

3.141592653589793 Imaginaryunit,1 Sameasi Floatingpointrelativeprecision2.220446049250313e016 Thesmallestpositivenormalizedsingleprecisionfloatingpointnumberon yourcomputer:2^(1022),aprox.2.225073858507201e308 Thelargestsingleprecisionfloatingpointnumberrepresentableonyour computer:2^1024,aprox.1.797693134862316e+308 Infinity Notanumber

realmax Inf NaN

Limbajeavansatedeprogramare MATLAB

Numelefunciilornusuntrezervateideciesteposibilsuprascrierealor. Exemplu:
eps = 1.e-6

Funciaoriginalestereconstituitprincomanda:
clear eps

Expresii Exempledeexpresiiirezultatelecorespunztoarealeevaluriiacestorexpresii:
rho = (1+sqrt(5))/2 rho = 1.6180

a = abs(3+4i) a = 5

z = sqrt(besselk(4/3,rho-i)) z = 0.3730 + 0.3214i

nr_foarte_mare = exp(log(realmax)) nr_foarte_mare = 1.7977e+308

nr_prea_mare = pi* nr_foarte_mare nr_prea_mare = Inf

Limbajeavansatedeprogramare MATLAB

2. Helponline,formatuldatelor,opiunidesalvare Helponline PentrurulareaMATLABpeunPCtrebuiepurisimpluexecutatundubluclickcumouseulpeiconul MATLAB. Dac sistemul de operare nu este de tip Windows (este de tip UNIX) trebuie tastat matlab dupprompterulsistemuluideoperare. Limbajul MATLAB este mult mai simplu de nvat dac se renun la inspectarea arid a listelor cu variabile, funciii operatorii se utilizeaz n schimb comenzile help, helpdesk, demo,tastatedirectdelaprompterulMATLAB; Pentru aflarea tuturor informaiilor utile despre o comand sau o funcie se tasteaz help urmatdenumelecomenziisaufuncieirespective; Pachetul MATLAB dispune de asemenea de informaii complete despre utilizare sub forma uneidocumentaiitip.pdf; n cazuri particulare se poate apela la INTERNET, existnd o legtur la pagina Web a firmei productoare; Altecomenziutilepentruaflareadeinformaiisunt:helpwin,lookfor, help help. Exemplesugestivedeutilizareacomenziihelp:
help sin SIN Sine of argument in radians.

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

See also asin, sind.

Overloaded methods: codistributed/sin

Reference page in Help browser doc sin _________________________________________________________________________

help exp EXP Exponential. EXP(X) is the exponential of the elements of X, e to the X. For complex Z=X+i*Y, EXP(Z) = EXP(X)*(COS(Y)+i*SIN(Y)).

See also expm1, log, log10, expm, expint.

Limbajeavansatedeprogramare MATLAB

10

Overloaded methods: lti/exp codistributed/exp fints/exp xregcovariance/exp

Reference page in Help browser doc exp ___________________________________________________________________________

help plot PLOT Linear plot.

PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix, then the vector is plotted versus the rows or columns of the matrix, whichever line up. If X is a scalar and Y is a vector, disconnected

line objects are created and plotted as discrete points vertically at X.

PLOT(Y) plots the columns of Y versus their index. If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)). In all other uses of PLOT, the imaginary part is ignored.

Various 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 g r c m y k w

blue green red cyan magenta yellow black white

. o x + * s d v ^ < >

point circle x-mark plus star square diamond triangle (down) triangle (up) triangle (left) triangle (right)

: -. -(none)

solid dotted dashdot dashed no line

Limbajeavansatedeprogramare MATLAB

11

p h

pentagram 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.

PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined by the (X,Y,S) triples, where the X's and Y's are vectors or matrices and the S's are strings.

For example, PLOT(X,Y,'y-',X,Y,'go') plots the data twice, with a solid yellow line interpolating green circles at the data points.

The PLOT command, if no color is specified, makes automatic use of the colors specified by the axes ColorOrder property. By default, For

PLOT cycles through the colors in the ColorOrder property.

monochrome systems, PLOT cycles over the axes LineStyleOrder property.

Note that RGB colors in the ColorOrder property may differ from similarly-named colors in the (X,Y,S) triples. For example, the

second axes ColorOrder property is medium green with RGB [0 .5 0], while PLOT(X,Y,'g') plots a green line with RGB [0 1 0].

If you do not specify a marker type, PLOT uses no marker. If you do not specify a line style, PLOT uses a solid line.

PLOT(AX,...) plots into the axes with handle AX.

PLOT returns a column vector of handles to lineseries objects, one handle per plotted line.

The X,Y pairs, or X,Y,S triples, can be followed by parameter/value pairs to specify additional properties of the lines. For example, PLOT(X,Y,'LineWidth',2,'Color',[.6 0 0]) will create a plot with a dark red line width of 2 points.

Example

Limbajeavansatedeprogramare MATLAB

12

x = -pi:pi/10:pi; y = tan(sin(x)) - sin(tan(x)); plot(x,y,'--rs','LineWidth',2,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',10)

See also plottools, semilogx, semilogy, loglog, plotyy, plot3, grid, title, xlabel, ylabel, axis, axes, hold, legend, subplot, scatter.

Overloaded methods: robot/plot quaternion/plot timeseries/plot phytree/plot HeatMap/plot clustergram/plot channel.plot sfit/plot cfit/plot fints/plot idmodel/plot idfrd/plot iddata/plot idnlhw/plot idnlarx/plot cgrules/plot xregtwostage/plot xregtransient/plot xregmodel/plot xregarx/plot localmulti/plot localmod/plot localavfit/plot sweepset/plot mdevtestplan/plot cgdatasetnode/plot mpc/plot

Limbajeavansatedeprogramare MATLAB

13

rfckt.plot frd/plot dspdata.plot wdectree/plot ntree/plot dtree/plot wvtree/plot rwvtree/plot edwttree/plot Reference page in Help browser doc plot

Formatuldatelor MATLABul afieaz numerele cu 5 zecimale (setare implicit). Aceast setare se poate modifica cu ajutorulcomenziiformat:
help format FORMAT Set output format. FORMAT with no inputs sets the output format to the default appropriate for the class of the variable. For float variables, the default is FORMAT SHORT.

FORMAT does not affect how MATLAB computations are done. Computations on float variables, namely single or double, are done in appropriate floating point precision, no matter how those variables are displayed. Computations on integer variables are done natively in integer. Integer variables are always displayed to the appropriate number of digits for the class, for example, 3 digits to display the INT8 range -128:127. FORMAT SHORT and LONG do not affect the display of integer variables.

FORMAT may be used to switch between different output display formats of all float variables as follows: FORMAT SHORT FORMAT LONG Scaled fixed point format with 5 digits. Scaled fixed point format with 15 digits for double and 7 digits for single. FORMAT SHORT E FORMAT LONG E Floating point format with 5 digits. Floating point format with 15 digits for double and 7 digits for single.

Limbajeavansatedeprogramare MATLAB

14

FORMAT SHORT G

Best of fixed or floating point format with 5 digits.

FORMAT LONG G

Best of fixed or floating point format with 15 digits for double and 7 digits for single.

FORMAT SHORT ENG Engineering format that has at least 5 digits and a power that is a multiple of three FORMAT LONG ENG Engineering format that has exactly 16 significant digits and a power that is a multiple of three.

FORMAT may be used to switch between different output display formats of all numeric variables as follows: FORMAT HEX FORMAT + Hexadecimal format. The symbols +, - and blank are printed for positive, negative and zero elements. Imaginary parts are ignored. FORMAT BANK FORMAT RAT Fixed format for dollars and cents. Approximation by ratio of small integers. Numbers

with a large numerator or large denominator are replaced by *.

FORMAT may be used to affect the spacing in the display of all variables as follows: FORMAT COMPACT Suppresses extra line-feeds. FORMAT LOOSE Puts the extra line-feeds back in.

Example: format short, pi, single(pi) displays both double and single pi with 5 digits as 3.1416 while format long, pi, single(pi) displays pi as 3.141592653589793 and single(pi) as 3.1415927.

format, intmax('uint64'), realmax shows these values as 18446744073709551615 and 1.7977e+308 while format hex, intmax('uint64'), realmax shows them as ffffffffffffffff and 7fefffffffffffff respectively. The HEX display corresponds to the internal representation of the value and is not the same as the hexadecimal notation in the C programming language.

Limbajeavansatedeprogramare MATLAB

15

See also disp, display, isnumeric, isfloat, isinteger.

Overloaded methods: quantizer/format

Reference page in Help browser doc format Exemple: c=1.333456789233 c = 1.3335

format long c c = 1.33345678923300

format short e c c = 1.3335e+000

format long e c c = 1.333456789233000e+000

format c c = 1.3335

Limbajeavansatedeprogramare MATLAB

16

Opiunidesalvarealevariabilelor Pentru salvarea variabilelor curente cu care se lucreaz n MATLAB la ncheierea unei sesiuni delucrusepoateutilizacomandasave. Aceast comand va salva toate variabilele curente generate de ctre utilizator ntrun fiier numit matlab.mat . Dac se dorete se poate da un nume fiierului de date n care se salveazvariabilele. Exemplu:
save date c determ A

realizeazsalvareadatelorc,determiAntrunfiierdate.mat Pentrurestituireavariabilelorntrosesiunedelucruulterioarsefolosetecomandaload. Exemplu:


load date

Dacsedoreteaflareavariabilelorcurentesepotutilizacomenzilewho,whos:
who Your variables are:

determ

whos Name Size Bytes Class

A c determ

2x2 1x1 1x1

32 8 8

double array double array double array

Grand total is 6 elements using 48 bytes

Pentrutergerea tuturor variabilelor curente din memoria de lucru se poate utiliza comanda clear.