Download - Funciones

Transcript
  • 25/6/2015 Funciones

    http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html 1/10

    Clculosaritmticos

    Variablesescalares

    Vectoresymatrices

    Entrada/salida

    Grficosbidimensionales

    Funciones

    Sentenciascondicionales

    Sentenciasiterativas

    Ejemplos

    Inicio MATLAB Bsico

    FuncionesEstamosacostumbradosatrabajarconfuncionesdeltipoy=f(x)dondef(x)esunaexpresinmatemticaentrminosdelavariablex.Secalculaunvalordey(salida)cuandoseproporcionaunvalordex(entrada)enlaexpresin.MATLABdefinemuchasfuncionescomosin(x),sqrt(x),etc.

    Podemosdefinirnuestraspropiasfuncionesguardarlasenunficheroyusarlasdeunmodosemejantealasfuncionespredefinidas.Enmuchoscasoslasfuncionessonloscomponentesbsicosdentrodeunprogramadeordenador.Habitualmente,unprogramasesubdivideentareasycadaunadeellasesllevadaacaboporunafuncin,aestaformaderesolverlosproblemassedenominaprogramacinestructurada.

    Laprincipalventajadelasfuncioneseslaposibilidaddereutilizarelcdigoenotrosprogramasdistintosalcualfuerondefinidas.

    Laentradaylasalidapuedeserunaovariasvariables,cadaunadeellaspuedeserunescalar,unvectorounamatrizdecualquiertamao.

    Definicindeunafuncin

    LasfuncionessecreandelmismomodoqueunscriptseleccionadoenelmenFile/New/Functionyseguardanenunficheroquetieneelmismonombrequelafuncinyextensin.m

    Laprimeralneaeneleditoresladefinicindelafuncinquecomienzaconlapalabraclavefunction

    functionvariables_salida=nombre_funcion(variables_entrada)sentenciasend

    nombre_funcion,eselnombresignificativoqueseleasignaalafuncinycoincideconelnombredelficherodeextensin.menelqueseguardaelcdigodedichafuncin.Lasreglasparanombrarunfuncinsonlasmismasqueparalasvariables,losnombresnodebendeincluirespacios,nisepuedenutilizarplabrasreservadasporMATLAB.

    variables_entrada,eselconjuntodeparmetrosqueselepasaalafuncin.Losnombresdelasvariablesvanentreparntesisyseparadasporcoma.

    variabales_salida,eselvaloroconjuntodevaloresdelasvariablesdevueltosporlafuncin.Lasvariablesdesalidavandespusdelapalabrareservadafunctionentrecorchetescuadradosyseparadosporcomassihayvarios.

    sentencias,lneasdecdigoquetomandolosvaloresdelosparmetrosdeentradacalculanmedianteexpresioneslosvaloresquedevuelvelafuncin.

    end,marcaelfinaldelafuncinesopcional(salvoenlasfuncionesanidadas)peroesconvenienteacostumbrarseaponerloalfinalizarlafuncin.

    Opcionalmente,enlasegundalneaseponeuncomentario,enelqueseexplicalatareaquerealizalafuncin.A

  • 25/6/2015 Funciones

    http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html 2/10

    continuacin,unaexplicacindetalladasobrelasvariablesdeentradaydesalida

    Cuandounafuncinnodevuelveningnvalor,sedefine

    functionnombre_funcion(variables_entrada)

    Cuandounafuncionnoprecisadevariablesdeentradasedefine

    functionvariables_salida=nombre_funcion

    Cuandounafuncindevuelveunasoloresultadoysepuedeescribir,dedosmaneras

    function[y]=nombre_funcion(a,b,c)functiony=nombre_funcion(a,b,c)

    Engeneral,definiremosunafuncindelsiguientemodo:

    function[y1,y2]=nombre_funcion(a,b,c)

    contresargumentosa,bycvariablesdeentradayquedevuelvedosresultadosenlasvariablesy1ey2.

    Unafuncinsellamadelmismomodoquelasfuncionespredefinidas.Lasfuncionessepuedenllamardesdelaventanadecomandos,desdeunficheroscriptodesdeotrafuncin.

    Todaslasvariablesenunafuncinsonlocalesadichafuncin,incluyendolasdeentradaylasdesalida.

    Vamosaverunoscuantosejemplosenestapginadefunciones.

    Ejemplos

    Sumadedosnmeros

    Empezaremosporunafuncinsumaquerealizalasiguientetarea,sumadedosnmerosxeyydevuelvelasumaz=x+y

    Definicindelafuncin

    function[z]=suma(x,y)%Estafuncinsumadosnmerosxey%ydevuelveelresultadodelasumaenz

    z=x+y%efectalasumaend

    Alafuncinsumaselepasandosdatosenlasvariablesxey,ydevuelveelresultadoenlavariablez.

    Lafuncinseguardaenunfichero

    Elficheroqueguardalafuncintieneelmismonombrequelafuncin,talcomovemosalseleccionarenelEditorFile/Saveas...

    Llamadaalafuncin

    Lallamadaalafuncinsepuedehacerdesdelaventanadecomandos

    >>suma(2,3)ans=5

  • 25/6/2015 Funciones

    http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html 3/10

    Sepuedehacerdesdeunscript

    a=3b=2res=suma(a,b)disp(res)

    Enlallamadaalafuncinsumasuparmetroxadquiereelvalordelprimerargumentoa,elsegundoparmetroytomaelvalordelargumentob,seefectalasumaenelcuerpodelafuncin,seguardaelresultadoenlavariablezquedevuelvelafuncin.Elvalorqueguardazsecopiaenlavariableres.Lasvariablesx,yyzsonlocalesalafuncinyportanto,noaparecenenlaventanaWorkspace,nosepuedeaccederaellasdesdelaventanadecomandos.

    Comohemosvistohayquepasarlosvaloresqueguardanlasvariablesaybalafuncinsumaporqueunafuncinnotieneaccesoalasvariablesdeclaradasenunscriptoenlaventanadecomandos.

    Sistemadeayuda

    Enlaventanadecomandosescribimos

    >>helpsumaEstafuncinsumadosnmerosxeyydevuelveelresultadodelasumaenz

    aparecenloscomentariosquehemospuestoalprincipiodelafuncin,peronoaparecenelcomentario"efectalasuma",quehemospuestoenlaterceralnea.

    Movimientodecadadeloscuerpos

    Lasecuacionesquedescribenelmovimientodecadadeloscuerposson:

    Dondev0yx0eslavelocidadinicialylaposicininicial,respectivamente.Vamosacrearunafuncindenominadacaida_librequeadmitacomoparmetroseltiempotydevuelvalaposicinxyvelocidadvdeunmvilqueselanzadesde200mdealturaconvelocidadde40m/s.Laaceleracinconstantedelagravedadg=10m/s2

    v=4010tx=200+40t5t2

    SeleccionamosFile/New/Functionparaabrireleditordefunciones.

    1. Definimoslafuncin:

    Lapalabraclavefunction

    Lasvariablesdesalidaentrecorchetescuadrados[x,v]

    Eloperadorasignacin=

    Elnombredelafuncin,caida_libre

    Entreparntesislavariabledeentrada(t)

    2. Escribimoselcuerpodelafuncincondossentenciasquecalculanlavelocidadvylaposicinxcuandoseproporcionaeldatodeltiempot

    3. Finalizamosconend.

    4. SeleccionamosFile/SaveAs..paraguardarlafuncinenelficherocaida_libre.mconelmismonombrequelafuncin.

    function[x,v]=caida_libre(t)v=4010*tx=200+40*t5*t^2

    2 #02

    4 0 #4

    2

    0

  • 25/6/2015 Funciones

    http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html 4/10

    end

    Enlaventanadecomandossellamaaestafuncincaida_libre,pasndoleuntiempot=2s,delsiguientemodo

    >>[pos,vel]=caida_libre(2)pos=240vel=20

    Quecalculaymuestra,lavelocidadv=20m/sylaposicinx=240menelinstantet=2s

    Enlallamadaalafuncincaida_libreelparmetrotadquiereelvalorde2,enlasdossentenciassecalculalavelocidadyposicinyseguardanenlasvariableslocalesvyx.Lafuncindevuelveestosdosvaloresquesecopianenlasvariablesvelyposdelaventanadecomandos.Enlaventanadecomandosnotenemosaccesoalasvariablest,vyxporserlocalesalafuncincaida_libreydesaparecencuandoterminadeejecutarse,perositenemosaccesoalasvariablesvelyposqueguardanlosresultadosdelclculorealizadoenelcuerpodelafuncin.

    Siintentamosaccederalavariablexotobtendremosunmensajedeerror

    >>x,t???Undefinedfunctionorvariable'x'.

    Siqueremosquelafuncincaida_librecalculelaposicinyvelocidaddelmvilparaunasecuencia(vector)detiempost,tendremosquemodificarladefinicindedichafuncin

    function[x,v]=caida_libre(t)v=4010*tx=200+40*t5*t.^2end

    Enlaventanadecomandossellamaaestafuncincaida_libre,pasndolelostiempost=[0,2,4,6,8,10]obien,t=0:2:10,delsiguientemodo

    >>t=0:2:10>>[pos,vel]=caida_libre(t)pos=200260280260200100vel=40200204060

    Mediaydesviacinestndardeunconjuntodedatos

    Ladefinicindemediaydesviacinestndareslasiguiente

    Creamosunafuncindenominadaestadisticaalaqueselepasaunvectorxdedatosydevuelvelamediamedyladesviacin,des,ylaguardamosenunficheroconelmismonombrequelafuncin

    function[med,des]=estadistica(x)n=length(x)med=sum(x)/ndes=sqrt(sum((xmed).^2/(n1)))end

    Lafuncinsumcalculalasumadeloselementosdeunvectorx

    Lafuncinlength,calculaelnmerodeelementosdelvectorx.

    Calcularlamediayladesviacinestndardelaalturadelos10alumnosdeunaclase:1.65,1.82,1.72,1.75,1.73,1.85,1.90,1.74,1.76,1.77.

    Escribimoselnombredelafuncinestadisticaenlaventanadecomandosylepasamoselvectordedatos

    >>[media,desviacion]=estadistica([1.651.821.721.751.731.851.901.741.761.77])media=1.7690desviacion=0.0713

    MATLABdisponededosfuncionesquecalculanlamediameanyladesviacinestndar,std.

    >>x=[1.651.821.721.751.731.851.901.741.761.77]>>mean(x)ans=1.7690>>std(x)ans=0.0713

    Funcionesdefinidasenelmismofichero

    4 U

    *

    4

    %

    *

    *

    44

    %

    *

    +

    '

    *

    *

    *

  • 25/6/2015 Funciones

    http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html 5/10

    Unficherofuncinpuedecontenermsdeunafuncin.Lasfuncionessedefinenunaacontinuacindelaotra.Laprimerafuncineslaprimariaytieneelmismonombrequeelfichero,lasotrasfuncionessonsecundariasysedenominansubfuncionesypuedenestarencualquierordendentrodelfichero.Solamentesepuedellamaralafuncinprimariaenlaventanadecomandosoporotrasfunciones.Cadafuncintienesuspropiasvariablesquesonlocalesalafuncin,nosepuedeaccederalasvariablesdeunasubfuncindesdelafuncinprimariaodesdeotrasubfuncin.Nosepuedeaccederalasvariablesdelafuncinprimariadesdeunasubfuncin.

    Lassubfuncionespermitenorganizartareasgrandesenotrasmspequeas.

    Msadelanteveremoslautilidaddeestasfuncionescuandolosprogramasseanmslargosycomplejos,demomentovamosaverunejemploquenospermitavislumbrarcomosedefinenyllamanlassubfunciones.

    Ecuacindesegundogradoax2+bx+c=0Lasracessonx1yx2ytienenlassiguientespropiedades:

    Vamosacrearunafuncinquenospermitacomprobarlaspropiedadesdelasracesdeunaecuacindesegundogrado,ydossubfunciones,laprimeracalculalarazx1ylasegundalarazx2.

    Eneleditordefuncionescreamoslafuncincomprobar_raices,alaqueselepasaloscoeficientesa,bycdelaecuacindesegundogradoydevuelveloscocientesb/ayc/adelasumayproductodelasdosracesx1yx2.Guardamoselcdigodelafuncinprimariacomprobar_raicesydelassubfuncionescalcula_raiz1ycalcula_raiz2enelficherocomprobar_raices.m

    function[r1,r2]=comprobar_raices(a,b,c)x1=calcula_raiz1(a,b,c)x2=calcula_raiz2(a,b,c)r1=x1+x2r2=x1*x2end

    functionraiz=calcula_raiz1(a,b,c)raiz=(b+sqrt(b*b4*a*c))/(2*a)end

    functionraiz=calcula_raiz2(a,b,c)raiz=(bsqrt(b*b4*a*c))/(2*a)end

    Paracomprobarlasracesdelaecuacindesegundogradox2x6=0,llamamosalafuncincomprobar_raicesylepasamosloscoeficientes1,1,6ynosdevolverb/a=1yc/a=6

    >>[b_a,c_a]=comprobar_raices(1,1,6)b_a=1c_a=6

    Funcionesanidadas

    Unafuncinanidadaesunafuncindefinidadentrodeotrafuncin.Lasfuncinprimariaylasanidadasdebenobligatoriamenteterminarconend

    Lasfuncionesanidadastieneaccesoalasvariablesdelafuncinprimariaylafuncinprimariatieneaccesoalasvariablesdefinidasporlafuncinanidada.

    Unafuncinanidadapuedecontenerotrayassucesivamente,peroesteprocesopuedellevaraconfusin.Existenreglasparallamaraunafuncinanidadadentrodeotraperonotieneporelmomentointersparaellector.

    Eneleditordefuncionescreamoslafuncincomprobar_raices1,alaqueselepasaloscoeficientesa,bycdelaecuacindesegundogradoydevuelveloscocientesb/ayc/adelasumayproductodelasdosracesx1yx2.Guardamoselcdigodelafuncinprimariacomprobar_raices1ydelassubfuncionescalcula_raiz1ycalcula_raiz2enelficherocomprobar_raices1.m

    function[r1,r2]=comprobar_raices1(a,b,c)dis=sqrt(b*b4*a*c)calcula_raiz1calcula_raiz2r1=x1+x2r2=x1*x2functioncalcula_raiz1x1=(b+dis)/(2*a)endfunctioncalcula_raiz2x1=(bdis)/(2*a)

    4

    4

    4

    4

    4

    4

  • 25/6/2015 Funciones

    http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html 6/10

    endend

    Vemosquelasfuncionesanidadascalcula_raiz1ycalcula_raiz2tienenaccesoalosparmetrosa,bycdelafuncinprimaria,quesonvariableslocalesalafuncincomprobar_raicesytambin,alavariablelocaldis,queguardaeldiscriminantedelaecuacindesegundogrado.Porotraparte,lafuncinprimariatieneaccesoalasvariablesx1yx2declaradasencadaunadelasfuncionesanidadas.

    Estasfuncionesanidadasnoprecisandevariablesdeentradaynodevuelvennada.

    Paracomprobarlasracesdelaecuacindesegundogradox2x6=0,llamamosalafuncincomprobar_raices1ylepasamosloscoeficientes1,1,6ynosdevolverb/a=1yc/a=6

    >>[b_a,c_a]=comprobar_raices(1,1,6)b_a=1c_a=6

    Comoejercicioseporponeallectorcrearlafuncinestadistica_1,quedevuelvalamediayladesviacinestndar,cuandoselepasaunvectordedatos.Elvalormediosecalcularmediantelafuncinanidadamediayladesviacinestndarmediantelafuncinanidadadesviacion.

    Solucin

    Funcionesannimas

    Lasfuncionesannimasnospermitendefinirunafuncinsimplesinnecesidaddecrearlayguardarlaenunfichero.m.Sepuedendefinirenlaventanadecomandos,enunficheroscriptodentrodeotrafuncin,conlasiguientesintaxis:

    variable=@(lista_argumentos)expresion

    expresionconsisteenunanicayvlidaexpresin,puedetenerunaomsvariablesdeentradaqueseespecificanenlalistadeargumentosseparadasporcomas.Puedeincluirvariablesquesehandefinidopreviamente

    Lasfuncionessepuedenasignaravariablesyestasvariablessepuedenpasaraotrasfuncionescomosepasanescalaresovectores.Msadelanteveremoscmosellamaaunafuncindentrodeotrafuncinqueselepasaenunodesusparmetros.

    Comparamosladefinicindeunafuncinfuncqueseguardaenunficherofunc.mysuequivalenteannima

    functiony=func(x)y=cos(x)xend

    Llamadaalafuncin

    >>z=func(0.5)z=0.3776

    Suequivalenteannimaseescribeenlaventanadecomandossinnecesidaddeguardarlaenunficheroysellamadelmismomodoquecualquierotrafuncin

    >>f=@(x)cos(x)x>>z=f(0.5)z=0.3776

    fguardaunvalorasociadoaunafuncinquedenominaremosmanejador(functionhandle)

    EnlaventanaWorkspace,vemosqueapreceunavariablefdedistintotipoqueguardalareferenciaalafuncinannima.

    Teoremadelcoseno

  • 25/6/2015 Funciones

    http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html 7/10

    Podemoscalcularelladocdeltringulosiconocemoslosladosaybyelngulocomprendido,medianteelteoremadelcoseno

    >>c=@(a,b,gamma)sqrt(a^2+b^22*a*b*cosd(gamma))>>lado=c(3,4,30)lado=2.0531

    Llamadaaunafuncindesdeotrafuncin

    Existenmuchasituacionesenlasqueunafuncinf1utilizaotrafuncinf2.Porejemplo,MATLABtieneunafuncinfzeroqueseutilizaparacalcularlasracesdeunaecuacinf(x)=0.Lafuncinfselepasaafzerocuandosellamaparaencontrarlasracesdef(x).Hayvariasformasdepasarunafuncinfaotrafuncinparasuuso.

    Yahemosvistoelsignificadodemanejadorparaunafuncinannima,unvalorqueguardaunavariablefocyqueestasociadoaunafuncin.

    Sidefinimosunafuncindeformaexplcitaenunficheroporejemplo,lafuncinfunc,obtenemoselmanejadoranteponiendoelcarcter@alnombredelafuncin

    Laderivadadeunafuncin

    Vamosahora,avercomoselepasaunafuncinaotrafuncinenunodesusparmetros.

    Laderivadaprimerady/dx,deunafunciny=f(x)enunpuntox0,sepuedecalcularaproximadamentemediantelafrmula

    dondehununnmeropequeoencomparacinconx0.Escribirunafuncindenominadaderivada,cuyosparmetrosseanlafuncinf,ylaabscisax0ydevuelvaelvalordeladerivadadelafuncinf(x)enx0.Tomarh=105.Utilizarlafuncinderivadaparacalcularlasderivadasdelassiguientesfunciones,comparandoconlosresultadosexactos.

    functionyp=derivada(f,x0)h=1e5yp=(f(x02*h)8*f(x0h)+8*f(x0+h)f(x0+2*h))/(12*h)end

    Enlaventanadecomandos,definimoslafuncin(annima)quequeremosderivaryllamamosalafuncinderivada.

    >>f1=@(x)x^2*exp(x)>>derivada(f1,0.25)ans=0.7223

    Podemoscalculartambinladerivadasegundadeunafuncinenunpuntodelsiguientemodo

    >>f1=@(x)x^36*x^2+3>>derivada(f1,2)ans=12.0000>>f2=@(x)derivada(f1,x)>>derivada(f2,2)ans=9.8686e007

    Podemosrepresentarlafuncin(encolorazul),suderivadaprimera(encolorrojo)ysuderivadasegunda(encolorverde)

    DPT E

    5

    4

    " $ " $ " $ " $4

    4

    4

    4

    $

    5 4

    4

    4

    5 4

    !

    4

    4

  • 25/6/2015 Funciones

    http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html 8/10

    x=3:0.05:7f1=@(x)x.^36*x.^2+3y=f1(x)%funcinyp=derivada(f1,x)%derivadaprimeraf2=@(x)derivada(f1,x)ypp=derivada(f2,x)%derivadasegundaplot(x,y,'b',x,yp,'r',x,ypp,'g')xlabel('x')ylabel('y')title('funcinyderivadas')ylim([50,50])gridon

    Representacingrficadeunafuncin

    Definimosunafuncindenominadagraficaylepasamoselmanejadordelafuncincuyagrficaqueremosrepresentarenundeterminadointervaloa,b.Lafuncinnodevuelveningnvalor.

    functiongrafica(f,a,b)x=linspace(a,b,50)y=f(x)plot(x,y,'r')gridonxlabel('x')ylabel('y')title('grficadeunafuncin')end

    Enlaventanadecomandocreamosunafuncinannimacuyomanejadoresfuncyllamamosalafuncingrafica,pasndoleelmanejador,elintervalo(a,b)enelcualqueremosrepresentarlafuncin

    >>func=@(x)xcos(x)>>grafica(func,0,pi/2)

    Aparecelaventanagrfica

    5 4

    4

    4

    5

    4

    4

    4

    5

    4

  • 25/6/2015 Funciones

    http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html 9/10

    Definimosunafuncinsimilarfunc1ylaguardamosenunficherofunc1.m

    functiony=func1(x)y=cos(x)xend

    Enlaventanadecomandosllamamosalafuncingrafica,pasndoleelmanejadordelafuncinfunc1,@func1yelintervalo(a,b)enelcualqueremosrepresentarlafuncin.

    >>grafica(@func1,0,pi/2)

    Seobtienelamismagrfica

    Lafuncinfplot

    Lafuncinfplotdibujaunagrficasiselepasalafuncinfenelprimerparmetroyelintervalo[xmin,xmax]enelsegundo

    >>f=@(x)x5*(1exp(x))>>fplot(f,[06])

    Alternativamente,fplotdevuelveunatabladevalores[x,y]quepuedenserutilizadasporlafuncinplot(x,y)paradibujargrfica,superponerunarejilla(grid),ponerttulo(title)yetiquetas(xlabel,ylabel),etc.talcomosemuestraenelsiguientescript

    f=@(x)x5*(1exp(x))[x,y]=fplot(f,[06])plot(x,y)gridonxlabel('x')ylabel('y')title('grficadeunafuncin')

    Haydiferenciassignificativasentreplotyfplot.Laprimeraevalalafuncinparavaloresdexigualmenteespaciados.Comovemoshayqueespecificarelintervaloxoelnmerodepuntos,mientrasqueenlasegundanoesnecesarioespecificarlo.fplotevalainternamentelafuncinmsfrecuentementeenaquellasregionesenlasquecambiarpidamente.Enelsiguienteejemplosedibujalasiguientefuncinenelintervalo[0.010.1]

    >>x=0.01:0.001:0.1>>y=sin(1./x)>>plot(x,y)

    5 TJO

    4

  • 25/6/2015 Funciones

    http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html 10/10

    Tomandox=0.001,seobtieneunafiguraconbajaresolucin.Sinembargo,

    >>f=@(x)sin(1/x)>>fplot(f,[0.010.1])

    Obtenemosunafiguraconmejorresolucinsintenerqueprobardistintosvaloresdexodelnmerodepuntos.

    EnergasRenovablesEUITIdeEibar


Top Related