Sie sind auf Seite 1von 34

Advanced OOP Dynamic Programming

IAP 2009 Scott Gorlin gorlins@mit.edu

http !!stellar.mit.edu!S!pro"ect!advanced#matla$!

OOP
%

&he 'ig Advantages


% (ncapsulation % Overloading % Inheritance % Aesthetics!Deployment!)olla$oration

OOP
%

Good class e*amples


% )omple* data +iles
% % % % )on+ocal image stac,s - read series. plot series etc Any /D volume data )ompressed data. etc 'inary data +ormats - read!0rite to dis,

% AI
% )lassi+iers 0ith training data. classi+ication routines

% (*periment
% 1hat $etter2 3e4uires data and methods5

Pac,ages
% %

1raps up multiple classes. and!or pac,age +unctions 6ne0 in 7.89: Simple


% )reate directory +pkgname/
% fun1.m, @Class1, +subpkg, etc inside % ;i,e classdirs. don<t need to add to path

% =sage
% % >> >> pkgname.fun1(); obj = import pkg.*; fun1(); pkgname.Class1() obj=Class1();

Pac,ages
% %

Group related code!classes!constants (ven larger reusa$le units Divide up namespace


% pkg.plot() vs plot() % pkg.plot() vs pkg .plot()

Pac,ages # (*ample
%

Py>?PA - multivariate pattern analysis 6Python:

OOP
%

)lass &ric,s % )lass and method attri$utes. li,e property attri$utes


% 1e can have private +unctions as 0ell as private data
% !""ess attri$ute. or any method can have a su$+unction % Great +or utility routines that should only $e called $y the o$"ect itsel+. or restricted +unctions % Any +older can have a su$directory named <private<. only calla$le +rom that directory

OOP
%

>ore advanced techni4ues...


% (vents. noti+ications. listeners
% Allo0s other o$"ects to listen to a class instance +or things li,e +unction calls. property changes. etc

% meta"lass in+o. # Operator


% Allo0s introspection into class heirarchy

% % %

Overload $elete() >ultiple inheritance Dynamic properties


% Su$class $%nami"props. can call a$$prop()

@andles
% %

)lasses may su$class &an$le Pass $y re+erence55


% 3educe memory. easier synta*. 6unclear overhead: % 'rea,s all >atla$ conventions...

cf r.incr() c.f.rr = = r.incr();

OOP
%

&ypes o+ methods
% % % % % Standard - actually does stu++ )onstructor 6$uild o$"ect: Destructor 6cleanup deleted o$"ect: Property get!set 6esp. +or dependent props: Operator overloads 6eg 9 # A .A ! .! B C 6: DE FG:

% Static - +or a class. $ut not an o$"ect % )onversion - creates instance o+ a di++erent class % A$stract - not implemented. $ut must $e de+ined in a su$class 6$uilds interfaces:

OOP
%

One >AHO3 dra0$ac,

% Property de+initions )AIIO& change

% I+ properties change you 0ill IO& $e a$le to reuse saved o$"ects % During development. i+ you change you must
' >> "lear "lasses % &hey 0ill $e treated as structures $ut class initialiJation 0ill +ail % )an 0rite a method to convert your old +ormat to your ne0 +ormat

% I.e.. all o$"ects o+ same class >=S& have same +ields. in the same order

% I+ you do not save o$"ects $et0een sessions. this is moot % >ethods can change at any time

OOP
%

Di++erences +rom )!Hava!Python )lasses


% Interpreted - not HI& compliant. so should not $e used in critical loops
% )an still have HI& compliant methods % >ath0or,s claims HI& compliance. $ut I don<t see it

% Old 7.K synta* runs +aster in some tests... % Io pointers. so they lose some po0er
% @andles - must de+ine inheritance. some overhead

% % %

&ypecasting!inheritance not as good Synta* not as clean Io dynamic de+initions li,e Python

Dynamic Programming Duc, &yping

Dynamic Programming
%

>odi+ying the $ehavior o+ +unctions at runtime Simplest e*ample +unction ta,es argument telling it ho0 to 0or,
% Lunction d M dist6pointN. point2. space:
s0itch space
case <city$loc,< d M sum6a$s6pointN#point2::O case <euclidian< d M s4rt6sum66pointN#point2:.C2::O ...

Lunction handles
% %

1e can. instead. use functions as variables Inline +unctions


% + M inline6<some e*pression<: % Automatically loo,s +or varia$les in e*pression. uses as input to +unction % Io 0or,space!scope o+ its o0n

Lunction handles
% + M @+cnPnameO eg +M@sinO or + M str2+unc6<sin<: % Io0 +6...: calls sin6...:

Lunction handles
%

Anonymous +unctions
% % % + M @6args...: e*prO )reates single#line +unction =ni4ue 0or,space - varia$les used in e*pr are copied +rom parent +unction
% % % Ie "onst=(; f = @()) "onst*); (4uivalent to f = @())(*); Allo0s modi+ying +unctions at runtime

Lunction @andles
%

Simple e*ample

Imports variable

NB: changing "onst after creating &()) in junk function does not modif "onst in &())! since it has its o"n "orkspace (unless it's a handle object!)

Lunction @andles

Lunction generators
%

Lunction creates. returns a calla$le +unction


% fun"tion rbf = "reate*bf+ernel(sigma, origin) rbf = @()) e)p(,sigma*norm() , origin)); % fun"tion p = "reate-lotter()range) figure; p = @(%) plot(g"a, )range, %()range));
#ame a$is is reused "% ever p( ) call&

Io0 0e can create +unctions at 0ill Q and call or pass them to other +unctions5

Dynamic Programming 0ith OOP


%

Some languages allo0 dynamic class de+initions. li,e anonymous +unctions >atla$ does not 0! current synta*
% >ay $e a$le to hac, it 0ith old synta*. using class6: +unction - $ut not recommended % )an add dynamic props though. as noted

Inter+aces
%

1e can still dynamically code $y 0riting +unctions 0hich ta,e o$"ects as an argument +unction out M doSomething6o$"ect:
o$"ect.computeSomething6:...

Inter+aces
%

Inter+ace typically a parent o$"ect 0hich de+ines properties and methods re4uired +or some +unction!process etc
% Su$classes may modi+y methods % !bstra"t method attri$ute all su$classes o+ an o$"ect must reimplement that method
% Allo0s <empty< classes 0hich "ust de+ine a set o+ re4uired methods % In this pure +orm. class is called an <Inter+ace<
%

Su$methods said to implement inter+ace R

Inter+aces
%

Io0. di++erent classes are interchangea$le


% Ie. let<s have an inter+ace +or supervised machine learning
% Su$class N is S?> S Supervised;earner % Su$class 2 is TII S Supervised;earner % 'oth must implement o$".train6la$els. data:. o$".test6data:. $ut do so in di++erent 0ays5 % )an pass instance o+ either to a +unction to customiJe ho0 it learns!classi+ies data

Inter+aces
%

>ore general e*ample


% % % % >y(*periments 0! a$stract analyJe6:. plot6: (*pN S >y(*periments ?is(*periment S >y(*periments Aud(*periment S >y(*periments

% +unction $atchAnalyJe6dir:
% +or every +ile in dir
% % %

+ M load6+ile:O +.o$".analyJe6: +.o$".plot6:....

'his "orks regardless of "hat t pe of e$periment "e(re anal )ing&

Duc, &yping
%

In some languages 6ie Hava: an inter+ace must $e e*plicitly de+ined >atla$ is a Duc, &yped language
% I+ it 4uac,s li,e a duc,. let<s call it a duc,5 % 1e do not need a$stract methods or to de+ine a superclass % If an object has the methods, you can use it as if it had that interface

Duc, &yping
%

Pass in any o$"ect 0! the right methods to a +unction that calls those methods Io0 your +unction is dynamically controlled $y the $ehavior o+ that o$"ect 1e can de+ine e*tremely general +unctions 0hich re4uire an o$"ect to de+ine it<s $ehavior
(NB: there is no need to t pecast)

(rror )hec,ing
try
)ode...

catch e*ception
De+ensive $loc,... use e*ception.stac,. e*ception.identi+ier. etc

end
% %

See also. error6<msgID<:. rethro0. lasterr. etc Ie can deli$erately thro0 errors instead o+ returning $ad outputs. and have code handle it correctly

(rror )hec,ing

*ur e$pected error! "hich "e handle (or can check for specific +atlab errors! i.e. (+,'-,B:.ndefined/unction( or (+,'-,B:innerdim() , (real( error! "hich here "e treat as such

3ecursion
%

Iot really dynamic programming. $ut use+ul... Instead o+ 0riting a loop. some +unctions should call themselves recursively

3ecursion
%

(*ample
% +unction + M +actorial6I:
+ M prod62 I:O

% +unction + M +actorial6I:
+ M NO +or i M 2 I
+ M + A iO
NB: due to 0I'! 1st t"o are actuall faster ;)

% +unction + M +actorial6I:
i+ I S 2
+ M NO

else
+ M IA+actorial6I#N:O

3ecursion
%

OptimiJe
+unction F*ma*. yma*G M ma*imiJe6*lo. *hi. y. iters:
* M linspace6*lo. *hi:O Fyma*. yma*indG M ma*6y6*::O *ma* M *6yma*ind:O i+ iters U N
F*ma*. yma*G M ma*imiJe6*ma*#6*ma*#*lo:!2. Q *ma*96*hi#*ma*:!2. y. iters#N:O

end

3ecursion
%

+unction change6o$". ne0val:


o$".val M ne0valO +or c M N o$".num)hildren
o$".child6c:.change6ne0val:O
obj

end

obj

obj

obj

obj

obj

6I' here. should $e handle o$"ects5:


obj

3ecursion
%

Is elegant +rom a design point o+ vie0 'ut. due to HI&. it may not $e optimal Al0ays ensure there<s an end condition
% &hat is. $e0are in+inite loops5

1ednesday
%

(*ternal inter+acing Application control

Das könnte Ihnen auch gefallen