1、MATLAB Object-Oriented Programming R2013aHow to Contact MathWorks Web comp.soft-sys.matlab Newsgroup Technical Support Product enhancementsuggestions Bug reports Documentation error reports Orderstatus,licenserenewals,passcodes Sales,pricing,andgeneralinformation 508-647-7000(Phone) 508-647-7
2、001(Fax) TheMathWorks,Inc. 3 Apple Hill Drive Natick, MA 01760-2098 Forcontactinformationaboutworldwideoffices,seetheMathWorksWebsite. Object-Oriented Programming COPYRIGHT 19842013 by The MathWorks, Inc. Thesoftwaredescribedinthisdocumentisfurnishedunderalicenseagreement. Thesoftwaremaybeused or co
3、pied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks, Inc. FEDERAL ACQUISITION: Thisprovision applies to all acquisitions ofthe Programand Documentation by, for, or through the federal
4、 government of the United States. By accepting delivery of the Program or Documentation, the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation assuch terms are used or defined in FAR 12.212, DFARS Part
5、 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions of this Agreement and onlythoserights specified inthis Agreement, shall pertain to andgovern theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand Documentationbythefederalgovernment(orotherent
6、ityacquiringfororthroughthefederalgovernment) and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the governmentsneedsorisinconsistentinanyrespectwithfederalprocurementlaw,thegovernmentagrees to return the Program and Documentation, unused, to The MathW
7、orks, Inc. Trademarks MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See for a list of additional trademarks. Other product or brand namesmay be trademarks orregistered trademarksof their respectiveholders. Patents MathWorks products are protected by one or more U.S. patents.
8、Please see for more information.Revision History March 2008 Online only New for MATLAB 7.6 (Release 2008a) October 2008 Online only Revised for MATLAB 7.7 (Release 2008b) March 2009 Online only Revised for MATLAB 7.8 (Release 2009a) September 2009 Online only Revised for MATLAB 7.9 (Release 2009b)
9、March 2010 Online only Revised for MATLAB 7.10 (Release 2010a) September 2010 Online only Revised for Version 7.11 (Release 2010b) April 2011 Online only Revised for Version 7.12 (Release 2011a) September 2011 Online only Revised for Version 7.13 (Release 2011b) March 2012 Online only Revised for Ve
10、rsion 7.14 (Release 2012a) September 2012 Online only Revised for Version 8.0 (Release 2012b) March 2013 Online only Revised for Version 8.1 (Release 2013a)1 Using Object-Oriented Design in MATLAB “Begin Using Object-Oriented Programming” on page 1-2 “Why Use Object-Oriented Design” on page 1-4 “Cla
11、ss Diagram Notation” on page 1-171 Using Object-Oriented Design in MATLAB Begin Using Object-Oriented Programming In this section. “Video Demo of MATLAB Classes” on page 1-2 “MATLABProgrammerWithoutObject-OrientedProgrammingExperience” on page 1-2 “MATLAB Programmer with Object-Oriented Programming
12、Experience” on page 1-2 VideoDemoofMATLABClasses YoucanwatchabriefpresentationonMATLAB class development by clicking this link: Play video MATLAB Programmer Without Object-Oriented Programming Experience If you create MATLAB programs, but are not defining classes to accomplish your tasks, start with
13、 the following sections: “Why Use Object-Oriented Design” on page 1-4 “Classes in the MATLAB Language” on page 2-2 “Introductory Examples” on page 2-6 “Learning Object-Oriented Programming” on page 2-7 MATLAB Programmer with Object-Oriented Programming Experience If have experience with both MATLAB
14、programming and object-oriented techniques, start with the following sections: “Class Files” on page 3-2 “Compatibility with Previous Versions ” on page 3-46 1-2Begin Using Object-Oriented Programming “ComparingMATLAB with OtherOO Languages”on page3-50 1-31 Using Object-Oriented Design in MATLAB Why
15、 Use Object-Oriented Design In this section. “Approaches to Writing MATLAB Programs” on page 1-4 “WhenShouldYouStartCreatingObject-OrientedPrograms”onpage1-8 Approaches to Writing MATLAB Programs Creatingsoftwareapplicationstypically involves designinghow torepresent theapplicationdataanddetermining
16、howtoimplementoperationsperformed onthatdata. Proceduralprograms pass data to functions,which perform the necessary operations on the data. Object-oriented software encapsulates data and operations in objects that interact with each other via the objects interface. TheMATLABlanguageenablesyoutocreat
17、eprogramsusingbothprocedural and object-oriented techniques and to use objects and ordinary functions in your programs. Procedural Program Design In procedural programming, your design focuses on steps that must be executedtoachieveadesiredstate. Youtypicallyrepresentdataasindividual variables or fi
18、elds of a structure and implement operations as functions that take the variables as arguments. Programs usually call a sequence of functions, each oneof which ispassed data, and then returns modified data. Eachfunctionperformsanoperationorperhapsmanyoperationsonthedata. Object-Oriented Program Desi
19、gn The object-oriented program design involves: Identifying the components of the system or application that you want to build Analyzingandidentifyingpatternstodeterminewhatcomponentsareused repeatedly or share characteristics Classifying components based on similaritiesand differences 1-4Why Use Ob
20、ject-Oriented Design After performing this analysis, you defineclassesthatdescribetheobjects your application uses. Classes and Objects A class describes a set of objects with common characteristics. Objects are specificinstancesofaclass. Thevaluescontainedinanobjectspropertiesare whatmakean object
21、different from other objects ofthe same class (an object of class double might have a value of 5). The functions defined by the class (calledmethods)arewhatimplementobjectbehaviorsthatarecommontoall objectsofaclass(youcanaddtwodoubles regardless oftheirvalues). Using Objects in MATLAB Programs The M
22、ATLAB language defines objects that are designed for use in any MATLABcode. Forexample,considerthe try/catchprogrammingconstruct. Ifthecodeexecutedinthetry block generates an error, program control passes to the code in the catch block. This behavior enables your program to providespecial error hand
23、ling that ismoreappropriate to your particular application. However, you must haveenough information about the error to take the appropriate action. MATLAB provides detailed information about the error by passing an MException object to functions executing the try/catch blocks. The following try/cat
24、ch blocks display the error message stored in an MException object when a function (surf in this case) is called without the necessary arguments: try surf catch ME disp(ME.message) end Not enough input arguments. In this code, ME is an object of the MException class, which is returned by the catch s
25、tatement to the functions workspace. Displaying the value of the objects message property returns information about the error (the surf 1-51 Using Object-Oriented Design in MATLAB function requiresinput arguments). However, thisisnot all the information available in the MException object. You can li
26、stthepublicpropertiesofanobjectwith the propertiesfunction: properties(ME) Properties for class MException: identifier message cause stack Objects Organize Data The information returned in an MException object is stored in properties, which are much like structure fields. You reference a property us
27、ing dot notation,asin ME.message. Thisreferencereturnsthevalueoftheproperty. For example, class(ME.message) ans = char showsthatthevalueofthe message propertyisanarrayofclass char(a text string). The stack property contains a MATLAB struct: ME.stack ans = file: 1x90 char name: surf line: 50 You can
28、simply treat the property reference, ME.stack as a structure and reference its fields: ME.stack.file ans = D:myMATLABmatlabtoolboxmatlabgraph3dsurf.m The file field of the struct contained in the stack property is a character array: 1-6Why Use Object-Oriented Design class(ME.stack.file) ans = char Y
29、oucould,forexample,use apropertyreference inMATLABfunctions: strcmp(ME.stack.name,surf) ans = 1 Objectpropertiescan contain anyclassofvalueandcanevendeterminetheir value dynamically. This provides more flexibility than a structure and is easier to investigate than a cell array, which lacks fieldname
30、s and requires indexing into various cells using array dimensions. Objects Manage Their Own Data You couldwritea function thatgeneratesareportfrom thedata returnedby MException object properties. This function could become quite complicated because it would have to be able to handle all possible err
31、ors. Perhaps you wouldusedifferentfunctionsfordifferent try/catch blocksin yourprogram. If the data returnedby the error object needed to change, you would have to update the functions you have written to use the new data. Objects provide an advantage in that objects define their own operations. A r
32、equirement of the MException object is that it can generate its own report. The methods that implement an objects operations are part of the object definition (i.e., specified by the class that defines the object). The object definitionmightbemodifiedmanytimes,buttheinterfaceyourprogram(and otherpro
33、grams)usedoesnotchange. Thinkofyourprogram asaclientofthe object, which isolates your code from the objects code. ToseewhatmethodsexistforMExceptionobjects,usethemethodsfunction: methods(ME) Methods for class MException: addCause getReport ne throw eq isequal rethrow throwAsCaller Static methods: 1-
34、71 Using Object-Oriented Design in MATLAB last You can usethesemethodslikeanyotherMATLAB statementwhenthereis an MException object in the workspace. For example: ME.getReport ans = Error using = surf Not enough input arguments. Objectsoftenhavemethodsthatoverload(redefinedfortheparticularclassof the
35、object)MATLAB functions(e.g., isequal, fieldnames,etc.). Thisenables you to use objects just like other values. For example, MException objects haveanisequal method. Thismethodenablesyou to comparetheseobjects in the same way you would compare variables containing doubles. If ME and ME2are MExceptio
36、nobjects,youcancomparethemwiththis statement: isequal(ME,ME2) However, whatreallyhappensin thiscaseisMATLABcallsthe MException isequalmethodbecauseyouhavepassedMExceptionobjectsto isequal. Similarly,the eqmethodenablesyoutousethe=operatorwith MException objects: ME = ME2 Of course, objects should su
37、pport only those methods that make sense. For example,itwouldprobablynotmakesensetomultiplyMException objectsso the MException class does not implement methods to do so. When Should You Start Creating Object-Oriented Programs ObjectsarewellintegratedintotheMATLABlanguage,regardlessofwhether you are
38、writing simple functions, working interactively in the command window, or creating large applications. Simple programming tasks are easily implemented as simple functions, but as the magnitude and complexity of your tasks increase, functions become more complex and difficult to manage. 1-8Why Use Ob
39、ject-Oriented Design As functions become too large, you might break them into smaller functions and pass data from one to the other. However, as the number of functions becomeslarge,designingandmanagingthedatapassedtofunctionsbecomes difficult and error prone. At this point, you should consider movi
40、ng your MATLAB programming tasks to object-oriented designs. Understanding a Problem in Terms of Its Objects Thinking in terms of things or objects is simpler and more natural for some problems. You might think of the nouns in your problem statement as the objectsyouneedtodefineandtheverbsastheopera
41、tionsyoumustperform. Forexample,considerperformingananalysisofeconomicinstitutions.It would be difficult to represent the various institutions as procedures even thoughthey are allactors in the overalleconomy. Consider banks, mortgage companies,creditunions. Youcanrepresenteachinstitutionasanobjectt
42、hat performs certain actions and contains certain data. Theprocessof designing the objects involves identifying the characteristics of these institutions that are important to your application. Identify Commonalities. Alloftheseinstitutionsbelonginthegeneralclass oflendinginstitutions,soallobjectsmi
43、ghtprovidea loanoperationandhave a Rate property that stores the current interest rate. Identify Differences. Youmustalsoconsiderhoweachinstitutiondiffers. A mortgage company might provide only home mortgage loans. Therefore, the loan operation mightneedbespecialized formortgagecompaniestoprovide fi
44、xRateLoanand varRateLoanmethodstoaccommodatetwoloantypes. Consider Interactions. Institutions can interact, as well. For example, a mortgage company mightsella mortgageto a bank. To supportthis activity, the mortgage company object would support a sellMortgage operation and the bank object would sup
45、port a buyMortgage operation. Youmightalsodefinealoanobject,which would represent a particular loan. It might need Amount, Rate,andLender properties. When the loan is sold to another institution, the Lender property could be changed, but all other information is neatly packaged within the loan objec
46、t. 1-91 Using Object-Oriented Design in MATLAB Add Only What Is Necessary. Itislikelythattheseinstitutionsengagein manyactivitiesthatarenotofinteresttoyourapplication. Duringthedesign phase, you need to determine what operations and data an object needs to contain based on your problem definition. M
47、anaging Data. Objects encapsulate the model of what the object represents. If the object represents a kind of lending institution, all the behaviors of lending institutions that are necessary for your application are contained by this object. This approach simplifies the management of data that is n
48、ecessary in a typical procedural program. Objects Manage Internal State In the simplest sense, objects are data structures that encapsulate some internalstate,whichyouaccessviaits methods. Whenyou invokeamethod, it is the object that determines exactly what code to execute. In fact, two objects of t
49、he same class might execute different code paths for the same method invocation because their internal state is different. The internal workings of the object need not be of concern to your program you simply use the interface the object provides. Hiding the internalstatefrom general accessleadstomorerobust code. If a loan objects L