您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 咨询培训 > matlab面向对象编程
Matlab–Object-OrientedProgrammingPaulSchrimpfJanuary14,2009PaulSchrimpf()Matlab–Object-OrientedProgrammingJanuary14,20091/15ProgrammingParadigmsProceduralIDothis,thendothat...IMostofwhatwehaveseensofarFunctionalIOperateonfunctionsIe.g.LISP,Scheme,HaskellObject-orientedIFocusoncodereuseandreliabilityIAnobjectisdataandmethodstomanipulateitITakecomponentsthatareusedrepeatedlyandsharecharacteristicsandimplementasaclassothers...PaulSchrimpf()Matlab–Object-OrientedProgrammingJanuary14,20092/15Object-orientedLingoAclassisadatastructureandmethodsthatactonitAnobjectisaspecificinstanceofaclassIe.g.adoubleisaclasswithmethodssuchas+,−,*,exp()Encapsulationreferstothefactthatauserofaclassshouldonlyneedtoknowwhatamethoddoes,nothowitisimplementedIe.g.Donotneedtoworryabouthowdoublesarestoredorhow+worksAsubclassisaspecializedversionofaparentclass.Subclassesinheritdataandmethodsfromtheirparent.Ie.g.doubleandintmightbesubclassesofagenericnumericclassPaulSchrimpf()Matlab–Object-OrientedProgrammingJanuary14,20093/15MoreOOLingoAbstractionmeanswritingcodethatoperatesatthehighestlevelclasspossibleIe.g.mostarithmeticoperationsworkwithanynumericclassAnabstractionbarrierreferstothefactthataslongaswedonotchangeagivenclass,changesaboveitshouldnotrequireanychangesbelowit,andchangesbelowitshouldnotrequireanychangesaboveIe.g.doingadifferentsequenceofarithmeticoperationsdoesnotrequirechangingintordouble,andchangingtheimplementationofintordoubleshouldnotrequirechangingasequenceofarithmeticoperationsPaulSchrimpf()Matlab–Object-OrientedProgrammingJanuary14,20094/15Example:functionseriesclassOften,wewanttoapproximateanunknownfunctionbyaseriesoffunctions(asinthedynamicprogrammingexamplecoveredearlier)Manytypesofseries:orthogonalpolynomials,Fourierseries,splines,etcForanyseries,weshouldbeabletoevaluateatapoint,add,subtract,multiply,differentiate,integrate,andconstructtogiveabestapproximationtoafunctionThissuggestswritingagenericfunctionseriesparentclasswiththesemethods,andthenwritingspecifictypesofseriesassubclassesPaulSchrimpf()Matlab–Object-OrientedProgrammingJanuary14,20095/15Example:functionseriesclassThiscodeshouldbeinafilenamedseriesFn.minadirectorynamed@seriesFn(Inolderversionsofmatlab(before7.5?)thewayoforganizingclassesandmethodswasdifferent.)1classdefseriesFn2properties%thedata3order%orderofseries4coeff%coefficients5dim%dimension6powers%powersthatgowithcoefficients7end8methods(Abstract=true)%thesearemethodsthatareonly9%implementedinchildclasses10y=sval(f,x)%evaluateseries11d=derivative(f)%createderivative12F=integral(f,lo,hi)%evaluateintegral13c=mtimes(a,b)%multiplication14s=approxFn(s,fn,tol)%makesapproximatefn15endPaulSchrimpf()Matlab–Object-OrientedProgrammingJanuary14,20096/15Example:functionseriesclass–constructorConstructorscreateanewobjectChildclassescanredefinetheirconstructors(oranyothermethod)iftheydonot,theyinherittheirparent’sconstructorThefollowingcodewouldgoinsideamethodsblockinsideclassdefseriesFn1functionf=seriesFn(order,coeff,tol,dim)2f.order=order;3f.dim=dim;4f.powers=intVecsLessThan(f.order,f.dim)';5if(length(coeff)size(f.powers,1))6warning('order=%d,butonly%dcoeff\n',order,...7length(coeff));8end9f.coeff=coeff;10f.coeff(end+1:size(f.powers,2))=0;11f.coeff=reshape(f.coeff,1,numel(f.coeff));12endPaulSchrimpf()Matlab–Object-OrientedProgrammingJanuary14,20097/15Example:functionseriesclass–operatoroverloadingClassescanredefinetheirownversionsofoperators(+,−,*,(),:,etc)ThefollowingcodewouldgoinsideamethodsblockinsideclassdefseriesFnThisversionofpluswillbecalledwheneversomeonewritesa+bandeitheraorbisaseriesFnPaulSchrimpf()Matlab–Object-OrientedProgrammingJanuary14,20098/151functionc=plus(a,b)2if¬isa(a,'seriesFn')||¬isa(b,'seriesFn')3error('BothargumentsmustbeseriesFnobjects');4end5order=max(a.order,b.order);6c=seriesFn(order,zeros(1,order+1));7if(a.orderb.order)8c.coeff=a.coeff;9c.coeff(1:length(b.coeff))=c.coeff(1:length(b.coeff))+b.coeff;10elseif(b.ordera.order)11c.coeff=b.coeff;12c.coeff(1:length(a.coeff))=c.coeff(1:length(a.coeff))+a.coeff;13else14c.coeff=a.coeff+b.coeff;15end16end%functionplusPaulSchrimpf()Matlab–Object-OrientedProgrammingJanuary14,20099/15Example:functionseriesclass–subclass1classdefpolynomialseriesFn2methods3functionc=mtimes(a,b)4c=polynomial(a.order+b.order,...5conv(a.coeff(end:−1:1),b.coeff(end:−1:1)));6c.coeff=c.coeff(end:−1:1);7end8functiony=sval(f,x)9y=polyval(f.coeff(end:−1:1),x);10end11functiondf=derivative(f)12df=polynomial(f.order−1,f.coeff(2:end).*(1:f.order));13end14%...moremethodsomitted...15end16endPaulSchrimpf()Matlab–Object-OrientedProgrammingJanuary14,200910/15ForwardAutomaticDifferentiationForwardautomaticdifferentiationcomputesderivativesbyapplyingthechainruletoeachoperationinacomputationIe.g.forx=2;y=x2;z=log(y);forwardADwould1x=2,∂x=12y=x2=4,∂y=2x∂x=43z=log(y),∂z=1y∂y=2Wecanwriteaclassthatstoresthevalueofanumberanditsderivative,overloadeveryarithmeticoperatortoworkwiththatclass,andthenbyusingthisclassinplaceofdoubles,wewillbeabletocomputethederivativeofanyfunctionwithoutchangingourcodeP
本文标题:matlab面向对象编程
链接地址:https://www.777doc.com/doc-1463620 .html