Objects and Classes UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Slides:



Advertisements
Similar presentations
A MATLAB function is a special type of M-file that runs in its own independent workspace. It receives input data through an input argument list, and returns.
Advertisements

True or false A variable of type char can hold the value 301. ( F )
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
MATLAB and Simulinklecture 31 To days Outline  Functions  Strings  Sparse Arrays  Cell Arrays  Structures  Exercises on this days topics.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Solving ODEs UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative.
Functions UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative Commons.
Fundamentals of Python: From First Programs Through Data Structures
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
Numerical Integration UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Fall 2006AE6382 Design Computing1 OOP: Creating a Class More OOP concepts An example that creates a ASSET class and shows how it might be used Extend the.
Debugging UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative Commons.
Regression UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative Commons.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Simulink SubSystems and Masking April 22, Copyright , Andy Packard. This work is licensed under the.
Cell Arrays UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative Commons.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
Recursion and Induction UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Digital Image Processing Lecture10: MATLAB Example – Utility M-functions for Intensity Transformations.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Script Files UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative.
Numerical Differentiation UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under.
IEEE Arithmetic UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
Searching UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative Commons.
Struct Arrays UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative.
JavaScript, Fourth Edition
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
CSE123 Lecture 3 Files and File ManagementScripts.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Polynomials UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative Commons.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
Digital Image Processing Introduction to M-function Programming.
Basics of Matlab UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative.
Intro to Simulink April 15, Copyright , Andy Packard. This work is licensed under the Creative Commons.
Inheritance in Matlab Classes E177 February 14, Copyright , Andy Packard. This work is licensed.
Digital Image Processing Introduction to MATLAB. Background on MATLAB (Definition) MATLAB is a high-performance language for technical computing. The.
Root Finding UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative.
Fall 2006AE6382 Design Computing1 OOP Programming in Matlab Review our ASSET class and study how it might be used as a parent for other classes Extend.
Get/Set Methods UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Intro to Simulink Modified by Gary Balas 20 Feb 2011 Copyright , Andy Packard. This work is licensed under.
Introduction to CMex E177 April 25, Copyright 2005, Andy Packard. This work is licensed under the Creative.
OOP: Creating a Class Topics More OOP concepts
Java Primer 1: Types, Classes and Operators
For/Switch/While/Try UC Berkeley Fall 2004, E77 me
Scripts & Functions Scripts and functions are contained in .m-files
Operator Overloading BCA Sem III K.I.R.A.S.
MATLAB: Structures and File I/O
Control Structures – Selection
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
A First Book of ANSI C Fourth Edition
@ReferAssignGetSet February 21, me. berkeley
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
E177, Reference/Assignment for Classes: Intro February 12, Copyright , Andy Packard. This work.
Function Handles UC Berkeley Fall 2004, E Copyright 2005, Andy Packard
Arrays in Matlab UC Berkeley Fall 2004, E Copyright 2005, Andy Packard
Basics of Matlab UC Berkeley Fall 2004, E Copyright 2005, Andy Packard
Presentation transcript:

Objects and Classes UC Berkeley Fall 2004, E77 Copyright 2005, Andy Packard. This work is licensed under the Creative Commons Attribution-ShareAlike License. To view a copy of this license, visit or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.

Classes and Objects Objects and Classes User defined classes in Matlab Methods Designing a new class –Data –Methods Constructor Other methods, including operator overloading Dispatching and Precedence Inheritance An abstract class for get/set/reference/assignment

Classes and Objects Objects are variables with an identity (the class) and functions (the methods) to operate on them. Data may look like many different things –given a 3 by 1 column vector. Does it represent a date (day/month/year) a point in 3-dimensional space –Cartesian coordinates –Cylindrical coordinates –Spherical coordinates a quadratic polynomial or something else… And, what functions make sense on the data? So, classes give data an identity, and associate functions to the identity (don’t allow two dates to be multiplied). negative, distance between two points, add/subtract if cartesian coordinates are interpreted as components of a geometric vector subtract two dates, add an integer add, subtract, multiply, differentiate, integrate, evaluate, etc. These are the different “ methods ” Different identities

Classes/Objects and Methods in Matlab Objects are instances of the class Example: the most common class in Matlab is double. An instance of a double is, for example, >> M = [2 3;4 5;6 7] Another common class in Matlab is cell. >> C = [{M} {’e77’};{pi} {[]};{2} {3}] is an instance of class cell. Both classes have the method size and use identical () referencing methods. Only double (+), only cell has {} >> size(M) >> size(C) >> M(1,2) >> C(1,2) >> M+M >> C+C >> C{3,2} >> M{3,2}

User Defined Classes/Objects in Matlab Associated with a class, an Object is –a structure (ie., struct ), with a fixed set (for that class) of fields contains the data that constitutes the object –an internal hidden “tag” which labels the structure as an object of that class, and not just a Matlab struct. The structure’s fields are not accessible to the user The user interacts with the object using methods –function m-files (for example) that reside in the method’s folder for that particular class –Within methods m-files, the fields of the structure are accessible –Certain referencing methods ( subsref and subsasgn ) allow the programmer to give user access to the fields if desired. Next lecture for these…

Defining a class in Matlab Need a class for polynomial objects –purpose: to distinguish them from ordinary row vectors Pick a name for the class. This is the “classname”. –example: e177poly Create a folder of the same name as the class, but beginning with the character This is referred to as the methods folder. –example: create folder Decide on fields, and write the constructor method (an m- file) which creates objects (specific instances of the class) –The name of the m-file should be the same as the classname. –The constructor should be placed in the methods folder. Decide on methods, and write function m-files which implement the methods

e177poly data fields Design decision: the struct which contains the data that constitutes an e177poly object will have two fields –a row vector of coefficients, using the typical Matlab interpretation (ie., the roots command) where the row vector represents the polynomial coefficients, from highest power down to the 0 th power, fieldname is coeff –a single character for the symbol to represent the indeterminate variable of the polynomial, only used in display purposes, fieldname is symbol With this decision made, the constructor can be written. –The name of the constructor file is e177poly.m –The constructor file goes in folder.

Role of the constructor The Constructor must –Accept data as input arguments –Create a structure with the appropriate fields –Fill the fields of the structure based on the input arguments –Use the class command to “tag” the structure as an object of the e177poly class. If the constructor is called with –no input arguments it should create an “empty” or “default” instance. –an instance of the class as the input argument it should simply return the object.

Format of the constructor function h = e177poly(p) if nargin==0 h.coeff = []; h.symbol = ’x’; h = class(h,’e177poly’); else if isa(p,’e177poly’) h = p; elseif isa(p,’double’) h.coeff = p; h.symbol = ’x’; h = class(h,’e177poly’); end default instance Input argument is an object of this class Usual construction from row vector Creating the object of class “ e77poly ” from the structure using class Create structure from data

Common methods in the Methods folder 1.The constructor itself 2.the display method, which Matlab automatically calls if there is no semicolon at the end of an expression. Matlab passes the result to the display method. 3.converter methods, which convert the object to a different representation, if appropriate. 4.the get method, to access properties of the object 5.the set method, to change properties of the object 6.Operator overloaded methods, such as plus. The expression A+B is actually plus(A,B). If A and B are objects from the same class, and there is a plus method, it will be called.

Design Decision: Methods for e177poly Constructor, e177poly converter and display methods –double, converts a polynomial to a row vector of coefficients –char, converts a polynomial to a formatted string –display, for expressions that result in an e177poly object Operator overloaded methods –plus(A,B) for A+B –minus(A,B) for A-B –uplus(A) for + A –uminus(A) for - A –mtimes(A,B) for A*B Overloaded methods –roots, polyval, polyder, polyint Access methods ( get, set ), next e177poly.m double.m char.m display.m plus.m minus.m uplus.m uminus.m mtimes.m roots.m polyval.m polyder.m polyint.m get.m set.m

Method Dispatching and Precedence Suppose A and B are two objects of different class. Consider the expression SomeMethod(A,B) Question: Which method will be called? –SomeMethod.m in the methods folder of class(A), or … –SomeMethod.m in the methods folder of class(B) ? Answer: –If the objects have equal precedence, then the method from class(A) (ie., the first argument) will be called. –If the objects have unequal precedence, the method associated with the object of higher precedence will be called. Facts: –All user-defined classes have higher precedence than Matlab built-in classes (like double, char ). By default, all user- defined classes are of equal precedence. –Commands superiorto and inferiorto are used to define precedence among user-defined classes. More next lecture

Dispatching and Precedence Since e177poly objects have higher precedence than double objects, the sequence of commands >> A = e177poly([3 -1 4]); >> C = 2*A % mtimes >> D = A-5 % minus methods respectively (each with two arguments). Let’s write these multi-input argument functions –to handle non- e177poly objects, –knowing at least one argument will be an e177poly object.

Access methods: get and set The public properties of the object are –Retrieved using get –Modified using set, which can control changes that are allowed Properties have names to identify them, so a natural syntax is PropertyValue = get(Object,PropertyName) set(Object,PropertyName,PropertyValue) For the e77poly class, let’s make Symbol a public property –Its value is the single character symbol used to represent the indeterminate variable of the polynomial –Since the user will be able to control its value, we won’t allow binary operations (like + and * ) unless the symbols match.

Writing get is pretty easy function value = get(p,PropName) switch PropName case 'Symbol' value = p.symbol; otherwise error('Unknown property'); end The convention (we’ll see next week) in Matlab for value = get(Object) is to return a struct, whose fieldnames are the public properties. Easy to add this in, using nargin. Limited access

Writing set is a little harder Why won’t this work? function set(p,PropName,value) switch PropName case ’Symbol’ if isa(value,’char’) & isscalar(value) p.symbol = value; else error(’Invalid Symbol value’); end otherwise error(’Unknown property’); end Controlling what is allowed

Writing set is a little harder Without some trickery, the command set(a,PropName,Value) will not work as intended. In other words, after executing initvalue = get(a,PropName); newvalue = some_new_value; set(a,PropName,newvalue) the result of isequal(get(a,PropName),newvalue) is false, and the result of isequal(get(a,PropName),initvalue) is true. Why? (week 2/3): variables are passed to functions by value, changing them in the function only changes the function’s copy.

(recall) Accessing other workspaces Two built-in Matlab commands to circumvent this by –Allowing assignment of variables in other workspaces –Within a function, giving access to the name of an input argument variable in the caller’s workspace Specifically, these two functions are assignin –copy a variable from the current workspace into a different workspace, with a new, given name. inputname –Access the name (in the caller’s workspace) of an input argument variable.

Example with assignin >> >> v1 = [1 -2 3]; >> W = EXAMP1(v1); >> function [B] = EXAMP1(A) assignin(’caller’,’NEWV’,2*A); B = 3*A; BASE WORKSPACE v1: [1 -2 3] NEWV: [2 -4 6] W: [3 -6 9] FUNCTION INSTANCE WS A: [1 -2 3] B: [3 -6 9] function [B] = EXAMP1(A) assignin(’caller’,’NEWV’,2*A); B = 3*A;

Example with inputname >> >> fred = [2 3]; >> joe = [5 5]; >> W = EXAMP2(fred,joe); >> function [C] = EXAMP2(A,B) D = inputname(1); E = inputname(2); C = A + B; BASE WORKSPACEFUNCTION INSTANCE WS D: ’fred’ E: ’joe’ C: [7 8] function [C] = EXAMP2(A,B) D = inputname(1); E = inputname(2) C = A + B; fred: [2 3] joe: [5 5] W: [7 8] A: [2 3] B: [5 5]

Example using both Look at the function incr.m function incr(a) assignin(’caller’,inputname(1),a+1); It increments, without an output argument! >> var = 7; >> incr(var); >> var var = 8 >>

Fixing set uses this idea Here is one working version of set function set(p,PropName,value) switch PropName case 'Symbol' p.symbol = value; % need error check otherwise error('Unknown property'); end assignin(’caller’,inputname(1),p); Could also pass back an argument, or give user the option to do either…

A version of set allowing for either… function pnew = set(p,PropName,value) switch PropName case 'Symbol' p.symbol = value; % need error check otherwise error('Unknown property'); end if nargout==0 assignin(’caller’,inputname(1),p); else pnew = p; end

Nearly finished: Methods for e177poly Constructor, e177poly converter and display methods –double, converts a polynomial to a row vector of coefficients –char, converts a polynomial to a formatted string –display, for expressions that result in an e177poly object Operator overloaded methods –plus(A,B) for A+B –minus(A,B) for A-B –uplus(A) for +A –uminus(A) for -A –mtimes(A,B) for A*B Overloaded methods –roots, polyval, polyder, polyint Access methods ( get, set e177poly.m double.m char.m display.m plus.m minus.m uplus.m uminus.m mtimes.m roots.m polyval.m polyder.m polyint.m get.m set.m