Lecture 5 Advanced MATLAB: Object-Oriented Programming

Transcription

Introduction to OOPOOP in MATLABLecture 5Advanced MATLAB:Object-Oriented ProgrammingMatthew J. ZahrCME 292Advanced MATLAB for Scientific ComputingStanford University7th October 2014CME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLAB1Introduction to OOP2OOP in MATLABClass Definition and OrganizationClassesCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABWhat is OOP?Procedural programming is a list of instructions for the computer toperform to accomplish a given taskCode and dataNo association between functions and the data on which they operateLanguages: FORTRAN, CObject-oriented programming (OOP) is a programming paradigmorganized around objects equipped with data fields and associatedmethods.Data (state) and methods (behavior) associated via objectsObjects used to interact with each otherLanguages: C , Objective-C, Smalltalk, Java, C#, Perl, Python, Ruby,PHPCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABWhy use OOP?OOP enables a level of modularity and abstraction not generally available inprocedural languagesIncreased code understandingCode maintenanceCode expansion/evolutionCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABOOP FundamentalsClass: template for creating objects, defining properties and methods,as well as default values/behaviorObject: instance of a class that has a state (properties) and behavior(methods)Properties: data associated with an objectMethods: functions (behavior) defined in a class and associated withan objectAttributes: modify behavior of classes and class componentsInheritance: object or class (subclass) derived from another object orclass (superclass)Polymorphism: single interface to entities of different typesOther OOP features include events and listeners, which will not be coveredCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesClass Components in MATLABclassdef blockContains class definition, class attributes, and defines superclassesproperties blockDefines all properties to be associated with a class instanceDefines attributes of all properties and default valuesmethods blockDefines methods associated with the class and their attributesFirst method must have the same name as the class, called the constructorevent blockenumeration blockhttp://www.mathworks.com/help/matlab/matlab oop/class-components.htmlCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesClass BlockClass definitions - blocks of code delineated with classdef . endkeywordsSpecify attributes and superclassesContains properties, methods, events subblocksOne class definition per fileOnly comments and blanks can precede classdefCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesProperties: Definition/InitializationProperties are variables associated a particular classDefined in special properties blockCan be multiple properties blocks, each with own attributesCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesProperties: Initialization/Attributes123456789classdef class namepropertiesPropertyNameendproperties (SetAccess private,GetAccess public)PropertyName 'some text';PropertyName sin(pi/12);endendProperty attributes: http://www.mathworks.com/help/matlab/matlab oop/property-attributes.htmlCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesMethodsMethods are MATLAB functions associated with a particular classDefined in special methods blockCan be multiple methods blocks123456789101112classdef ClassNamemethodsfunction obj ClassName(arg1,arg2,.)endfunction normal method(obj,arg1,.)endendmethods (Static true)function static method(arg1,.)endendendCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesValue vs. Handle ClassThere are two fundamentally different types of classes in MATLABValue classHandle classAn instance of a value class behaves similar to most MATLAB objectsA variable containing an instance of a value class owns the data associatedto itAssigning object to new variable copies the variableConversely, an instance of a handle class behaves similar to MATLABgraphics handlesA variable containing an instance of a handle class is a reference to theassociated data and methodsAssigning object to a new variables makes a new reference to same objectEvents, listeners, dynamic dle-classes.htmlCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesExamplesThe remainder of this lecture will be done in the context of two examplespolynomial.mA value class for handling polynomials of the formp(x) c0 c1 x c2 x2 · · · cm xmin a convenient and simple waySimple interface for performing operations of polynomials to create newonesdsg elem def.mA handle class for graphically deforming the deformation of a bodyBoth examples are incomplete. We will (mostly) complete polynomial.mthroughout the remainder of the lecture. You will have the opportunity toextend both in Homework 3.CME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABpolynomialClass Definition and OrganizationClassesclassclassdef polynomial%POLYNOMIALproperties (GetAccess public,SetAccess private)coeffs 0;order onfunctionfunctionfunctionfunctionfunctionself polynomial(arg)[tf] iszero(poly)[y] evaluate(poly,x)[apoly] plus(poly1,poly2)[mpoly] minus(poly1,poly2)[ipoly] integrate(poly,const)[dpoly] differentiate(poly)[iseq] eq(poly1,poly2)[] plot it(poly,x,pstr,ax)[] disp(poly)CME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesConstructor - Create instance of classTo create an instance of a class for a list of arguments, call its constructorBy definition, the constructor is the first method in the first methodblockIt is required to have the same name as the class (polynomial in ourcase)Responsible for setting properties of class based on input argumentsProperties not set will be given default valueDefault value either [] or defined in properties blockReturns instance of classSee polynomial in polynomial.m p1 polynomial([1,2,3]);%3xˆ2 2x 1 p2 polynomial(p1);%3xˆ2 2x 1 p3 polynomial([1,2,3,0]); %3xˆ2 2x 1CME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesObject ArraysSimilar to arrays of numbers, cells, and structures, we can define objectsarrays as an array where each element is an instance, or object, of aparticular class p(1,7) polynomial([1,2,3]); length(p)ans 7 p(3)ans 0.0000 p(7)ans 1.0000 2.0000 x 3.0000 xˆ2CME 292: Advanced MATLAB for SC%3xˆ2 2x 1Lecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesAccessing PropertiesProperties are accessed using the . operator, similar to accessing fields in astructure. p1.orderans 2 p2.coeffsans 123CME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesPublic vs. private propertiesRecall the properties block definition of polynomialproperties (GetAccess public,SetAccess private)coeffs [];order 0;endGetAccess, SetAccess define where the properties can be queried orset, respectivelypublic properties have unrestricted accessprotected properties can only be accessed from within class or subclassprivate properties can only be accessed from within classp3.coeffs [5,2,3];? Setting the 'coeffs' property of the 'polynomial' class .is not allowed.CME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesTypes of MethodsThis information is directly from http://www.mathworks.com/help/matlab/matlab oop/how-to-use-methods.htmlOrdinary methods - functions that act on one or more objects (plusadditional data) and return a new object or some computed valueConstructor methods - special function that creates the objects of aclassDestructor methods - function called when instance of class is deletedStatics methods - functions associated with a class that do notnecessarily act on class objectsCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesUsing MethodsAll methods must accept the class instance as their first argumentMethods can be accessed in two main waysUsing the . operator with the class instanceImplicitly passes the class instance as the first argumentDirectly passing the class instance as the first argument p3.iszero()ans 0 p3.evaluate(0:0.25:1.0)ans 1.00001.68752.7500 p4 polynomial(0); p4.iszero()ans 1CME 292: Advanced MATLAB for SC4.1875Lecture 56.0000

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesImplementing OperatorsOperators such as , , *, .*, , , , etc can be overload for a givenclassSimply implement a method with an appropriate name and number ofargumentA list of operators and their corresponding name are listed hereWhen operator such as called, it uses the data type to determine whenfunction is calledfunction [iseq] eq(poly1,poly2)iseq all(poly1.coeffs poly2.coeffs);end p1 p2ans 1 p1 p4ans 0CME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABAssignment:Class Definition and OrganizationClassespolynomialIn polynomial.m, implementplus to overload the operator to return p3 (x) p1 (x) p2 (x)minus to overload the operator to return p3 (x) p1 (x) p2 (x)differentiate to return p0 (x)integrate to returnThen, define p1 (x) polynomial class to10x2Rp(x) dx x 3 and p2 (x) 2x3 x 9. Use thecompute the polynomial p3 (x) defined as p3 (x) p1 (x) p2 (x)compute the polynomial p4 (x) defined as p4 (x) p1 (x) p2 (x)CME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABAssignment:Class Definition and OrganizationClassespolynomialConstruct simple example to check implementation of mtimes andmpowerCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABAssignment:Class Definition and OrganizationClassespolynomialDefine the piecewise cubic polynomial(x3 6x 2p(x) x3 x2 2for x [ 1, 0]for x [0, 1]compute the derivative of p(x) (the fact that it does not exist at 0should not cause problems)compute the definite integral of p(x) over [ 1, 1]CME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesHandle ClassHandle class is a reference to data and methods (similar to graphicshandles as references to graphics objects)In contrast to value classes, handle classes enable you to create anobject that more than one function can shareDeclare class a handle class by having it inherit from the handlesuperclassSimilar to handle classes,the first argument of all methods must be the class instance itselfmethods are invoked identicallyclassdef dsg elem def handlepropertiesendendCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABClass Definition and OrganizationClassesHandle ClassUnlike value classes, a method in a handle class can modify properties ofthe class instanceRemoves need for instantiating new objects and returning them inmethodsA method can simply modify the properties of the instance in placeDoes not necessarily require an outputCME 292: Advanced MATLAB for SCLecture 5

Introduction to OOPOOP in MATLABExample:Class Definition and OrganizationClassesdsg elem defSee Homework 3 handout for detailsDemoCME 292: Advanced MATLAB for SCLecture 5

CME 292: Advanced MATLAB for SC Lecture 5. Introduction to OOP OOP in MATLAB Class De nition and Organization Classes Implementing Operators Operators such as , , *,.*, , , , etc can be overload for a given class Simply implement