Sie sind auf Seite 1von 21
Contents: ‘What Is Matlab? Stating Mati Basic Data Entry and Manipulation Explicit Data Enty ‘Soppressing Output ‘Case Sensitivity Some Very, Very, Basic Matlab aes ‘For people who have never used Listing Declared Variables Clearing Variables Complex Numbers ‘Accessing Individual Elements Using Subscripts 8 Using The Colon Operator 9 ‘Constructing Matrices Using Buil-In Matlab Functions uw Basic Operators : 2 “Applying Operators To Elements B Matlab Functions : 4 Useful Constants : Eo cece) Groups Of Matlab Functions: 16 Details of Selected Groups: 20 Elementary Mathematical Functions: 20 [Elementary Matrices and Matrix Manipulation Functions: 2 ‘Matrix Functions For Numesical Linear Algebra: ......... 24 Basic Graphics - see 26 ‘Creating A Basic Plot 6 Creating Subpots 32 ‘Working With Complex Data... 34 Axes Commands 36 Mesh and Surface Plots 38 Getting Help roo wee Scott D, Snyder “The Help Command 43 Department of Mechanical Engineering Documeatation : 5 8 ‘What Is Matlab? Matlab sa software package designed specifically for technical computing. The name “Matlab” stands for Mosrix Laboratory, a8 it was originally writen to provide easy access 10 state-of the-art sofware for matrix manipulation and ‘Computation developed in the Linpack and Eispack project. ‘Matlab is now one ofthe most widely used computational software packages in ‘engineering, a standard tol for instruction, research and development ina wide range of disciplines and areas. Matlab enables users to undertake computation, viswalisation and programming operations in a single environment. Typical pplication areas for Matlab include: Data analysis and visualisation. Engineering simulation snd modeling Mathematical problem solving Algorithm development Complete application development, including graphics ‘The complete Matab package can be divided into five components: ‘The Matlab language, which is a high-level language based around matrix ‘manipulation, containing contol flow statements, functions, daa structures, ‘npaoutput and object-oriented programming featres. ‘The Matlab working environment, which contains ase of tools and facilities Which are useful when either programming or using Matlab, Handle graphics, which isthe Matlab sophie systems, inluding commands for 2-D and 3D ploting, image processing, animation and presentation graphics. ‘The Matlab mathematical function Ubrary, which is an extensive range of| algorithms fo solving both simple and complicated mathematical fonctions. ‘The Matlab Application Program Interface (APD, which allows you to write (Cand Fortran programs that interact with Mab In addition the above components, Matlab ha a nomber of aplication-specifc sdd-ons called Toolbores. These enable specialised work in a range of areas, such as contol system design and analysis signal processing and opsimisaion. Starting Matlab This handout is intended to provide a very basi introduction to data entry and ‘manipulation in Matlab, presented to help anew usr of Matlab get started ‘To run Matlib on & PC, double click onthe Matlab icon, Ta run Matlab on a UNIX system, type Matlab atthe operating system prompt. To quit Matlab at any time, enter “uit” tthe Matlab proms. Basie Skills in Data Entry and Manipulation Using Matlab the package is expected tobe in max format (inthe general sense, including Sealare and vectors). There area number af way input a set of matrix data into ‘Matlab, including + Entering listo data either onthe command line or via an Mile roti. 2 Generating special” matrices using either Matab's built-in functions or user developed functions + Transferring data from other software packages, such as through the clipboard of via DDE. + Loading data from external fies. [Explicit Data Entry “There are afew basic conventions which must be followed o enter data in Matlab, citheron the command line or in an Mcfile: + Row elements must be separated with either a comms ora blak; {Columns must be separated with itera semicolon ota carriage retum. 2 Dataisto be entered from the top left element tothe botom right element, ‘mowing across the fist row, then the second row, etc. The entire dataset js tobe enclosed with square brackets, So, for example, typing the following onthe Matlab command line: ae 23 41 ies the ouput: eae > 4 ‘We have now entered a (2x 2) matrix, which Matlab “knows as A. “There are other ways in which we could bave entered this matix, including: aAea2 34 Basic Skills in Data Entry and Manipulation Using Mati Basic Data Entry and Manipulation or Matlab is fundamentally a matrix manipulation package. As such, data input to a tis also possible to construct large matrices from smaller ones. The mast basic ‘cae for this is where a number of scalars ave first defined and then wsed (0 ‘oustuct the matrix. For example, the mak A above could be constructed using ‘he commands ba? eo act RE labret Using the above procedure, Matlab will now know of five variables: aed, and A ‘Suppressing Output Ifyou eater any ofthe above commands nto Matlab, you will noice the results {immediately displayed to soteen. This can lead toa significant reduction in the Speed with which Matlab peforms a given set of tasks. This s especially tue Shen there ar large matries involved in a calculation. To suppres the sereen Sutput after a execution ofa given Matlab command, the instruction should be terminated with a semicolon, So, for example, ifthe matrix A is entered as ae 023 4: ‘no sereen output will result. Ifyou now type ‘on the command line, you wil get the result 1 2 nis good practice to display to sereen only those reslts which are required. Basic Skills in Data Entry and Manipulation Using Matlab Case Sensitivity [Matla is case sensitive, Therefore, after having entered the matix A above ‘Matlab will recognise "A", but nt “a. So, for example, entering "A" on the command line wil display the matrix: 24 hile entering “a” will give an error message: 297 Undefined function or variable ‘a! Angular Data [i should be noted that Matlab expect to receive, and returns, all data relating to angles in radians, and not degrees. Naming Variables ‘Matlab does not require any type declarations or array sizes when assigning a Variable name to apiece of data. Whenever Matlab encounters a new variable ‘name, it simply creates the variable and asigns an amount of storage appropiate ore curent size. Ifan existing variable is modified in sie, then Matlab will modi the storage requirement. ‘One important point to note concemns naming conventions. Matlab places very few retictions upon the naming of variables: basically, a variable consists of leet, followed by additional leer, numbers, andor undescoces up to a total of SI characters. AS a result, itis possible to assign a variable name which isthe Same as 2 Matlab function or a pre-defined Matlab variable. In the case of a “Matlab funtion, this will essentially blind Matlab is existence and so make it impossible to call. A very common example ofthis “problem in Mechatronics ‘oocurs with te function damp, rich suse to caleulat the damping ofa given system model, Unfortunately, students like to use damyp asa variable name for damping in developing a system model, which has the effect of removing the «damp function from posible se, A more acceptable variable name for damping ratio is zeta, the Grek character commonly used to represent it in equations. ‘A.common example of oversritng pre-defined Matlab variables occurs with the ‘variables f and - In Matlab, the variables / and are used to construct complex ‘numbers (discussed shorty). However, they are also commonly selected as Basic Skills in Data Entry and Manipulation Using Matlab variables in looping expressions. Psthaps beter variables to use for looping ‘expressions are i and (oc variable. The simplest way to recover the original Matlab coaten ist “lea the new declaration. For example, if damp is accidentally used as avaiable, then Seen eeraney ace pe mermnenseye te|| ‘yg following on command te | ‘ill delete the curent data and restore the orginal conten Listing Declared Variables ‘Once several variables have been defined in Matlab, it is easy to loose track of What you have actually done. The Matlab command who will list all of the ~ Variables which ate currently defined. AV this pont, entering who will yield Your variables are: a ‘A longer form ofthe command is who, which wil also display the size and type of contents. Entering whos here will produce the following output Mame size Bytes class a 22 32 double array Clearing Variables The Matlab command clearis used to remove variables from memory. Entering {he command: clear & will remove the variable A. Entering the command Basie Sills in Data Entry and Manipulation Using Matlab will ernove all variables, ‘Complex Numbers “Matis can work with both rea and complex data. To enter a complex variable, tse either rj to define the complex portion. For example, the variable a=1+2) fan be entered in Matlab as either: anne ag ‘Accessing Individual Elements Using Subscripts Individual elements in a matrix can be targeted for a given operation using subscips. For example, fit is desired to construct a (1x 1) matrix B (a scala) ‘whose Value is equal tothe element inthe second ro and first eoluma inthe matrix A above, then the following could be entered on the command line Braga “Matlab will return the following 3 Subscripts are always given inthe order (Yow, column). Counting of rows and columns begins at "I", not “0” [Note that te entire matrix A could have been entered onan element-by-element Dasis using subscripts: Aga) 22 Rit) #2 Razin) 23 nizi2) 24 “The Colon Operator “The colon operator, sis used in a number of paces in Matlab, Basically, ican ‘be viewed as meaning “from and to”, For example, the expression "1:8" in 8 ‘Basic Skills in Data Entry and Manipulation Using Matlab Matlab basically means “fom | to 8". Entering this onthe command line: ae produces the result 20203 6 8 6 7 8 [Note here for fue reference that if no variables assigned for the ouput, Matlab automatically assign the result to the variable ans. “The sequence above increments by a value of 1 between outputs. This default condition ean be altered by adding an explicit increment. For example, suppose (we wan to construct a row vector B which has values ranging from Oto 1.0in Increments of 0.2. The Matab syntax for constructing a set of sequential data ver a given range and with a given increments: “stat: nerement: finish”, oF perhaps more intuitively: “fom” + "in increments of": “to”. So, entering the following onthe commandline: 8 = {0:0.2:2) will yield the results © 0.2000 9.4000 0.6000 0.8000 3.0000 [Note thatthe command above is enclosed in square brackets. Tis is not strictly required forthe vector operation. However, itis good practice to do tis ast ‘eauited forthe more general case of constucting matrices with multiple rows For example, the Matlab command b= (os0.24; 1:.2:21 vill yield the result © 0.2000 9.4000 9.6000 9.8000 1.0000 1.0000 112008 3149006000 8000 2.0000 [Note here thatthe semicolon operator hasbeen used to indicate the stat of anew Basic Skills in Data Entry and Manipulation Using Matlab ‘We wil find later in this book that using the colon operator inthe way described above i very useful for constructing vectors whose elements are pints in time, tw be fed as input to some for of simulation routine. In ation tots use in constructing new matrices, the colon operator can also be used to count out elements in existing matrices. For example, having entered the matrix A earlier in the section, typing the command aaa) will yield the ourpr: Ba “The Matlab input “A(1,1:2)" could be read as “the elements in matrix A in the first row and in columns from 1102". Asthissthe entire ange of columns the ‘matrix, the command could have been abbreviated age) A further extension which can be useful when working with large matices isto ad the word “end”. For example, the command above could have been entered ACL, Arena) Note finally hat the colon operator can be used multiple times in a given expression. For example, the command Aue ‘ill display the elements inal rows and all columns: 3 Constructing Matrices Using Bull-In Matlab Functions Matlab has a purber of bulla functions fo quickly constructing commonly used ‘matrices. Thyee ofthe most common are the idemity mati, mattix witha elements equal to 0.0, and a matrix with al elements equal 01.0. ‘Basic Skils in Date Entry and Manipulation Using Matlab ‘The Matab command for constructing the identity marx is ee. For example to cconstroct a (3 x 3) matrix A which isan identity matrix, the following ean be ‘entered on the command line eo) which yields the outpat: tee 0a 2 1 0 o 8 3 ‘The command eye i somewhat more general that is suggested above, in hat ican construct a mauix of any dimension with 1s on the main diagonal and O's elsewhere, For example, the command: A= eye(2,3) yields a matix A with 2 rows and 3 columns, the values of which are 1 for ‘elements onthe main diagonal (the (1.1) and (22 element), and O forall ober ‘The Matlab commands for constructing matrices with all 0 ofall Us are zeros and ones, respectively. For example, the command: A= ter08(2,3) will produce a matrix A with 2 rows and 3 columns of zeroes: ° ‘The command: A = onae(3,2) will produce a matrix A with 3 rows and 2 columns of ones: Basie Skill in Data Entry and Manipulation Using Matlab ‘Basie Skills in Data Entry and Manipulation Using Matlab apa ‘Example: “Two other commands which are inthe sme vein as those discussed above are Evaluate C=(A + B), where: ‘and and randn. ‘The commands canbe vse to construct maries with random, : 4 is 4 Clements: ond fr elements wich ae uniformly distributed berween Oand 1.0, eels “ind randa for elements which are normally distibated with a mean of O and a bs 4 (7 sl watiance of 10. A base command Using these functions would look something ike “The Matlab script for doing this isa fellows A = zanai2,3) arn23 4 hich woul yield a matix A with 2 ows and 3 columns, teenies of which BFS 67 a ‘night ook ike: Ae wich produces the result a.za11 9.4860 0.7622 ce | Gots fasts 6.4505 fo It shouldbe note that the random number generation functions of Matlab are fa oR trove gear than what is ndiaed ere. A more complete acoso wil be Cndern atria tis bok Basie Operators Applying Operators To Elements “Matlab evaluates expressions using a numberof standard arithmetic operators and precedence rules. The operators include the following “The operaiors for multiplication, division and powers given above are forthe standard matrix operation. However, itis possible to apply them onan elements by element basis by preceding the operator witha period. So for example. if We + séditon Subaction center the maties A and Bs a F ; Avision (als, \for eft division) arinaze : * power Be 15 6:7 81; + Complex conjugate transpose | (©) spzzfication of evaluation oer then muliplying A and B yields theresa: i ea while multiplying the corresponding elements in A and B yields the esut ‘Basie Skillen Data Entry and Manipulation Using Matlab a} ‘Matlab Functions Matis basa numberof functions available. Some ofthese, such asthe sn, ex, and imag, are built into the Matlab program itself Others, such as sinh, are simply Matlab script (Mefiles, discussed shorty) provided 0 the user. Panctions in Matlab are divided, both notionlly and inthe directory suture, into groups. The most basic mathematical functions are the “elementary ‘pathematical functions” group. These include functions sul a8 sn, cos, xp, ahd fmag. A complete ist ofthe elementary mathematical functions group is given at the end ofthis chapter. To see tis lis in Matlab, enter the following on the ‘commandline help elfun All of the Mf for the funetons in this group are located in the “elfun” directory (in Matlab 5x for Windows, this directory is located at ‘\WMatlabtoolbox\mallabielfun). To obtain help fr any individual function, help zexon the commandline, where xe the function of interest. For example, to obtain help on how to use the sin funetion, enter the following help sin This wil yield the following response: 'SIN(X) Ie the sine of the elenents of x. kis worth noting again that Matlab expects to reoeive, as well as retums, all information on angles in radians. “The syntax for use of Mata functions the same as that forthe use of operators described carler. If, for example, we have previously defined whe mate A, the contents of which are displayed by entering A onthe command line ‘which display ‘Basic Skills in Data Entry and Manipulation Using Matlab then the sine ofeach clement in A can be calculated and stored in the matrix sin_A by entering the following sina = eintay ‘This yields the result 0.8418 0.9093 ole -017568 ‘The groups of Matlab functions included in the base software, without any toolbox adltions are listed later in this document. Ta lis the set of comands sociated with any ofthis, enter help x2 onthe Matlab command line, where x {is the function group of interest. Useful Constants Matlab has several atonal functions which provide the values of useful constants. This include the following Constant | Value Pi 3.14159068, q Imaginary number (square root of 1) i ‘imaginary number (square root of) ops Aoatng point relative precision reaimin | smallest ating pont number realmax | largest Moating point number ink infinity na nota-number 15 Basie Skills in Data Entry and Manipulation Using Matlab Example 1 Enter the following matrix into Matlab faa 4 2 m7 9 14 ley a1 0 ext Answer: (On the command line enter the following: ext = (23.6 6 12) 27.7 913.4) 20265 2.2 01 ‘Without a semicolon atthe end ofthe enzy the result wil echo tothe seren: on = 23.4000 4.0000 22.0000 2717000 30000 33,1000 220000 + 3.000 22000, 3 Groups Of Matlab Funetions: Functions in Matab are grouped into a number of areas, a sted below. To view the specific functions contained within a group type “help group name” onthe ‘command line. Functions inthe Elementary Mathematical Factions, Elementary ‘Matrices and Mars Manipulation Functions, and Eiementary Matrices and Marx ‘Manipatotion groups age listed athe nd ofthis handout “The groups areas follows: Group | Description Categories ‘stfon | Daa analysis nd Fourier ‘Basi operations, inte transforms Giterenes, conto, Sitering nd convolution, Fourie ansforns, sound and di, Basic Skills in Data Entry and Manipulation Using Mata atte ‘ata iypes and suctres. ‘Dats ype, cell aay fonctions, ‘mol mensional aay ‘tions, scare ances bjt fened programming functions, ovesaadibie peor ae Dynami dat exchange DDE client foetons. Examples and demonstrations. ais ‘fon emery math functions ‘Complex, exponen rounding and remainder ignometic ‘lemenary matioes and marx ‘manipulation. ‘Connection of elementary and speinland mates. base ay Information, mex manipulation. Function fenctions and ODE. (Optimiston and woot Finding ‘numencalimtegraton, function ilies, ODE salves. cen ‘Gavel purpose commands “Gener information, maging the seach spue, pt, ‘commands. aad “Two dimensional graphs. lenny wy graphs axe con graph annoason, pining ‘eaphad “Thee dimensional graphs "Elementary -D sap, oom, Tightng and ipo cont ‘raph annotation, pong apis Handle Graphics, ‘Figure window creation and ‘onto axis creation ah ‘conta, Handle Graphics objects hardopy ad printing, ofan Fie apap File ope, clove, ed, write, arin. por, export Programming lnguage comics. ‘Cont flow, evaluation ana texcetion, snp, unetions, nd variables, aigunent, handling. message display, input sie Skills in Data Entry and Manipulation Using Matlab maton ‘Matrix functions - merc inear algebra, ‘Maan analysis equations elgnvales and Singular values, atx ops (Operators ae special charset ‘Ants operons relational opertrs, logical operas, spoil characters, wise penton, st operators poiyfen Interpolation and polyomiat finns ‘Daz inerpoain, spine {nterpoatio, geome nafs, polynomials. srt uncon fr sparse matrices. Elementary spate mies, fll te spare conversion, working ‘ith sparse mates, eoening gorithms, linet algebra, tine ‘cation erative methods). ‘operations on graphs (ree) and ‘scllaneousfnctions, spectan ‘Specialized math fonctions. Specialized math fontons, ‘umber theoretic Fnetions. coordinate nafs specs Specialized pr, ‘Specialized 2D graphs, contour snd 2-12 D graphs, specialized 5. grophs, images display and Fe 10, moves and animation, lor elated fonctions, slid modeling (Character rng fonctions. Genera, sng tests, sing operators, suing to number Time and dates. ‘Care date and tie, base fetions, done fonetcay, deing, fneions ‘tole ‘Graphical wser interac oa ‘GUI functions, GUI design tool, dialog boxes, mend ies, eotbar burn group ilies user defined Ages opery ie, ‘Basic Skils in Data Entry and Manipulation Using Matlab Details of Selected Groups: Elementary Mathematical Fonctions: Name Function Trigonometric Functions sin Sine sinh Hyperbolic sine. asin Inverse sine ‘sinh Inverse hypesboli sine cos Cosine cosh Hyperbolic eosin, cos Inverse cosine. acosh averse hyperbolic cosine. tan Tangent tanh Hyperbolic tangent, aan Inverse tangent aan? Four quadrant inverse tangent. tanh Inverse hyperbolic tangent sec Sean. sech Hyperbolic secant. icc avert secant. ascch Inverse hyperbolic secant cx Cosecan exch Hyperbolic cosecan. cso Inverse cosecant, acsch Inverse hyperbolic cosecant. cot Cotangent. coth _Hypeybolic cotangent. scot Inverse cotangent, acoth Inverse hyperbolic cotangent. Exponentat Functions ew oe, Jogt0 ker. pow sac Exponential. [ator logarithm, Common (base 10) toga, Base 2 logarithm and dissect floating point umber. ‘Base 2 power and seae floating point number. Square root. Basie Skills in Data Entry and Manipulation Using Matlab nextpow? Next higher power of2. ic Skills in Data Entry and Manipulation Using Matlab Blementary Matrices and Matrix Manipulation Functions: Complex Number Functions abs Absolute value Name Function angle Phase angle. Elementary Matrices 09) Complex conjugate. zeros Zeros amy. imag Complex imaginary part cones (Ones ara, real Complex real par. eye Ideatity matrix unirap— Unvirap phase angle repmat Replicate and tile aray jateal Troe for eal aay. ad Uniformly distributed random numbers. cplepair Sort numbers into complex conjugate prs. anda Normally distributed random numbers. Tinspace _Linealy spaced vecter. Rounding and Remainder Functions logspace Logarthmically spaced vector. fx Round towards 210. rmeshgrid X and Y arays for 3-D plo. floor Round towards minus infinity Regula spaced vector and index into matrix. ceil Round toward pus infinity. round Round towards nearest integer. Basic Array Information mod Modulus (signed remainder after division). size Size of max. rem Remainder ater division. length Length of vector. sig Signum, dims Number of dimensions. isp Display matrix or tex. isempty Tre for empty matrix isequal True if rays are identical isnumerie Tre for numeric arays. ielogical True for logical aay. logical Convert numeric values to logical. ‘Matrix Manipulation reshape Change size, diag Diagonal matrices and diagonals of matrix. tail Extroct lower triangular par. 0 Exroct upper triangular part iplt ‘Flip mateix in Jfuright direction, flipad Flip matrix in upidown diection flipdim Flip matrix along specified dimension. roi90 Rotate matrix 90 deprecs. Regula spaced vector and index into mates Find Find indices of nonzero elements end Last index. 0 subaind Linear index feom multiple subscripts. a Basie Skis in Dota Entry and Manipulation Using Matlab ind2sub Multiple subscripts from linear index. Special Variables and Constants as Most rceat answer ens Floating point relative acuracy realmax Largest positive floating pont number. realmin Smallest postive losting point number. Pi 5.1415926535897, hi Imaginary unit int Infinity. Nan [Nota-Number. fsnan Troe for Not-a Number. isint True For infinite elements, isfinite True for finite elements flops Floating point operation count way ‘Suseinct answer, Specialized Matrices ‘compan Companion matrix. fallery —_Highara est matrices. hadamard Hadamard matrix, hhankel Hankel matrix bil Hilbert matrix. invhild Inverse Hilbert max magic Magic square. pascal Pascal matrix osser Classic symmetie eigenvalue test problem. tocplitz Toeplitz max. vander Vandermonde mati, wilkinson Wilkinson's eigenvalue test matrix. Basic Skills in Data Entry and Manipulation Using Matlab ‘Matrix Functions For Numerical Linear Algebra: Name Fanetion Morr analysis, ‘orm ‘Matrix of vector norm, rpormest Estimate the mateix 2-norm rank Marx rank. eet Determinant trace ‘Sum of diagonal elements. cull Niall space nh Orthoganalization ref Reduced row echelon form. subspace Angle between to subspaces Linear equation. Vand / "Linear equation solution; use "help slash inv Matix inverse cond Condition number wit respect to inversion, condest _L-norm condition number estimate, hol Cholesky factorization. choline Incomplete Cholesky factorization tw LLY factorization, Iuine Incomplete LU factorization. Orthogonal-trangular decomposition, als Non-egaive least-squares, pine Predoinverse. Iscov ‘Least squares with known covariance, Eigenvalues and singular values ie Eigenvalues and eigenvectors, sd Singular value decomposition. cis A few eigenvalues. suds ‘A fow singular values poly Characteristic polynomial polyeig Polynomial eigesvalue problem. condeig Condition number with respect to eigenvalues bess Hessenberg form, e 2 factorization for generalized eigenvalues sebur Schur decomposition Matrix functions expm Matrix exponential logm Matex logarithm, sqrt Matrix square root. 23 ‘Basic Skils in Data Entry and Manipulation Using Matlab funam [Evaluate general matrix function, Factorization wiles frdeiete Delete column from OR factorization Gansert Insert column in QR factorization {Silest Real block diagonal form to complex diagonal form, cit2nit Complex diagonal form to real block diagonal form. balance Diagonal scaling to improve eigenvalue accuracy. planerot Given’ plane rotation, % Basic Graphics (One ofthe strongest features of Matlab she extensive set of graphics functions, functions which enable the wer fo display vectors and matrices as graphs in 40 ‘and three dimensions. Once displayed, he graphs canbe further annotated and printed “This section provides some basic instruction in using the graphies functions in Matlab, le must be stated atthe onset that only 2 small faction of the Matlab ‘commands and options wil be diseussed here. More information willbe provided ina later tucoril Creating A Basic Pot “The most basic graphics command in Matlab is plot. The plot command takes a umber of forme, depending upon reuiremens. “The plot command is most easily described by demonstration. Suppose it is deste to display the sine function varying through one cycle. As wih all Matlab fanetions, plot requires data in matnx form. Therefore, the fist sep isto generate ‘matrices which contain the sine data. The following commands, entered on the “Matlab commandline, wall do ths: yesinie; “The fist line generates a vector t which contains 201 values, ranging fom Oto 2¢pi, and incrementing in steps of pi/100. The second line creates a vector 'y which contains 201 values, which corespond othe sine ofthe values int. To plot the sine of the data (y axis) versus the actual data (x axis), enter the following: ploe(esy) ‘This wil erate the following plo: 25 Basie Skills in Data Entry ond Manipulation Using Matlab ‘Suppose now we wish to plot both the cosine and sine curves ona single Higues ‘To do tis, the cosine data ean be generated using the command: 1068): To plot multiple curves on a single figure, x-y data pats ae passed to the cominand in a sequential fashion. So, entering the command plotie.x.e.¥? produces the pot ees Si ant od of —_— Note that in addition tothe two curves, the above figure now has axis labels, a tile, and legends to distinguish the curves. These were added by entering the following commands after the plot command eitze (‘Cosine and sine!) ; Legena("Cosine’, “Sine") xlabel (angie. (rad) ") Yiabel (Value)? tis possible to specity a particular color for plo, andra tine style, andor line markers. The specifies fora panicula curve are given alter the xy data pair: Plot (x9, ‘color seye_marker) whete color_syle_marker i 1-,2:,r3-character string which is delimited by single quotation marks. Common vas include + Colors: ‘e's my’ 'B' bw" and“, for eyan, magenta, yellow, 2 ‘Basic Skills in Data Entry and Manipulation Using Matlab red, green, be, which and black for dashed,“ for dotted, "for dash-det, Line soles: for sold and “none” for none Makers‘ for point,‘ for circle, ‘x for x-matk, “4 for pls,“ for star, 's' for square, “for diamond, fr triangle own, °* for tianale ‘p< for ange lef, > for triangle ight, "por pentagram, and h’ for Dexagram. So, for example, if we eplace the above plot command with ploete sa, t= teye ke #) the plot becomes: 0 vaue ‘Basie Skills in Data Entry and Manipulation Using Matlab you ae happy with the plot and you wish keep a copy for later eference, you have several options: you simply want to keep a copy on-Sreen for ater use, you can stat up nother figure window for future plots so thatthe present plot is not ‘written over. To.open anew figure window and make it current, simply enter: gure To get back tothe orginal pot on fact to make any existing figure window the curent one, enter: figure (=) were nis the number inthe Figure window tle bar you simply want to retin the carent pot and add more plot ot then you use the command: ‘Suppose, fr example, you want to place a black centrelie inthe previous figure. You could d this using the following commands: hold on Tine = (0 2*pi) Line-y = [0 0) plot (line x,14 yey ‘The results as follows: Basie Skil in Data 30 Value and Manipulation Using Matiab ‘When you are finished, enter: hold off To clear (ease) the figure at anytime enter: cis ‘This command will lear the cutent figure ‘To obtain a hard copy, the figure can be printed. Mati has support functions and options fora wide range of printers enter help print to obtain a isting ‘To copy the figure to the clipboard so that it can be pasted ito other Basi de Skills in Data E Manipulation Using Matlab ocurnens, such as word processor Files or drawings, open the “ei ‘menu in the figure window, and selet the “copy figure” option. This will copy the figure asa windows metafile. When importing the Figure into nother document, it is often useful o select the “pate special” option, ‘rather than the “paste” option, and ty importing using different formats. Some are better than others, andthe best option will change depending ‘upon the characteristics ofthe plo. Creating Subplots Matlab has the capability to display multiple plots inthe same Figure ‘window andor print muliple plots on te same piece of paper. Entering the command subplot (m,n) effectively breaks the figure windows into an m x m array of smaller Figures, and selects the pth one ofthese for plotting. FFor example the sine and cosine plots shown previously could be placed on two subplots using the following commands: subplot (2.1.2), pet (ta) (Angie. (rad)") label ("Value")? ELtle('cosine Plot’) Eoxt (1.5, 5, "Note the data range from 0 to 2\pi'): Subplot (2.1/2), poe (tsy) xisbel Vangie. (xad)") Yiabel ("value")? Eiela('sine Plot) fexeiois,-5:"\isilote the data range from 0 to 2\pi)") ‘The result ofthis Fook like: Fy | | ! ‘Basic Skills in Data Entry and Manipulation Using Matlab ‘Basie Skills in Dota Entry and Manipulation Using Matlab aa snd mathematical symbols. y ‘One final point to noe: When using subplos is that Matlab will continue os petotedtacngetemot2e Souci dene ay of pti iy pe esse cfeommand, as Working With Complex Data ‘Matlab supports complex number data. However, when the arguments to a plot aze complex, the imaginary part ofthe data i ignored, unless the Aeelod ‘command is explicitly given a single complex argument. 1 For example, suppose we are intrested in ploting an exponential function ost feces with data ranging though a single eyele. If we enter the following, commands zd 3 & = 0:0..¢pisatpss asl 2 > expire): ploctes2) 1 2 8 «5 6 7 ‘ve wl be given the warning peg) Warning: Inaginacy parts of complex X and/or ¥. Srgunente ignored and only the eal part ofthe dat wil be ploted: From the commands shove, note that the title and axis labelling onmands fra given subplot should follow immediately afer the subplot ‘command is called, Inthe plots above, text has been inserted using the test command. The sya for this command is. ext (x.y; ‘string’ ) ‘where ‘strings the text tobe inserted, and (x) isthe locaton in wits from the curtent plot. Ifa three dimensional plot is being constructed, then the syntax becomes: text (ey.2,/etring’) Note that Matlab recognises a subset ofthe Tex notation, whish can be ‘sed to produce lteative fonts (uch a the italics above), Greek leters 32 se Skillen Dato Entry ipulation Using Matlab ‘This isthe same result as if we had used the command: Basie Skills n Data Entry and Manipulation Using Matlab not (2) k plot(t-reat(2)) ‘This shortcut will automatically plt real vs. imaginary data provide that If we were expliidy interested in examining the imaginary part of the zis complex, data then we could enter: plot(tdmagi2)) ‘Axes Commands : What might be of more interest, however, so plot the data on a complex Left to its own devices, Matlab will scale the plot ates to suit the data ani, real data versus imaginary data. This coUld be accomplished by inpot range. However, itis often the eae that we will want to change the scaling, orientation, or in some other way alter the appearace ofthe pet plot (real (2) ,{magiz)) The following are some useful commands fr doing this: Deane To override the default Matlab axis selection, which is based upon the data minimum and maximum, use the following command: (oonin sonax yin, max. 1) 5 ; where min, Xmas, yin, and max. are the minimam and maximum values f a} for the x and y axes, respectively. “9 ‘The command: ast axis equare ax} i makes the x and y axis the same length. The command i q axis equal 02} ‘makes te tick mark increments the same on the two axes, The command “| axis off | tums offal axis markers, and “4 axis on 1 a5 05 4 020 02 Q4 08 aa 3 tums them back on, For more information on these and other options, hep axie ———————————— ‘There are occasions where repoting the dat isnot desired. Rather, we sae npg neg pier eee a 2 ‘Basic Skis in Data Entry and Manipulation Using Matlab fon the command line, The zoom is implementing using the mouse, by tither holding down the let button and dragging the cursor over the aca Of imerest,o by simply clicking the lft button. The zoom out, click the Fight mouse bution, To turnoff the zoom feature, enter: zoom off ‘on the command line ‘Another useful feature i ase of grid marks onthe plot, which ean be included using the command: “To remove the grid masks, use the command grid off ‘Mesh and Surface Pots 36 “Matlab contains a wide assortment of commands and options for plotting Gata which ia function of two variables. These plots canbe to oF three ‘mensional, While a more detailed discussion willbe given in alter tutorial itis of us to briefly outine afew commands bere. Given dota thats funtion of two variables, = f(xy), Matlab defines ‘surface by connecting the point located above and below te xy plane ‘with straight lines, The commands mesh and surf are used to plot the points in three dimensions, while the command contour is used to plot in to dimensions “The first step in plotting data which i a fonction of two variables is to generate a pir of matrices consisting of repeat rows and columns over the ‘domain of the function, This data defines a grid of locations where data pons exist. The command to generate ths pir of matrices is meshgrid. For example, suppose we are interested in plotting the function z= sin) sinG), Osxe2n, Osystn We can define a vector of pints for and y where we want o evaluate z 0:0.19p8:2%p4; ‘Basie Skills in Data Bniry and Manipulation Using Matlab [Note thatthe dimension of x andy is (Ix 21). Thats, we have created two row vectors with 21 point each (this could be checked using the whos command), We now use the meshgrid command o generate a grid of points inthe xy plane ranging over the data defined in he above vectors. ‘The command fo thsi: [6.4 = meshgriaix.y) [Noting apn that Matiab is case Sensitive, and so X is nt the same a x, the data in X and Y is the value of x and y at each point on the (WO ‘dimension grid of points. This canbe visualised as follows: Tage toad meee ———_—_—_—_——$—_—$————— To complete the dataset, we need to evaluat the function st each location ‘on the grid defined by X and Y. The Matlab command for doing this is “To now plot the data using a mesh format, eter: (6.2) ‘The results as follows: ” Using Matlab Tits, labels tex, et, could beaded inthe same way as fortwo dimensional plots ‘The plot can be changed to a surface, as opposed to a mesh, by using the command: eure on¥.2) “The resus 38 ‘Basle Skills in Data Entry end Manipulation Using Matlab ‘There area variety of coor, shading and image options which canbe applied to the plot. Enter help surf to get listing of some of these. Finally the above dataset ean also be contour plotted, using the command contour tx, ¥,2) ‘The results s follows: 3» lation Usis Matlab 40 Basie Skills in Data Entry and Manipulation Using Mtl Getting Help “Thete area variety of ways to get help in Matlab, including: The help command he help window “The Matiab helpdesk On-line reference pages “The ater thee are implemented from the Help menu in Matlab, and ac self= explanatory ‘The Help Command “The mos simple ofthe help options i the help command. To get basic help about any function. simply enter nol function If the topic you are interested in is nota function, then now useful information will be returmed when you enter the help command. If this happens, tr the Tookfor command, instead of the help command. Documentation ‘The entte set of Matlab documentation is available as PDF files. which ean be read and printed using Adobe Acrobat Look in the directory ‘umalabielpipdf_doe on your computer. “a

Das könnte Ihnen auch gefallen