Sunteți pe pagina 1din 16

Informaticaaplicatninginerie 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 rezolvareaproblemelordecalculnumeric,nspecialcelecarenecesitprelucrareadevectori saumatrici; NumeleMATLABprovinedelaMatrixlaboratory.FirmaproductoareesteTheMathWorks, Inc.,SUA; MATLABulaevoluat: n mediul universitar unde este pachetul standard pentru cursurile introductive i avansatedematematic,inginerieitiine; n industrie, unde este utilizat pentru cercetarea de nalt randament, dezvoltare i producie.

MATLABul permite dezvoltarea unei familii de aplicaii sub forma toolboxurilor. Aceste toolboxuri permit nvarea i aplicarea tehnologiilor specializate din diverse domenii. Sunt disponibiletoolboxuripentrudomeniicumarfi:procesareanumericasemnalelor,sisteme de conducere automat, reele neurale, logic fuzzy, wavelet, simulare (SIMULINK), identificareetc.

Informaticaaplicatninginerie 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(Operatorii caracterespeciale) Programminglanguageconstructs(Construcia limbajuluideprogramare) Characterstrings(iruridecaractere) Fileinput/output(Fiieruldeintrare/ieire) Timeanddates(Or idate) 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)

Programareaorientatobiectesteunuldinceimaiimportanipaifcuinevoluialimbajelordeprogramarespreo maiputernicabstractizarenimplementareaprogramelor.Eaaaprutdinnecesitateaexprimriiproblemeintrunmod mai natural fiinei umane.Astfel unitile care alctuiesc un program se apropie mai mult de modul nostru de agndi dectmoduldelucrualcalculatorului.
1

Informaticaaplicatninginerie MATLAB

HandleGraphics:ReprezintsistemulgraficalMATLABului.Cuprindecomenzidenaltnivelpentru 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(Instrumentede interfagraficpentruutilizator)

Biblioteca de funcii matematice a MATLABului: Reprezint o colecie complex de algoritmi de calculporninddelafunciielementare(sinus,cosinusetc.)pnlafunciisofisticate(inversareade matrice,valoriproprii,funciiBessel,FFTetc.).Funciilematematicesuntorganizaten8directoare:
elmat Elfun Specfun Matfun

Elementarymatricesandmatrixmanipulation(Matrice elementareimanipularealor) Elementarymathfunctions(Funciimatematiceelementare) Specializedmathfunctions(Funciimatematicespecializate) Matrixfunctions numericallinearalgebra(Funciide matricealgebrliniarnumeric) DataanalysisandFouriertransforms(Analizadatelori transformriFourier) Interpolationandpolynomials(Interpolaresipolinoame) FunctionfunctionsandODEsolvers(Funciile defunciiide rezolvareaecuaiilordiferenialeordinare) Sparsematrices(Matricerare)

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 rutinelordinMATLAB,apelareaMATLABuluicamaindecalcul,scriereaicitireafiierelordetip .MAT.

Informaticaaplicatninginerie MATLAB

PachetulSIMULINK SIMULINK este un pachet software ataat MATLABului i reprezint un sistem interactiv pentru simularea dinamicii sistemelor. Este conceput sub forma unei interfee grafice care 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, procesarea semnalelor etc.; RealtimeWorkshop este un program foarte important care permite generarea unui cod C pentruschemelebloccreatenSIMULINKiprinurmarepermiterulareadeaplicaiintimp realdeomarediversitate. ToolboxurileMATLAB Toolboxurilereprezintofamiliedeaplicaiicarepermitnvareaiaplicareatehnologiilor specializate din diverse domenii. Aceste toolboxuri sunt colecii de funcii MATLAB (functions)(Mfiles)careextindmediulMATLABpentrurezolvareaunorclaseparticularede probleme. Ctevadincelemaiutilizateaplicaiisuntprezentatenfiguraurmtoare.

Informaticaaplicatninginerie MATLAB

Informaticaaplicatninginerie 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).

Informaticaaplicatninginerie 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

Opartedinfuncii(cumarfi sqrt,sin) suntdetip builtin,adicsuntoparteanucleului MATLAB,auomareeficien,dardetaliileconstructivenusuntaccesibileutilizatorului. AltefunciisuntimplementatecafiiereMATLAB(Mfiles)ipotfichiarmodificate. Ctevafunciifurnizeazvalorileunorconstanteuniversale:


pi i j eps realmin

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

realmax Inf NaN

Informaticaaplicatninginerie 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

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

toobig = pi*huge toobig = Inf

2. Helponline,formatuldatelor,opiunidesalvare Helponline PentrurulareaMATLABpeunPCtrebuiepurisimpluexecutatundubluclickcumouseulpeiconul MATLAB.DacsistemuldeoperarenuestedetipWindows(estedetipUNIX)trebuietastat matlab dupprompterulsistemuluideoperare.

Informaticaaplicatninginerie MATLAB

Limbajul MATLAB este mult mai simplu de nvat dac se renun la inspectarea arid a listelorcuvariabile,funciiioperatoriiseutilizeaznschimbcomenzile 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; ncazuriparticularesepoateapelalaINTERNET,existndolegturlapaginaWebafirmei 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.

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

Reference page in Help browser

Informaticaaplicatninginerie MATLAB

10

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 ^ < > p h

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

: -. -(none)

solid dotted dashdot dashed no line

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.

Informaticaaplicatninginerie MATLAB

11

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 x = -pi:pi/10:pi; y = tan(sin(x)) - sin(tan(x)); plot(x,y,'--rs','LineWidth',2,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',10)

Informaticaaplicatninginerie MATLAB

12

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 rfckt.plot frd/plot dspdata.plot wdectree/plot ntree/plot dtree/plot wvtree/plot

Informaticaaplicatninginerie MATLAB

13

rwvtree/plot edwttree/plot Reference page in Help browser doc plot

Formatuldatelor MATLABul afieaz numerele cu 5 zecimale (setareimplicit). 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. 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

Informaticaaplicatninginerie MATLAB

14

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.

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

Overloaded methods: quantizer/format

Reference page in Help browser

Informaticaaplicatninginerie MATLAB

15

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

Opiunidesalvarealevariabilelor PentrusalvareavariabilelorcurentecucareselucreaznMATLABlancheiereauneisesiuni delucrusepoateutilizacomandasave. Aceastcomandvasalvatoatevariabilelecurentegeneratedectreutilizatorntrunfiier 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

Informaticaaplicatninginerie MATLAB

16

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

Pentrutergereatuturorvariabilelorcurentedinmemoriadelucrusepoateutilizacomanda clear.

S-ar putea să vă placă și