科学计算科学计算 (19).pdf
3.6 3.6 Definition and Call of Function Definition and Call of Function FileFileBasic structure of function fileFunction callAnonymous function1.Basic Structure of Function 1.Basic Structure of Function FileFilefunction formal output arguments list=function name(formal input arguments list)AnnotationsFunction body statementIf there are more than one formal output argument,they should be put in square brackets to form an output matrix.The name of a function file usually consists of the function name and an extension name.m.When the name of a function file and the function name are different,MATLAB willignore the function name and use the name of the function file when calling the function.The return statement indicates the end of function execution.Generally,the returnstatement is not used in the function file,so the called function will return automaticallyafter execution.Example 1 Create a function file to find the area and perimeter of the circle with radius r.function s,p=fcircle(r)s=pi*r*r;p=2*pi*r;2.Function Call2.Function CallForm of function call:actual output arguments list=function name(actual input arguments list)Call the fcircle function we defined before in the MATLAB Command Window.s,p=fcircle(10)s=314.1593p=62.83193.Anonymous Function3.Anonymous Functionfunction handle variable=(anonymous function input argument)anonymous function expressionOperators for function handles f=(x,y)x2+y2f=(x,y)x2+y2 f(3,4)ans=25function handle variable=function nameInner functions or user-defined function h=sin h=sin h(pi/2)ans=1Function file f2.mfunction f=f2(n)f=0;for k=1:nf=f+k*(k+1);endScript file mf.mf1=(n)n+10*log(n*n+5);y1=f1(40)/(f1(30)+f1(20)y2=f2(40)/(f2(30)+f2(20)Example 2 y=f(40)/(f(30)+f(20)(1)When f(n)=n+10ln(n2+5),what is the value of y?(2)When f(n)=12+23+34+.+n (n+1),what is the value of y?Define function f(n)with anonymous function and function file respectively.mfy1=0.6390y2=1.7662