Getting Started withMATLAB®7
Arranging the Desktop ... 7-4Start Button... 7-4Command Window and Command History...
3 Graphicsthe plot up and down or left and righ t without stretching it. Using themdoes not affect the figure itself, only the printed version of it.•
Preparing Graphs for Presentation• By default, MATLAB recalculates the locations of the axes tick marksbecause a printed graph is normally la rger tha
3 Graphics• When you are ready to print your plot, click Print in the right pane. Youcan also click Close to accept the settings and dismiss the dialo
Preparing Graphs for PresentationSet the size at which toexport the graph to a file.Specifying the Font SizeTo set the font size of all the text in th
3 GraphicsSelecting the File FormatAfter you finish setting options for the exported graph, click the Exportbutton. MATLAB displays a standard Save As
Using Basic Plotting FunctionsUsing Basic Plotting FunctionsIn this section.. .“Creating a Plot” on page 3-49“Plotting Multiple Data Sets in One Graph
3 Graphicstitle('Plot of the Sine Function','FontSize',12)Plotting Multiple Data Sets in One GraphMultiple x-y pair arguments crea
Using Basic Plotting Functionslegend('sin(x)','sin(x-.25)','sin (x-.5)')For More Information See “Defining the Color of
3 Graphics• Line style strings are '-' for solid, '--' for dashed, ':' for dotted, and'-.' for dash-dot. Omit
Using Basic Plotting FunctionsGraphing Imaginary and Complex DataWhen the arguments to plot are complex, the imaginary part is ignoredexcept when you
Component Object Model Interface ... 8-4Web Services... 8-5Serial Port Interface...
3 Graphicsdraws a 20-sided polygon with little circles at the vertices. The axis equalcommand makes the individual tick-mark increments on the x-andy-
Using Basic Plotting Functionshold oncontour(x,y,z,20,'k')hold offThe hold on command com bin es th e pcolor plot with the contour plot inon
3 GraphicsTo make an existing figure window the current figure, you can click the mousewhile th e pointer is in t hat wind ow or you can ty pefigure(n
Using Basic Plotting Functions[X,Y,Z] = cylinder(4*cos(t));subplot(2,2,1); mesh(X)subplot(2,2,2); mesh(Y)subplot(2,2,3); mesh(Z)subplot(2,2,4); mesh(X
3 GraphicsYoucanaddsubplotstoGUIsaswellastofigures.Fordetailsaboutcreatingsubplots in a GU I D E-g enerated GUI, see “Creating Subplo ts ” in the MATL
Using Basic Plotting Functionsfollowed by either axis square or axis equal turns the oval into a propercircle:axis auto normalreturns the axis scaling
3 GraphicsYou can produce mathematical symbols using LaTeX notation in the textstring, as the following example illustrates:t = -pi:pi/100:pi;y = sin(
Using Basic Plotting FunctionsSaving FiguresSave a figure by selecting Save from the File menu to display a Save dialogbox. MATLABsavesthedataitneedst
3 GraphicsNote The v6 option enables use rs of Version 7.x of MATLAB to createFIG-files that prev ious versions can open. It is obsolete and will be r
Creating Mesh and Surface PlotsCreating Mesh and Surface PlotsIn this section.. .“About Mesh and Surface Plots” on page 3-63“Visualizing Functions of
xii Contents
3 GraphicsR = sqrt(X.^2 + Y.^2) + e ps;Z = sin(R)./R;mesh(X,Y,Z,'EdgeColor','black')By default, MATLAB colors the m esh using the
Creating Mesh and Surface Plotssurf(X,Y,Z)colormap hsvcolorbarSee the colormap reference page for information o n colormaps.For More Information See “
3 Graphicsproduces a surface with a face alpha value of 0.4. Alpha values range from 0(completely transparent) to 1 (not transparent).For More Informa
Creating Mesh and Surface Plotssurf(X,Y,Z,'FaceColor','red','Edg eColor','none')camlight left; lighting phongM
3 GraphicsThese tools enable you to move the camera around the surface object,zoom, add lighting, and perform other viewing operations without issuing
Plotting Image DataPlotting Image DataIn this section.. .“About Plotting Image Data” on page 3-69“Reading and Writing Images” on page 3-70About Plotti
3 Graphicsand then u se the up arrow k e y on your keyboard to reexecute the image,colormap,andaxis commands. The statementcolormap(hot)adds some 21st
Printing Grap hicsPrinting GraphicsIn this section.. .“Overview of Printing” on page 3-71“Printing from the File Menu” on page 3-71“Exporting the Figu
3 Graphics• The Print option displays a dialog box that le ts you cho ose a pri nter, sele ctstandard printing options, and print the figure.Use Print
Printing Grap hicsprint -dtiff -r200 magicsquare.tiffIf you type print on the command line,printMATLAB prints the current figure on your default print
1IntroductionWhat Is MATLAB? (p. 1-2)See how MATLAB®can providesolutions for you in technicalcomputing, what are some ofthe comm on applications ofMAT
3 GraphicsHandle GraphicsIn this section.. .“Using the Handle” on page 3-74“Graphics Objects” on page 3-75“Setting Object Properties” on page 3-77“Spe
Handle Graphicsset(h,'Color','red')You can also specify properties when you call the plotting function:h = plot(x,y,'Color&ap
3 Graphics• Axes — Provide a frame of reference and scaling for the plotted lineseries.• Text — Label the axes tick marks a nd are u sed for titles an
Handle GraphicsFunction PurposeallchildFind all children of specified objects.ancestorFind ancestor of graphics object.copyobjCopy graphics object.del
3 Graphicssurf(x,y,z,'FaceColor','interp',. ..'FaceLighting','gouraud')plots the data in the variables x, y,an
Handle Graphicsprop_name(2) = {'MarkerFaceColor'} ;The prop_v alues cell array contains 10 values: five values for the Markerproperty and fi
3 GraphicsSpecifying the Axes or FigureMATLAB always creates an axes o r figure if one does not exist when youissue a plotting command. However, when
Handle Graphicshfig = figure('Name','Function and Mean',...'Pointer','fullcrosshair');hax = axes('Parent&
3 Graphicsare more than one. The following four sections provide examples illustratinghow to usefindobj.Finding All Objects of a Certain TypeBecause a
4ProgrammingIfyouhaveanactiveInternetconnection,youcanwatchtheWritingaMATLAB Program video demo for an overview of the major functionality.Flow Contro
1 IntroductionWhat Is MATLAB?In this section.. .“Overview of MATLAB” on page 1-2“The MATLAB System” on page 1-3Overview of MATLABMATLAB is a h igh-per
4 ProgrammingFlow ControlIn this section.. .“Conditional Control – if, else, switch” on page 4-2“Loop Control – for, while, continue, break” on page 4
Flow ControlIt is important to unde rstand how relational operators and if statementswork with matrices. When you want to check for equality betwe en
4 Programmingelseif A < B'less'elseif A == B'equal'elseerror('Unexpected situatio n')endSeveral functions are helpful
Flow ControlLoop Control – for, while, continue, breakThis section covers those MATLAB functions that provide control overprogram loops.forThe for loo
4 Programmingelseb = x; fb = fx;endendxThe result is a roo t of the polynomial x3-2x -5,namelyx=2.09455148154233The cautions involving matrix comparis
Flow ControlbreakThe bre ak statement lets you exit early from a for loop or while loop. Innested loops,break exits from the innermost loop only.Here
4 ProgrammingIn this sequence the statements b etween try an d catch are executed untilan error occurs. The statements betweencatch and end are then e
Other Data StructuresOther Data StructuresIn this section.. .“Multidimensional A rrays” on page 4-9“Cell Arrays” on page 4-11“Characters and Text” on
4 ProgrammingM(:,:,k) = A(:,p(k,:));endstores the sequence of 24 magic squares in a three-dimensional array, M.Thesize ofM issize(M)ans =4424Note The
Other Data Structures34 34 34 34andsum(M,2)is a 4-by-1-by-24 array containing 24 copies of the column vector34343434Finally,S = sum(M,3)adds the 24 ma
What Is MATLAB?and advanced courses in mathem atics, engineering, and science. In industry,MATLAB is the tool of choice for high-productivity research
4 ProgrammingThis is because the first two cells are too large to print in this limited space,but the third cell contains only a single number, 16!, s
Other Data StructuresYou can retrieve the 4-by-4 magic square matrix withM{4}Characters and TextEnter text into MATLAB using single quotes. For ex amp
4 ProgrammingInternally, the characters are stored as numbers, but not in floating-pointformat. The statementa = double(s)converts the character array
Other Data Structuresjoins the strings horizontally and producesh=Hello worldThe statementv = [s; 'world']joins the strings vertically and p
4 ProgrammingC='A''rolling''stone''gathers''momentum.'You can convert a padded character array to a
Other Data StructuresNow the structure is large enough that only a summary is printed:S=1x3 struct array with fields:namescoregradeThere are several w
4 ProgrammingSimilarly, you can create a cell array from the name fields by enclosing thelist-generating expression within curly braces:names = {S.nam
Other Data Structuresendavg = sum(scores)/(las t - first + 1);You can run this function using different values for the dynamic field stu den t.First,
4 ProgrammingScripts and FunctionsIn this section.. .“Overview” on page 4-20“Scripts” on page 4-21“Functions” on page 4-22“Types of Functions” on page
Scripts and FunctionsIf you duplicate function names, MATLAB executes the one that o ccurs firstin the search path.To view the contents of an M-file,
1 IntroductionGraphicsMATLAB has e xtensive facilities for displaying vectors and matrices asgraphs, as well as annotating and printing these graphs.
4 ProgrammingFunctionsFunctions are M-files that can accept input arguments and return outputarguments. ThenamesoftheM-fileandofthefunctionshouldbethe
Scripts and Functions% independent rows or c olumns of a mat rix A.% RANK(A,tol) is the nu mber of singular values of A% that are larger than tol.% RA
4 Programmingand output arguments involved in each particular use of the function. Therank function uses nargin, but does not need to use nargout.Type
Scripts and Functionsother M-files) while subfunctions cannot. Subfunctions are visible only to theprimary function and other subfunctions within thei
4 ProgrammingLike other functions, a neste d function has its own workspace where variablesused by the function are stored. B ut it also has a ccess t
Scripts and FunctionsThe two global statements make the value assigned to GRAVITY at thecommand prompt available inside the function. You can then mod
4 Programmings = ['August' int2str(d) '.dat'];load(s)% Code to proc ess the contents of the d-th fileendThe eval FunctionThe eval
Scripts and FunctionsThe function plot_f han dle, shown below, receives a function handle anddata, generates y-axis data using the function handle, an
4 ProgrammingThe graphshows that the function has a local minimum near x =0.6. Thefunctionfminsearch finds the minimizer,thevalueofx where the functio
Scripts and FunctionsQ = quadl(@humps,0,1)computes the area under the curve in the graph and producesQ=29.8583Finally, the graph shows that the functi
MATLAB DocumentationMATLAB DocumentationMATLAB provides extensive documentation, in both printable and HTMLformat, to help you learn about and use all
4 ProgrammingPreallocationIf you cannot vectorize a piece of code, you can make yourfor loops g o fasterby preallocating any vectors or arrays in whic
5Data AnalysisIntroduction (p. 5-2)Components of a data analysisPreprocessing Data (p. 5-3)Preparing data for analysisSummarizing Data (p. 5-10)Comput
5 Data AnalysisIntroductionEvery data analysis has some standard components:• Preprocessing — Consider outliers and m issing values, and smooth datato
Preprocessing DataPreprocessing DataIn this section.. .“Overview” on page 5-3“Loading the Data” on page 5-3“Missing Data” on page 5 -4“Outliers” on pa
5 Data AnalysisMissing DataIn MATLAB, NaN (Not a Number) values represent missing data. NaN valuesallow variables with missing data to maintain their
Preprocessing Datasigma3 = std(c3); % Da ta standard deviati onhist(c3) % Plot histogramhold onplot([mu3 mu3],[0 N],'r','LineWidt h&apo
5 Data Analysisc3m(outliers) = NaN; % Add Na N valuesSee “Removing Outliers” in the MATLAB Data Analysis documentation formore information on handling
Preprocessing DataNoisy data shows random variations about expected values. You may wantto smooth the data to reveal its main features before building
5 Data AnalysisThe extent of the smoothing is controlled with the variable span.Theaveraging calculation returnsNaN values whenever the smoothing wind
Preprocessing DataThe smoothed d ata are shifted from the previous plot. convn with the 'same'parameter returns the central part of the conv
1 IntroductionMATLAB also includes reference documentation for all MATLAB functions:• “Functions — By C ategory” — Lists all MATLAB functions grouped
5 Data AnalysisSummarizing DataIn this section.. .“Overview” on page 5-10“Measures of L ocation” on page 5-10“Measures of Scale” on page 5-11“Shape of
Summarizing Datax3 = mode(count)x3 =1199Like all of the statistical functions in MATLAB, the functions abovesummarize data across observations (rows)
5 Data Analysislegend('Intersection 1',...'Intersection 2',...'Intersection 3')Parametric models give analytic summaries
Summarizing Datamu1 = mean(c1);exp_pdf = @(t)(1/mu1)*exp(-t/mu1); % Integrates%to1t = 0:150;y = exp_pdf(t);plot(t,(hist_area)*y,'r','Li
5 Data AnalysisVisualizing DataIn this section.. .“Overview” on page 5-14“2-D Scatter Plots” on page 5-14“3-D Scatter Plots” on page 5-16“Scatter Plot
Visualizing DataThe strength of the linear relationship betw een the two variables (how tightlythe data lies along a least-squares line through the sc
5 Data Analysisof the variables to normalize values between +1 and –1. The results arecorrelation coefficients, computed by the MATLABcorrcoef functio
Visualizing DataThe strength of the linear relationship among the variables in the 3-D scatteris measured by computing eigenvalues of the covariance m
5 Data Analysisthe first principal component, along the axis of the data. U nlike the coefficientof determination for 2-D scatters, this measure does
Modeling DataModeling DataIn this section.. .“Overview” on page 5-19“Polynomial Regression” on page 5-19“General Linear Regression” on page 5-20Overvi
Starting and Quitting M ATLABStar ting and Quitting MATLABIn this section.. .“Starting MATLAB” on page 1-7“Quitting MATLAB” on page 1-8Starting MATLAB
5 Data AnalysisThe model has the advantage of being simple while following the up-and-downtrend. The accuracy of its predictive power, however, is que
Modeling DataX = [ones(size(tdata)) cos((2* pi/12)*(tdata-7))];s_coeffs = X\c3;figureplot(c3,'o-')hold ontfit = (1:0.01:24)';yfit = [on
5 Data Analysis73.2819stdx =8.918512.6127mse =1.9090e+003Check the assumption of a 12-hour period in the data with a periodogram,computed using the MA
Modeling DataThe peak near 0.0833 supports the assumption, although it occurs at aslightly higher frequency. The model can be adjusted accordingly.See
5 Data Analysis5-24
6Creating Graphical UserInterfacesWhat Is GUIDE? (p. 6-2)Introduces GUIDE, the MATLABgraphical user interface designenvironmentLaying Out a GUI (p. 6-
6 Creating Graphical User InterfacesWhat Is GUIDE?GUIDE, the M ATLAB graphical user interface development environment,provides a set of tools for crea
Laying Out a GUILaying Out a GUIIn this section.. .“Starting GUIDE ” on page 6-3“The Layout Editor” on page 6-4Starting GUIDEStart GUIDE by typing gui
6 Creating Graphical User InterfacesThe Layout EditorWhenyouopenaGUI in GUIDE, it is displayed in the Layout E ditor, which isthe control panel f or a
Laying Out a GUIYou can also use the L ayout Editor (along with the Toolbar Editor and IconEditor) to create m enus and toolbars, create and modify to
How to Contact The MathWorkswww.mathworks.comWebcomp.soft-sys.matlab Newsgroupwww.mathworks.com/contact_TS.html Technical [email protected]
1 IntroductionView or change thecurrent directory.Move or resize theCommand Window.Enter MATLABstatements at theprompt.Menus change,depending on theto
6 Creating Graphical User InterfacesProgramming a GUIAfter laying out the GUI and setting component properties, the next step is toprogram the GUI. Yo
7Desktop Tools andDevelopment EnvironmentIf you have an active Internet connection, you can watch the Working inThe Dev elopment Environment v ideo de
7 DesktopToolsandDevelopmentEnvironmentDesktop OverviewIn this section.. .“Introduction to the Desktop” on page 7-2“Arranging the Desktop” on page 7-4
Desktop Over viewView or change thecurrent directory.Move or resize theCommand Window.Enter MATLABstatements at theprompt.Menus change,depending on th
7 DesktopToolsandDevelopmentEnvironmentFor M ore Information For an overview o f the desktop tools, watch thevideo tutorials, accessible by typingdemo
Desktop Over viewFor More Info rm ation See “Desktop” in the MATLAB Desktop Tools andDevelopment Environment documentation.7-5
7 DesktopToolsandDevelopmentEnvironmentCommand Window and Command HistoryIn this section.. .“Command Window” on page 7-6“Command History” on page 7-7C
Command Window and Comma nd HistoryFor More Information See “Running Functions — Command Window andHistory” in the MATLAB Desktop Tools a nd Develo pm
7 DesktopToolsandDevelopmentEnvironmentHelpIn this section.. .“Help Browser” on page 7-8“Other Forms of H elp” on page 7-11“Typographical Conventions”
HelpTabs in the Help Navigator pane providedifferent ways to find information.Click the Close boxto hide the pane.View documentationin the display pan
Starting and Quitting M ATLABfinish.m each time M ATLAB quits that, for example, executes f unctions tosave the workspace.Confirm QuittingMATLAB can d
7 DesktopToolsandDevelopmentEnvironmentThesearethekeyfeatures:• Search for field — Look for s pe cific wor ds in the documentation anddemos. You can-
HelpOther Forms of HelpIn addition to the Help browser, you can use help functions. To get help fora specific function, use thedoc function. For examp
7 DesktopToolsandDevelopmentEnvironmentOther means for getting help include contacting Technical Support(www.mathworks.com/support) and participating
HelpItemConventionExampl eNew terms and foremphasisItalics In MATLAB, a matrix isa rectangular array ofnumbers.Omitted inputarguments(...) ellipsis de
7 DesktopToolsandDevelopmentEnvironmentCurrent D irectory Browser and Search PathIn this section.. .“Running Files” on page 7-14“Current Directory” on
Current Directory Browser and S earch P athDouble-click a fileto open it in anappropriate tool.Change the directory here.This field only appears here
7 DesktopToolsandDevelopmentEnvironmentTo see which directories are on the search path or to change the searchpath, select File > Set P ath and use
Workspace Browser and Array EditorWorkspace Browser and Array EditorIn this section.. .“Workspace Browser” on page 7-17“Array Editor” on page 7-18Work
7 DesktopToolsandDevelopmentEnvironmentto save to different formats. To read in a MAT-file, select File > ImportData,orusetheload function.For M or
Workspace Browser and Array EditorFor More Information See “Viewing and Editing Workspace Va riableswith the Array Editor” in the MATLAB Desktop Tools
1 Introduction1-10
7 DesktopToolsandDevelopmentEnvironmentEditor/DebuggerUse the Editor/Debugger to create and debug M-files, which are programs youwrite to run MATLAB f
Editor/DebuggerUse the document bar to access otherdocuments open in the Editor/Debugger.Comment selected linesand specify the indenting styleusing t
7 DesktopToolsandDevelopmentEnvironmentIfyouuseanothereditor,youcanstillusetheMATLABEditor/Debuggerfordebugging, or you can use debugging functions, s
M-Lint Code Check and Profiler ReportsM-Lint Code Check and Profiler ReportsIn this section.. .“M-LintCodeCheckReport”onpage7-23“Profiler” on page 7-2
7 DesktopToolsandDevelopmentEnvironmentIn M ATLA B, the M-Lint Code Check Report display s a message for each lin eof an M-file it determines might be
M-Lint Code Check and Profiler ReportsClick a line number to open the M-filein the Editor/Debugger at that line.The report displays a line number and
7 DesktopToolsandDevelopmentEnvironmentAlternatively, you can use automatic M-Lint code checking to view M-Lintmessages while you work on a file in th
M-Lint Code Check and Profiler ReportsFor More Information See “Tuning and M anaging M-Files” in the MATLABDesktop Tools and Development Environm ent
7 DesktopToolsandDevelopmentEnvironmentOther Development Environment FeaturesAdditional development environment fe atures include• Source Control — Ac
8External InterfacesUse MATLAB External Interfaces to connect M ATLAB to programs, devicesand data. Application developers use external interfaces to
2Matrices and ArraysYou can watch the Getting Started with MATLAB video demo for an ov e rviewof the major functionality.Matrices and Magic Squares (p
8 External InterfacesProgramming InterfacesIn this section.. .“Call MATLAB from C and Fortran Programs” on page 8-2“Call C and Fortran Programs from M
Programming InterfacesCall Java from MATLABMATLAB includes a Java Virtual Mach ine (JVM). This allo ws you to use th eJava interpreter with MATLAB com
8 External InterfacesComponent Object M odel InterfaceWith Component Object Model (COM) too ls and technologies, you canintegrate application-specific
Web Ser vicesWeb ServicesWeb services are XML-based technologies for making remote procedure callsover a network. They enable communication between ap
8 External InterfacesSerial Port InterfaceThe MATLAB serial port interface provides direct access to peripheral devicesthat you connect to your comput
IndexIndex: operator 2-82-D scatter plotsgetting started 5-143-D scatter plotsgetting started 5-16Aalgorithmsvectorizing 4-31annotating plots 3-17ans
IndexDdata analysisgetting started 5-1data sourcefor graphs 3-32debugging M-files 7-20deleting array elements 2-19demosrunning from the Start button 7
Indexgrids 3-59GUIDE 6-1HHandle Graphics 3-74defined 1-4finding handles 3-81Help browser 7-8help functions 7-11hold function 3-54Iif function 4-2image
Indexswapping columns 2-10symmetric 2-20transpose 2-5measures of locationgetting started 5-10measures of scalegetting started 5-11mesh plot 3-63Micros
Indexusing 3-42printingexample 3-42graphics 3-71Profiler 7-26Property Editorinterface 3-22Property Inspector 3-19using 3-19Qquitting MATLAB 1-8Rreturn
2 Matrices and Arra ysMatrices a nd Magic SquaresIn this section.. .“About Matrices” on page 2-2“Entering Matrices” on page 2-4“sum, transpose, and di
Indexlogical 2-27preallocating 4-32version control systemsinterfacing to MATLAB 7-28visibility of axes 3-59visualizing datagetting started 5-14Wwhile
Matrices and Mag ic SquaresThis im age is filled with mathematical symbolism, and if you look carefully,youwillseeamatrixintheupperright corner. This
2 Matrices and Arra ysEntering MatricesThe best way for you to get started with MATLAB is to learn how to handlematrices. Start MATLAB and follow a lo
Matrices and Mag ic SquaresMATLAB displays the matrix you just ente red:A=16321351011 89671241514 1This matrix matches the num bers in the engraving.
2 Matrices and Arra ysdiagona l, and also changes the sign of the imaginary component of anycomplex e lements of the matrix. The dot-apostrophe operat
Matrices and Mag ic Squaresandsum(diag(A))producesans =34The other diagonal, the so-called antidiagonal, is not so importantmathematically, so MATLAB
Revision HistoryDecember 1996 First printing For MATLAB 5May 1997 Second printing For MATLAB 5.1September 1998 Third printing For MATLAB 5.3September
2 Matrices and Arra ysregarded as one long column vector formed from the columns of the originalmatrix. So,forourmagicsquare,A(8) is another way of re
Matrices and Mag ic Squaresis0 0.7854 1.5708 2.3562 3.1416Subscript expressions involving colons refer to portions of a matrix:A(1:k,j)is the first k
2 Matrices and Arra ysThis matrix is almost the same as the one in the Dürer engraving and hasall the same “magic” properties; the only difference is
ExpressionsExpressionsIn this section.. .“Variables” on page 2-11“Numbers” on page 2-12“Operators” on page 2-12“Functions” on page 2-13“Examples of Ex
2 Matrices and Arra ysN=63The genvarname function can be useful in creating variable names that areboth valid and unique.NumbersMATLAB uses convention
Expressions'Complex conjugate transpose()Specify evaluation orderFunctionsMATLAB provides a large number of standard elementary mathematicalfunct
2 Matrices and Arra ysrealmaxLargest floatin g-point num ber,InfInfinityNaNNot-a-numberInfinity is generated by d ividing a nonzero value by zero, or
Expressionstoobig = pi*hugetoobig =Inf2-15
2 Matrices and Arra ysWorking with MatricesIn this section.. .“Generating Matrices” on page 2-16“The load Function” on page 2-17“M-Files” on page 2 -1
Working w ith MatricesR = randn(4,4)R=0.6353 0.0860 -0.3210 -1.2316-0.6014 -2.0046 1.2366 1.05560.5512 -0.4931 -0.6313 -0.1132-1.0998 0.4620 -2.3252 0
2 Matrices and Arra ys9.0 6.0 7.0 12.04.0 15.0 14.0 1.0 ];The statementmagikreads the file and creates a variable, A, containing the example matrix.Co
Working w ith MatricesDeleting Rows andColumnsYou can delete rows and columns from a matrix using just a pair of squarebrackets. StartwithX=A;Then, to
2 Matrices and Arra ysMore About Matrices and ArraysIn this section.. .“Linear Algebra” on page 2-20“Arrays” on page 2-24“Multivariate D ata” on page
More About Matrices and ArraysThe multiplication symbol, *, denotes the matrix multipli cation involvinginner products between rows and columns. Multi
2 Matrices and Arra yscondition estimate,isontheorderofeps , the floating-point relative precision,so the computed inverse is unlikely to be of much u
More About Matrices and Arrays0.1471 0.2941 0.3235 0.23530.2647 0.1765 0.2059 0.35290.1176 0.4412 0.4118 0.0294Such matric es represent the tr ansitio
2 Matrices and Arra ysArraysWhen they are taken away from the world of linear algebra, matrices becometwo-dimensional numeric arrays. Arithmetic opera
More About Matrices and ArraysThenpows = [n n.^2 2.^n ]builds a table of squares and p owers of 2:pows =001112244398416165253263664749128864256981512T
2 Matrices and Arra ysMultivariate DataMATLAB uses column-oriented analysis for multivariate statistical data.Each column in a data set repre sents a
More About Matrices and ArraysScalar ExpansionMatrices and scalars can be combined in several different ways. For example,ascalarissubtracted from a m
ContentsIntroduction1What Is MATLAB? ... 1-2Overview of MATLAB... 1-2The MATLAB System...
2 Matrices and Arra ysThis kind of subs cripting can be do n e in one step by specifying the logicaloperation as the subscripting expression. Suppose
More About Matrices and Arraysk = find(isprime(A))'picks out the locations, using one-dimensional indexing, of the primes in themagic square:k=2
2 Matrices and Arra ysControlling Command Window Input and OutputIn this section.. .“The format Function” on page 2-30“Suppressing Output” on page 2-3
Controlling Command Window Input and Outputformat long e1.333333333333333e+000 1.2345000000 00000e-006format long g1.33333333333333 1.2345e-006format
2 Matrices and Arra ysEntering Long StatementsIf a statement does not fit on one line, use an ellipsis (three periods), ...,followed by Return or Ente
Controlling Command Window Input and OutputKeyControl Key forMATLAB Standard(Emacs) Pre fe rence Operatio nCtrl+P Recall previous line. Works only at
2 Matrices and Arra ys2-34
3GraphicsOverview of MATLAB Plotting(p. 3-2)Create plots, include m ultiple d atasets, specify property values, andsave figures.Editing Plots (p. 3-17
3 GraphicsOver view of MATLAB PlottingIn this section.. .“Plotting Process” on page 3-2“Graph Components” on page 3-5“Figure Tools” on page 3-6“Arrang
Overview of MATLAB PlottingSee “Some Ways to Use MATLAB Plotting Tools” on page 3-23.• Use the command interface to enter commands in the Comm and Win
M-Files ... 2-17Concatenation... 2-18Deleting Rows and Columns...
3 Graphicsannotations to graphs when you want to show them to other people or w henyou want to save them for later reference.For More In forma tion Se
Overview of MATLAB Plotting• Save the graph as a FIG-file (select Save fro m the figure File menu).• Generate MATLAB code that can recreate the graph
3 GraphicsSee “Handle Graphics” on page 3-74 for more information about gra p hicsobject properties.The following picture shows the basic components o
Overview of MATLAB Plottingcontext menu items for individual tools such as zoom and pan. The figure alsoshows three figure toolbars, discussed in “Fig
3 GraphicsAccessing the ToolsYou can access or remove the figure toolbars and the plotting tools from theView menu, as shown in the following picture.
Overview of MATLAB PlottingPlotting ToolsPlotting tools are attached to figures and create an environm ent for creatinggraphs. These tools enable you
3 GraphicsYou can also control these components from the MATLAB Command Window,by typing the following:figurepaletteplotbrowserpropertyeditorSee the r
Overview of MATLAB PlottingUsing Plotting Tools and MATLAB CodeYou can enable the plotting tools for any g raph, even one created usingMATLAB commands
3 GraphicsFor example, adding a label for the y -axis that corresponds to the stem plotis easily accomplished by selecting that axes in the Plot Brows
Overview of MATLAB PlottingClick to add one axes to bottomof current layoutClick and drag right to specifyaxes layout.Select the a xes you want to tar
Preparing Gra phs for Pres entation ... 3-37Annotating Graphs for Presentation... 3-37Printing the Graph...
3 Graphics• In the Figure Palette, right-click a selected variable and choo se MorePlots from the context menu• In the Workspace Browser, right-click
Overview of MATLAB PlottingMATLAB displays the Plot Catalog in a new, un docked window with theselected variables ready to plot, a fter you sele ct a
3 GraphicsSelect a category of graphs and then choose a specific type.Specify variables to plot. See a description of each plot type.3-16
Editing PlotsEditing PlotsIn this section.. .“Plot Edit Mode” on page 3-17“Using Functions to Edit Graphs” on page 3-22Plot Edit ModePlot edit mode le
3 GraphicsThe context menu provides quick access to the most commonly used operationsand properties.Using the Property EditorIn plot edit mode, double
Editing PlotsClick to display Property InspectorAccessing Properties with the Property InspectorThe Property Inspector is a tool that enables you to a
3 GraphicsThefollowingpictureshowstheProperty Inspector displaying the propertiesof a graph’s axes. It lists each property and provides a text field o
Editing PlotsThe Property Inspector lists properties alphabetically by default. H owever,you can group H andle Graphics objects, such as axes, by cate
3 GraphicsUsing Functionsto Edit GraphsIf you prefer to work from the MATLAB command line, or if you are creatingan M-file, you can use MATLAB command
Some Ways to Use MATLAB Plotting ToolsSome Wa ys to Use MATLAB Plotting ToolsIn this section.. .“Plotting Two Variables with Plotting Tools” on page 3
Programming4Flow Control ... 4-2Conditional Control – if, else, s w itch...4-2Loop C ontrol – for, w
3 GraphicsVariables in workspace Figure plotting area3-24
Some Ways to Use MATLAB Plotting ToolsNote When you invoke plottool s, the set of p lotting tools you see and theirrelative positio ns depend on how t
3 GraphicsSelect plot(x, y) fromthemenu.MATLABcreatesthelinegraphinthefigurearea. The black squares indicate that the line is selected and you can edi
Some Ways to Use MATLAB Plotting ToolsSet line to no line.Set Marker to O.Set Marker fill color to red.Set Marker size to 4.0.Adding More Data to the
3 Graphicsif you issued repeated plotting commands. That is, the plotting tools are inahold on state.To add data using the Plot Browser:1 Click the Ed
Some Ways to Use MATLAB Plotting Tools1. Select axes.2. Click Add Data.3. Enter expression.ThepictureaboveshowshowtousetheAddDatatoAxesdialogboxtocrea
3 GraphicsChangingtheTypeofGraphThe plotting tools enable you to easily view your data with a variety of plottypes. The following picture shows the sa
Some Ways to Use MATLAB Plotting ToolsSelect both sets of data.Select Stem as the Plot Type.3-31
3 GraphicsModifying the Graph Data SourceYou can link graph data to variables in your workspace. When you changethe values contained in the variables,
Some Ways to Use MATLAB Plotting ToolsYou can use the Property Editor to change the data that this plot dis plays:1 Select the line ys vs x in the Plo
Smoothing and Filtering ... 5-6Summarizing Data... 5-10Overview...
3 GraphicsProviding New Values for the Data SourceMATLAB copies the data that defines the graph from variables in the baseworkspace (for e xample,x an
Some Ways to Use MATLAB Plotting ToolsNow recalculate y at the command line:y = cos(x)Selectthebluelineontheplot. Select,x as the X Data Source, y as
3 Graphics3-36
Preparing Graphs for PresentationPreparing Graphs for PresentationIn this section.. .“Annotating Graphs for Presentation” on page 3-37“Printing the Gr
3 GraphicsNow suppose you want to save copies of the graph b y• Printing the graph on a local printer so you have a copy for your notebook• Exportingt
Preparing Graphs for PresentationLabel some key points with data tips using the Data Cursor tool .Noticethat left-clicking the line moves the last dat
3 GraphicsNowaddatextbox,alsousingtheFigurePalette.Youmayhavetoscrolltosee the text box icon. Drag out a box, and then type into it. You can stretchor
Preparing Graphs for PresentationFinally, add text annotations, axis labels, and a title. You can add the title andaxis l abels u s ing th e followin
3 GraphicsYou can also add these annotations by selecting the axes and typing the abovestrings into their respective fields in the Property E ditor. T
Preparing Graphs for Presentationfield, and also use the Date Style drop-down list to specify a date format toadd the current date/time to the header.
Comentarios a estos manuales