Inicio
Funciones
MATLAB
Clculosaritmticos
Variablesescalares
Vectoresymatrices
Entrada/salida
Bsico
Funciones
Estamosacostumbradosatrabajarconfuncionesdeltipoy=f(x)dondef(x)esunaexpresinmatemticaen
trminosdelavariablex.Secalculaunvalordey(salida)cuandoseproporcionaunvalordex(entrada)enla
expresin.MATLABdefinemuchasfuncionescomosin(x),sqrt(x),etc.
Funciones
Podemosdefinirnuestraspropiasfuncionesguardarlasenunficheroyusarlasdeunmodosemejantealas
funcionespredefinidas.Enmuchoscasoslasfuncionessonloscomponentesbsicosdentrodeunprogramade
ordenador.Habitualmente,unprogramasesubdivideentareasycadaunadeellasesllevadaacaboporuna
funcin,aestaformaderesolverlosproblemassedenominaprogramacinestructurada.
Sentencias
condicionales
Laprincipalventajadelasfuncioneseslaposibilidaddereutilizarelcdigoenotrosprogramasdistintosalcual
fuerondefinidas.
Sentenciasiterativas
Laentradaylasalidapuedeserunaovariasvariables,cadaunadeellaspuedeserunescalar,unvectorouna
matrizdecualquiertamao.
Grficos
bidimensionales
Ejemplos
Definicindeunafuncin
LasfuncionessecreandelmismomodoqueunscriptseleccionadoenelmenFile/New/Functionyseguardan
enunficheroquetieneelmismonombrequelafuncinyextensin.m
Laprimeralneaeneleditoresladefinicindelafuncinquecomienzaconlapalabraclavefunction
functionvariables_salida=nombre_funcion(variables_entrada)
sentencias
end
nombre_funcion,eselnombresignificativoqueseleasignaalafuncinycoincideconelnombredelfichero
deextensin.menelqueseguardaelcdigodedichafuncin.Lasreglasparanombrarunfuncinsonlas
mismasqueparalasvariables,losnombresnodebendeincluirespacios,nisepuedenutilizarplabras
reservadasporMATLAB.
variables_entrada,eselconjuntodeparmetrosqueselepasaalafuncin.Losnombresdelasvariablesvan
entreparntesisyseparadasporcoma.
variabales_salida,eselvaloroconjuntodevaloresdelasvariablesdevueltosporlafuncin.Lasvariablesde
salidavandespusdelapalabrareservadafunctionentrecorchetescuadradosyseparadosporcomassihay
varios.
sentencias,lneasdecdigoquetomandolosvaloresdelosparmetrosdeentradacalculanmediante
expresioneslosvaloresquedevuelvelafuncin.
end,marcaelfinaldelafuncinesopcional(salvoenlasfuncionesanidadas)peroesconveniente
acostumbrarseaponerloalfinalizarlafuncin.
Opcionalmente,enlasegundalneaseponeuncomentario,enelqueseexplicalatareaquerealizalafuncin.A
http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html
1/10
25/6/2015
Funciones
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.Lasfuncionessepuedenllamardesdela
ventanadecomandos,desdeunficheroscriptodesdeotrafuncin.
Todaslasvariablesenunafuncinsonlocalesadichafuncin,incluyendolasdeentradaylasdesalida.
Vamosaverunoscuantosejemplosenestapginadefunciones.
Ejemplos
Sumadedosnmeros
Empezaremosporunafuncinsumaquerealizalasiguientetarea,sumadedosnmerosxeyydevuelvelasuma
z=x+y
Definicindelafuncin
function[z]=suma(x,y)
%Estafuncinsumadosnmerosxey
%ydevuelveelresultadodelasumaenz
z=x+y%efectalasuma
end
Alafuncinsumaselepasandosdatosenlasvariablesxey,ydevuelveelresultadoenlavariablez.
Lafuncinseguardaenunfichero
Elficheroqueguardalafuncintieneelmismonombrequelafuncin,talcomovemosalseleccionarenel
EditorFile/Saveas...
Llamadaalafuncin
Lallamadaalafuncinsepuedehacerdesdelaventanadecomandos
>>suma(2,3)
ans=5
http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html
2/10
25/6/2015
Funciones
Sepuedehacerdesdeunscript
a=3
b=2
res=suma(a,b)
disp(res)
Enlallamadaalafuncinsumasuparmetroxadquiereelvalordelprimerargumentoa,elsegundoparmetroy
tomaelvalordelargumentob,seefectalasumaenelcuerpodelafuncin,seguardaelresultadoenlavariable
zquedevuelvelafuncin.Elvalorqueguardazsecopiaenlavariableres.Lasvariablesx,yyzsonlocalesala
funcinyportanto,noaparecenenlaventanaWorkspace,nosepuedeaccederaellasdesdelaventanade
comandos.
Comohemosvistohayquepasarlosvaloresqueguardanlasvariablesaybalafuncinsumaporqueuna
funcinnotieneaccesoalasvariablesdeclaradasenunscriptoenlaventanadecomandos.
Sistemadeayuda
Enlaventanadecomandosescribimos
>>helpsuma
Estafuncinsumadosnmerosxey
ydevuelveelresultadodelasumaenz
aparecenloscomentariosquehemospuestoalprincipiodelafuncin,peronoaparecenelcomentario"efectala
suma",quehemospuestoenlaterceralnea.
Movimientodecadadeloscuerpos
Lasecuacionesquedescribenelmovimientodecadadeloscuerposson:
v = v0 + gt
x = x0 + v0 t +
1
2
gt
Dondev0yx0eslavelocidadinicialylaposicininicial,respectivamente.
Vamosacrearunafuncindenominadacaida_librequeadmitacomo
parmetroseltiempotydevuelvalaposicinxyvelocidadvdeunmvilque
selanzadesde200mdealturaconvelocidadde40m/s.Laaceleracin
constantedelagravedadg=10m/s2
v=4010t
x=200+40t5t2
SeleccionamosFile/New/Functionparaabrireleditordefunciones.
1. Definimoslafuncin:
Lapalabraclavefunction
Lasvariablesdesalidaentrecorchetescuadrados[x,v]
Eloperadorasignacin=
Elnombredelafuncin,caida_libre
Entreparntesislavariabledeentrada(t)
2. Escribimoselcuerpodelafuncincondossentenciasquecalculanlavelocidadvylaposicinxcuandose
proporcionaeldatodeltiempot
3. Finalizamosconend.
4. SeleccionamosFile/SaveAs..paraguardarlafuncinenelficherocaida_libre.mconelmismonombrequela
funcin.
function[x,v]=caida_libre(t)
v=4010*t
x=200+40*t5*t^2
http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html
3/10
25/6/2015
Funciones
end
Enlaventanadecomandossellamaaestafuncincaida_libre,pasndoleuntiempot=2s,delsiguientemodo
>>[pos,vel]=caida_libre(2)
pos=240
vel=20
Quecalculaymuestra,lavelocidadv=20m/sylaposicinx=240menelinstantet=2s
Enlallamadaalafuncincaida_libreelparmetrotadquiereelvalorde2,enlasdossentenciassecalculala
velocidadyposicinyseguardanenlasvariableslocalesvyx.Lafuncindevuelveestosdosvaloresquese
copianenlasvariablesvelyposdelaventanadecomandos.Enlaventanadecomandosnotenemosaccesoalas
variablest,vyxporserlocalesalafuncincaida_libreydesaparecencuandoterminadeejecutarse,perosi
tenemosaccesoalasvariablesvelyposqueguardanlosresultadosdelclculorealizadoenelcuerpodela
funcin.
Siintentamosaccederalavariablexotobtendremosunmensajedeerror
>>x,t
???Undefinedfunctionorvariable'x'.
Siqueremosquelafuncincaida_librecalculelaposicinyvelocidaddelmvilparaunasecuencia(vector)de
tiempost,tendremosquemodificarladefinicindedichafuncin
function[x,v]=caida_libre(t)
v=4010*t
x=200+40*t5*t.^2
end
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=200260280260200100
vel=40200204060
Mediaydesviacinestndardeunconjuntodedatos
Ladefinicindemediaydesviacinestndareslasiguiente
n
xi
< x >=
n
2
(xi x)
=
n
n 1
Creamosunafuncindenominadaestadisticaalaqueselepasaunvectorxdedatosydevuelvelamediamedy
ladesviacin,des,ylaguardamosenunficheroconelmismonombrequelafuncin
function[med,des]=estadistica(x)
n=length(x)
med=sum(x)/n
des=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.7690
desviacion=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
http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html
4/10
25/6/2015
Funciones
Unficherofuncinpuedecontenermsdeunafuncin.Lasfuncionessedefinenunaacontinuacindelaotra.
Laprimerafuncineslaprimariaytieneelmismonombrequeelfichero,lasotrasfuncionessonsecundariasy
sedenominansubfuncionesypuedenestarencualquierordendentrodelfichero.Solamentesepuedellamarala
funcinprimariaenlaventanadecomandosoporotrasfunciones.Cadafuncintienesuspropiasvariablesque
sonlocalesalafuncin,nosepuedeaccederalasvariablesdeunasubfuncindesdelafuncinprimariaodesde
otrasubfuncin.Nosepuedeaccederalasvariablesdelafuncinprimariadesdeunasubfuncin.
Lassubfuncionespermitenorganizartareasgrandesenotrasmspequeas.
Msadelanteveremoslautilidaddeestasfuncionescuandolosprogramasseanmslargosycomplejos,de
momentovamosaverunejemploquenospermitavislumbrarcomosedefinenyllamanlassubfunciones.
Ecuacindesegundogrado
ax2+bx+c=0
Lasracessonx1yx2ytienenlassiguientespropiedades:
2
x1 =
b+ b 4ac
x1 + x2 =
2a
b
a
x2 =
b b 4ac
x1 x2 =
2a
c
a
Vamosacrearunafuncinquenospermitacomprobarlaspropiedadesdelasracesdeunaecuacindesegundo
grado,ydossubfunciones,laprimeracalculalarazx1ylasegundalarazx2.
Eneleditordefuncionescreamoslafuncincomprobar_raices,alaqueselepasaloscoeficientesa,bycdela
ecuacindesegundogradoydevuelveloscocientesb/ayc/adelasumayproductodelasdosracesx1yx2.
Guardamoselcdigodelafuncinprimariacomprobar_raicesydelassubfuncionescalcula_raiz1y
calcula_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+x2
r2=x1*x2
end
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_raicesy
lepasamosloscoeficientes1,1,6ynosdevolverb/a=1yc/a=6
>>[b_a,c_a]=comprobar_raices(1,1,6)
b_a=1
c_a=6
Funcionesanidadas
Unafuncinanidadaesunafuncindefinidadentrodeotrafuncin.Lasfuncinprimariaylasanidadasdeben
obligatoriamenteterminarconend
Lasfuncionesanidadastieneaccesoalasvariablesdelafuncinprimariaylafuncinprimariatieneaccesoalas
variablesdefinidasporlafuncinanidada.
Unafuncinanidadapuedecontenerotrayassucesivamente,peroesteprocesopuedellevaraconfusin.
Existenreglasparallamaraunafuncinanidadadentrodeotraperonotieneporelmomentointersparael
lector.
Eneleditordefuncionescreamoslafuncincomprobar_raices1,alaqueselepasaloscoeficientesa,bycdela
ecuacindesegundogradoydevuelveloscocientesb/ayc/adelasumayproductodelasdosracesx1yx2.
Guardamoselcdigodelafuncinprimariacomprobar_raices1ydelassubfuncionescalcula_raiz1y
calcula_raiz2enelficherocomprobar_raices1.m
function[r1,r2]=comprobar_raices1(a,b,c)
dis=sqrt(b*b4*a*c)
calcula_raiz1
calcula_raiz2
r1=x1+x2
r2=x1*x2
functioncalcula_raiz1
x1=(b+dis)/(2*a)
end
functioncalcula_raiz2
x1=(bdis)/(2*a)
http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html
5/10
25/6/2015
Funciones
end
end
Vemosquelasfuncionesanidadascalcula_raiz1ycalcula_raiz2tienenaccesoalosparmetrosa,bycdela
funcinprimaria,quesonvariableslocalesalafuncincomprobar_raicesytambin,alavariablelocaldis,que
guardaeldiscriminantedelaecuacindesegundogrado.Porotraparte,lafuncinprimariatieneaccesoalas
variablesx1yx2declaradasencadaunadelasfuncionesanidadas.
Estasfuncionesanidadasnoprecisandevariablesdeentradaynodevuelvennada.
Paracomprobarlasracesdelaecuacindesegundogradox2x6=0,llamamosalafuncincomprobar_raices1y
lepasamosloscoeficientes1,1,6ynosdevolverb/a=1yc/a=6
>>[b_a,c_a]=comprobar_raices(1,1,6)
b_a=1
c_a=6
Comoejercicioseporponeallectorcrearlafuncinestadistica_1,quedevuelvalamediayladesviacin
estndar,cuandoselepasaunvectordedatos.Elvalormediosecalcularmediantelafuncinanidadamediay
ladesviacinestndarmediantelafuncinanidadadesviacion.
Solucin
Funcionesannimas
Lasfuncionesannimasnospermitendefinirunafuncinsimplesinnecesidaddecrearlayguardarlaenun
fichero.m.Sepuedendefinirenlaventanadecomandos,enunficheroscriptodentrodeotrafuncin,conla
siguientesintaxis:
variable=@(lista_argumentos)expresion
expresionconsisteenunanicayvlidaexpresin,puedetenerunaomsvariablesdeentradaqueseespecifican
enlalistadeargumentosseparadasporcomas.Puedeincluirvariablesquesehandefinidopreviamente
Lasfuncionessepuedenasignaravariablesyestasvariablessepuedenpasaraotrasfuncionescomosepasan
escalaresovectores.Msadelanteveremoscmosellamaaunafuncindentrodeotrafuncinqueselepasaen
unodesusparmetros.
Comparamosladefinicindeunafuncinfuncqueseguardaenunficherofunc.mysuequivalenteannima
functiony=func(x)
y=cos(x)x
end
Llamadaalafuncin
>>z=func(0.5)
z=0.3776
Suequivalenteannimaseescribeenlaventanadecomandossinnecesidaddeguardarlaenunficheroysellama
delmismomodoquecualquierotrafuncin
>>f=@(x)cos(x)x
>>z=f(0.5)
z=0.3776
fguardaunvalorasociadoaunafuncinquedenominaremosmanejador(functionhandle)
EnlaventanaWorkspace,vemosqueapreceunavariablefdedistintotipoqueguardalareferenciaalafuncin
annima.
Teoremadelcoseno
http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html
6/10
25/6/2015
Funciones
Podemoscalcularelladocdeltringulosiconocemoslosladosaybyelngulocomprendido,medianteel
teoremadelcoseno
c = a
+ b
2ab cos
>>c=@(a,b,gamma)sqrt(a^2+b^22*a*b*cosd(gamma))
>>lado=c(3,4,30)
lado=2.0531
Llamadaaunafuncindesdeotrafuncin
Existenmuchasituacionesenlasqueunafuncinf1utilizaotrafuncinf2.Porejemplo,MATLABtieneuna
funcinfzeroqueseutilizaparacalcularlasracesdeunaecuacinf(x)=0.Lafuncinfselepasaafzerocuando
sellamaparaencontrarlasracesdef(x).Hayvariasformasdepasarunafuncinfaotrafuncinparasuuso.
Yahemosvistoelsignificadodemanejadorparaunafuncinannima,unvalorqueguardaunavariablefocy
queestasociadoaunafuncin.
Sidefinimosunafuncindeformaexplcitaenunficheroporejemplo,lafuncinfunc,obtenemoselmanejador
anteponiendoelcarcter@alnombredelafuncin
Laderivadadeunafuncin
Vamosahora,avercomoselepasaunafuncinaotrafuncinenunodesusparmetros.
Laderivadaprimerady/dx,deunafunciny=f(x)enunpuntox0,sepuedecalcularaproximadamentemediantela
frmula
f (x0 2h) 8f (x0 h) + 8f (x0 + h) f (x0 + 2h)
dy
=
dx
12h
dondehununnmeropequeoencomparacinconx0.Escribirunafuncindenominadaderivada,cuyos
parmetrosseanlafuncinf,ylaabscisax0ydevuelvaelvalordeladerivadadelafuncinf(x)enx0.Tomar
h=105.Utilizarlafuncinderivadaparacalcularlasderivadasdelassiguientesfunciones,comparandoconlos
resultadosexactos.
3
y = 2x
2
y = x e
x
x
+ 3 x0 = 1
x0 = 0.25
functionyp=derivada(f,x0)
h=1e5
yp=(f(x02*h)8*f(x0h)+8*f(x0+h)f(x0+2*h))/(12*h)
end
Enlaventanadecomandos,definimoslafuncin(annima)quequeremosderivaryllamamosalafuncin
derivada.
>>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(en
colorverde)
+ 3
http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html
7/10
25/6/2015
Funciones
3
y = x
dy
dx
6x
2
dx
2
= 3x
+ 3
12x
= 6x 12
x=3:0.05:7
f1=@(x)x.^36*x.^2+3
y=f1(x)%funcin
yp=derivada(f1,x)%derivadaprimera
f2=@(x)derivada(f1,x)
ypp=derivada(f2,x)%derivadasegunda
plot(x,y,'b',x,yp,'r',x,ypp,'g')
xlabel('x')
ylabel('y')
title('funcinyderivadas')
ylim([50,50])
gridon
Representacingrficadeunafuncin
Definimosunafuncindenominadagraficaylepasamoselmanejadordelafuncincuyagrficaqueremos
representarenundeterminadointervaloa,b.Lafuncinnodevuelveningnvalor.
functiongrafica(f,a,b)
x=linspace(a,b,50)
y=f(x)
plot(x,y,'r')
gridon
xlabel('x')
ylabel('y')
title('grficadeunafuncin')
end
Enlaventanadecomandocreamosunafuncinannimacuyomanejadoresfuncyllamamosalafuncin
grafica,pasndoleelmanejador,elintervalo(a,b)enelcualqueremosrepresentarlafuncin
>>func=@(x)xcos(x)
>>grafica(func,0,pi/2)
Aparecelaventanagrfica
http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html
8/10
25/6/2015
Funciones
Definimosunafuncinsimilarfunc1ylaguardamosenunficherofunc1.m
functiony=func1(x)
y=cos(x)x
end
Enlaventanadecomandosllamamosalafuncingrafica,pasndoleelmanejadordelafuncinfunc1,@func1y
elintervalo(a,b)enelcualqueremosrepresentarlafuncin.
>>grafica(@func1,0,pi/2)
Seobtienelamismagrfica
Lafuncinfplot
Lafuncinfplotdibujaunagrficasiselepasalafuncinfenelprimerparmetroyelintervalo[xmin,xmax]en
elsegundo
>>f=@(x)x5*(1exp(x))
>>fplot(f,[06])
Alternativamente,fplotdevuelveunatabladevalores[x,y]quepuedenserutilizadasporlafuncinplot(x,y)para
dibujargrfica,superponerunarejilla(grid),ponerttulo(title)yetiquetas(xlabel,ylabel),etc.talcomose
muestraenelsiguientescript
f=@(x)x5*(1exp(x))
[x,y]=fplot(f,[06])
plot(x,y)
gridon
xlabel('x')
ylabel('y')
title('grficadeunafuncin')
Haydiferenciassignificativasentreplotyfplot.Laprimeraevalalafuncinparavaloresdexigualmente
espaciados.Comovemoshayqueespecificarelintervaloxoelnmerodepuntos,mientrasqueenlasegunda
noesnecesarioespecificarlo.fplotevalainternamentelafuncinmsfrecuentementeenaquellasregionesenlas
quecambiarpidamente.Enelsiguienteejemplosedibujalasiguientefuncinenelintervalo[0.010.1]
y = sin (
>>x=0.01:0.001:0.1
>>y=sin(1./x)
>>plot(x,y)
http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html
9/10
25/6/2015
Funciones
Tomandox=0.001,seobtieneunafiguraconbajaresolucin.Sinembargo,
>>f=@(x)sin(1/x)
>>fplot(f,[0.010.1])
Obtenemosunafiguraconmejorresolucinsintenerqueprobardistintosvaloresdexodelnmerodepuntos.
EnergasRenovablesEUITIdeEibar
http://www.sc.ehu.es/sbweb/energiasrenovables/MATLAB/basico/funcion/funcion.html
10/10