M函数 • • • • • • • • 一、M函数文件 二、匿名函数 三、局部函数 四、内嵌函数 五、私有函数 六、函数句柄 七、函数优先级顺序 八、递归 一、M 函数文件 Matlab 语言编写的程序称为 M 文件 M 文件以 .m 为扩展名 M 文件的分类: (1)Script:脚本文件 ,不接受参数的输入和输出。M 脚本文件 与maltab工作区(workspace)共享变量空间,每次只需要键入文 件名即可运行M脚本文件中的所有代码。 (2)Function:函数文件 ,接受参数的输入和输出,M函数文件 处理输入参数传递的数据,并把处理结果作为函数输出参数返回 给输出参数。M函数文件具有独立的内部变量空间。在调用函数 M文件时,要指定输入参数的实际取值,而且要指定接收输出结 果的输出变量。 1、M函数文件的格式 function [y1,...,yN] = myfun(x1,...,xM) M函数文件由 function 语句引导 function 输出形参列表 = 函数名(输入形参列表) % 注释说明部分(可选) 函数体语句(必须) end (可选) 函数名的命名规则与变量名相同 输入形参放在圆括号( )中,多余一个时,以逗号隔开,也 可以没有输入形参,这时可以省略圆括号 输出形参放在方括号[ ]中,多于一个时,以逗号分隔,也 可以没有输出形参。输出形参为一个或没有时,[]可以省略。 2、M 函数举例 (1)编写函数 function f = myfirstfun(n) f = prod(1:n); 形参 (2)保存函数文件(扩展名为.m) 为避免混淆,文件名应与函数名一致 (3)调用函数 x = 5; y = myfirstfun(x); 实参 若文件名与函数名不一致, 调用时应使用文件名。文件名命 名规则也应与变量名相同 3、函数参数 (1)确定函数输入参数的个数 函数 nargin 用于确定函数的输入参数个数。在函数体内部 用 nargin确定输入参数后可以用条件语句确定需要执行的操作。 function c = addme(a,b) switch nargin case 2 c = a + b; case 1 c = a + a; otherwise c = 0; end (2)确定函数输出参数的个数 函数 nargout 用于确定函数的输出参数个数。在函数体内部 用 nargout确定输出参数后可以用条件语句确定需要执行的操作。 function [dif,absdif] = subtract(y,x) dif = y - x; if nargout > 1 disp('Calculating absolute value') absdif = abs(dif); end (3)可变长度的输入参数列表(输入参数的个数可以 是不确定的) varargin 可以看做“Variable length input argument list”的缩写 。在matlab中, varargin提供了一种函数可变参数列表机制。 就 是说, 使用了“可变参数列表机制”的函数允许调用者调用该 函数时根据需要来改变输入参数的个数。 Examples: Variable Number of Function Inputs Define a function in a file named varlist.m thataccepts a variable number of inputs and displays the values of eachinput. function varlist(varargin) fprintf('Number of arguments: %d\n',nargin); celldisp(varargin) Call varlist with several inputs. Number of arguments: 3 varlist(ones(3),'some text',pi) varargin{1} = 1 1 1 1 1 1 1 1 1 varargin{2} = some text varargin{3} = 3.1416 Examples: varargin and Declared Inputs Define a function in a file named varlist2.m thatexpects inputs X and Y, andaccepts a variable number of additional inputs. function varlist2(X,Y,varargin) fprintf('Total number of inputs = %d\n',nargin); nVarargs = length(varargin); fprintf('Inputs in varargin(%d):\n',nVarargs) for k = 1:nVarargs fprintf(' %d\n', varargin{k}) end Call varlist2 with more than two inputs. varlist2(10,20,30,40,50) Total number of inputs = 5 Inputs in varargin(3): 30 40 50 Examples: Support Variable Number of Inputs This example shows how to define a functionthat accepts a variable number of input arguments using varargin.The varargin argument is a cell array that containsthe function inputs, where each input is in its own cell. Create a function in a file named plotWithTitle.m thataccepts a variable number of paired (x,y)inputs for the plot function and an optional title.If the function receives an odd number of inputs, it assumes thatthe last input is a title. function plotWithTitle(varargin) if rem(nargin,2) ~= 0 myTitle = varargin{nargin}; numPlotInputs = nargin - 1; else myTitle = 'Default Title'; numPlotInputs = nargin; end plot(varargin{1:numPlotInputs}) title(myTitle) Because varargin is a cell array, you accessthe contents of each cell using curly braces, {}.The syntax varargin{1:numPlotInputs} creates acommaseparated list of inputs to the plot function. Call plotWithTitle with two sets of (x,y) inputs and a title. x = [1:.1:10]; y1 = sin(x); y2 = cos(x); plotWithTitle(x,y1,x,y2,'Sine and Cosine') You can use varargin alone in an inputargument list, or at the end of the list of inputs, such as function myfunction(a,b,varargin) In this case, varargin{1} corresponds tothe third input passed to the function, and nargin returns length(varargin)+ 2. (4)可变长度的输入/输出参数列表(输入/输出参数 的个数可以是不确定的) varargout 可以看做“Variable length output argument list”的 缩写。在matlab中定义m函数时通过varargout我们可以得到可 变个数个返回值。 Examples: Variable Number of Function Outputs Define a function in a file named sizeout.m thatreturns an output size vector s and a variablenumber of additional scalar values. function [s,varargout] = sizeout(x) nout = max(nargout,1) - 1; s = size(x); for k=1:nout varargout{k} = s(k); end Output s contains the dimensions of the inputarray x. Additional outputs correspond to the individualdimensions within s. s= Call sizeout on a three-dimensionalarray and 4 5 2 request three outputs. rows = [s,rows,cols] = sizeout(rand(4,5,2)) 4 cols = 5 (5)其他与函数输入、输出参数相关的函数 检查函数的输入、输出参数 narginchk Validate number of input arguments nargoutchk Validate number of output arguments validateattributes Check validity of array validatestring Check validity of text string inputParser Parse function inputs 这些函数的具体用法,请查阅matlab的帮助。 函数应用示例:sudoku >> magic(3) ans = 8 3 4 1 5 9 6 7 2 sudoku_init.m (脚本文件) X = kron(eye(3),magic(3)) k = sub2ind(size(X),[1:4,6:9],[9,8,4,3,7,6,2,1]) X(k) = [3,8,1,3,1,3,2,1] 8 1 3 5 4 候选数 7 7 7 2 5 2 1 2 64 9 8 7 8 1 64 6 4 97 2 7 8 3 6 97 2 7 4 5 64 3 6 1 4 9 2 5 2 4 97 5 6 7 8 97 5 8 7 1 64 6 2 5 2 9 6 5 64 9 8 8 9 5 8 2 7 8 3 5 8 4 64 9 8 8 9 4 5 2 4 97 1 3 4 97 6 9 7 7 9 5 6 5 6 2 5 7 7 4 97 2 5 2 3 1 4 8 6 9 5 6 2 7 4 97 64 9 6 2 2 9 5 4 5 64 3 6 8 9 2 1 3 8 1 6 3 5 7 4 9 2 8 9 5 8 7 9 5 8 function [C,N] = candidates(X) % C = candidates(X) is a 9-by-9 cell array of vectors. % C{i,j} is the vector of allowable values for X(i,j). % N is a row vector of the number of candidates for each cell. % N(k) = Inf for cells that already have values. tri = @(k) 3*ceil(k/3-1) + (1:3); C = cell(9,9); for j = 1:9 for i = 1:9 if X(i,j)==0 z = 1:9; z(nonzeros(X(i,:))) = 0; z(nonzeros(X(:,j))) = 0; z(nonzeros(X(tri(i),tri(j)))) = 0; C{i,j} = nonzeros(z)'; end end end 记已有数值的单元格的候选数数目为inf,以后 N = cellfun(@length,C); 若发现某个单元格的候选数数目为0,则数独 N(X>0) = Inf; 无解。 N = N(:)'; function sudoku_plot(X,C) clf shg set(gcf,'WindowStyle','docked') hold on x = [0:9;0:9]; y = [zeros(1,10);9*ones(1,10)]; plot(x,y,'b','linewidth',2) plot(y,x,'b','linewidth',2) plot(x(:,1:3:end),y(:,1:3:end),'r','linewidth',4) plot(y(:,1:3:end),x(:,1:3:end),'r','linewidth',4) axis([-0.1,9.1,-0.1,9.1]) axis equal for r=1:9 for c=1:9 if X(r,c)>0 text(c-0.5,9.5r,num2str(X(r,c)),'fontsize',24,'HorizontalAlignment','center') ; else k = C{r,c}; K = zeros(3,3); K(k)=k; for i=1:3 The algorithm The outline of the main program is: • • • • Fill in all singletons. Exit if a cell has no candidates. Fill in a tentative value for an empty cell. Call the program recursively. function [X,steps] = sudoku_basic(X,steps) if nargin < 2 steps = 0; end [C,N] = candidates(X); sudoku_plot(X,C) disp(['steps = ',num2str(steps)]) pause while all(N>0) & any(N==1) s = find(N==1,1); X(s) = C{s}; steps = steps + 1; [C,N] = candidates(X); sudoku_plot(X,C) disp(['steps = ',num2str(steps)]) pause; end if all(N>0) Y = X; s = find(N==min(N),1); M 函数练习 1 函数y f x 的定义如下: x2 x 6 2 f ( x) x 5 x 6 x2 x 1 , x 0且x 4 , 0 x 10 , x 2且x 3 , 其它 1 编写一个Matlab函数实现该函数,且要求函数能够 处理输入参数为一维、二维数组的情况,即要求: f xij f xij mn mn 2 编写一个脚本文件,绘制上面的函数在区间 10 x 10的图形。 M 函数练习 2 Matlab没有专门的函数执行多项式加法(减法) 如果两个多项式的阶次相同,其系数向量的长度相等,多 项式的加法就是将两个多项式向量直接相加(相减)。 当两个多项式的阶次不同时,其系数向量的长度也不同, 这时需要先将低阶多项式的系数向量前边补上足够的0,以便使 它和高阶多项式具有相同的长度,然后再执行加法(减法)运算。 请编写一个函数 p = polyadd(p1,p2)实现不同阶次多项式 的加法,并利用该函数完成下面的练习。 练习: 已知:f x 1 2 x 3x 2 4 x3 g x 1 x 3x 2 求:f x g x , f x g x f = [4,3,2,1] g = [-3,-1,-1] M 函数练习 3 两个同一直线、频率相近的简谐振动的合振动 设一个质点同时参与两个同一直线不同频率的简谐振动, 角频率分别为ω1和ω2,为了突出频率不同所产生的效果,设分 振动的振幅和初相位都相同,因此两个分振动方程为 x1 = Acos(ω1t + φ) x2 = Acos(ω2t + φ) 利用和差化积公式可得合振动为 x x1 x2 2 A cos( 2 1 2 t ) cos( 2 1 2 t ) 可见:两个同方向不同频率的简谐振动合成之后不是简谐振 动,也没有明显的周期性。 x x1 x2 2 A cos( 2 1 2 t ) cos( 2 1 2 t ) 当两个分振动的频率比较大而差异比较小时: |ω2 - ω1| << ω2 + ω1, 方程就表示: 振幅按2Acos[(ω2 - ω1)t/2]变化, 角频率为(ω2 + ω1)/2的“近似”的简谐振动。 这种振动的振幅变化是周期性的,相对于“近似”的简谐振 动来说是缓慢的。 设两个振动的振幅都为1,初相都为0,第一个角频率为π/2 ,第二个角频率比第一个角频率大Δω = π/10。试在matlab中展示 上面所说的“近似”的简谐振动及其振幅的周期性。 M 函数练习 4 麦克斯韦速度分布律 若不考虑任何势场,在平衡态下,理想气体的麦克斯韦速率 分布函数为: 3 2 m f v 4 e 2 kT mv 2 2 kT v2 绘制并比较氖气(Ne)和氩气(Ar)在温度T1和T2时的速率分布 曲线 v 0, 2000 T1 273K 27 mNe 20.18 1.66 10 k 1.38110 23 JK 1 kg T2 500K mAr 39.94 1.66 1027 kg 二、匿名函数(anonymous function) 匿名函数不需要存盘为独立的.m文件。用户可以在命令窗 口或是其他任意 M 文件和脚本文件中使用匿名函数。 匿名函数的格式为:fhandle = @(arglist) expr 其中 fhandle 是为该函数创建的函数句柄;@ 符号用于创 建函数句柄;arglist 为用逗号分隔的参数列表;expr 为函数主 体,为 MATLAB 表达式。 sqr = @(x) x.^2; a = sqr(5) a= 25 Anonymous functions can contain only a single executable statement. 匿名函数举例(1) 很多Matlab函数可以用函数句柄作为输入参数。例如 quad()函数(使用Simpson算法求函数的数值积分)。它的一 种调用形式是: quad(fun, a, b) 其中,输入参数 fun 就可以是匿名函数 ,a和b分别是被积区间 的上、下限。考虑积分: 0 使用匿名函数 x cos xdx f = @(x)x.*cos(x) y = quad(f,0,pi) 匿名函数举例(2) Multiple Anonymous Functions The expression in an anonymous function can include another anonymous function. This is useful for passing different parameters to a function that you are evaluating over a range of values. g c x 2 cx 1 dx 1 0 g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1)) g(2) ans = 2.3333 integral():数值积分函数,与quad() 功能相同,matlab将来的版本会移除 quad()函数。 匿名函数举例(3) Variables in the Expression Function handles can store not only an expression, but also variables that the expression requires for evaluation.For example, create a function handle to an anonymous function that requires coefficients a, b, and c a = 1.3; b = .2; c = 30; parabola = @(x) a*x.^2 + b*x + c; Because a, b, and c are available at the time you create parabola, the function handle includes those values. The values persist within the function handle even if you clear the variables: clear a b c x = 1; y = parabola(x) y= 31.5000 匿名函数举例(4) Functions with No Inputs If your function does not require any inputs, use empty parentheses when you define and call the anonymous function. For example: t = @() datestr(now); d = t() d= 返回语句执行时的日期和时间 05-Nov-2014 19:13:54 Omitting the parentheses in the assignment statement creates another function handle, and does not execute the function: d = t d= @()datestr(now) 匿名函数举例(5) Functions with Multiple Inputs or Outputs Anonymous functions require that you explicitly specify the input arguments as you would for a standard function, separating multiple inputs with commas. For example, this function accepts two inputs, x and y: myfunction = @(x,y) (x^2 + y^2 + x*y); x = 1; y = 10; z = myfunction(x,y) z= 111 However, you do not explicitly define output arguments when you create an anonymous function. If the expression in the function returns multiple outputs, then you can request them when you call the function. Enclose multiple output variables in square brackets. For example, the ndgrid function can return as many outputs as the number of input vectors. This anonymous function that calls ndgrid can also return multiple outputs: c = 10; mygrid = @(x,y) ndgrid((-x:x/c:x),(-y:y/c:y)); [x,y] = mygrid(pi,2*pi); You can use the output from mygrid to create a mesh or surface plot: z = sin(x) + cos(y); mesh(x,y,z) 2 1 0 -1 -2 10 5 4 2 0 0 -5 -2 -10 -4 匿名函数举例(6) Arrays of Anonymous Functions Although most MATLAB fundamental data types support multidimensional arrays, function handles must be scalars (single elements). However, you can store multiple function handles using a cell array or structure array. The most common approach is to use a cell array, such as f = {@(x)x.^2; @(y)y+10;@(x,y)x.^2+y+10}; Access the contents of a cell using curly braces. For example, f{1} returns the first function handle. To execute the function, pass input values in parentheses after the curly braces: ans = x = 1; 1 y = 10; f{1}(x) f{2}(y) f{3}(x,y) ans = 20 ans = 21 三、局部函数(local function) Program files can contain multiple functions: the main function and any combination of local or nested functions. Local and nested functions are useful for dividing programs into smaller tasks, making it easier to read and maintain your code. Local functions are subroutines that are available to any other functions within the same file. They can appear in the file in any order after the main function in the file. Local functions are the most common way to break up programmatic tasks. 同一个M函数文件中可以包含多个函数。出现在文件中的 第一个M函数称为主函数(main function),其余的函数称为局 部函数(local function / subfunction,子函数)。M函数文件的 名称与主函数的名称保持一致。 局部函数只能被与其在同一M文件中的函数(包括主函数 和其他子函数)调用,不能在命令行窗口、其他M脚本或函数 文件调用。 主函数可以被命令行窗口、其他M脚本或函数文件 调用。 局部函数举例 function [avg, med] = mystats(x) n = length(x); avg = mymean(x,n); med = mymedian(x,n); end function a = mymean(v,n) % MYMEAN Example of a local function. a = sum(v)/n; end function m = mymedian(v,n) % MYMEDIAN Another example of a local function. w = sort(v); if rem(n,2) == 1 m = w((n + 1)/2); else m = (w(n/2) + w(n/2 + 1))/2; end end 在命令行不能调用局部函数,但可以用help命令查看局部 函数的帮助(主函数名、子函数名之间用>号分隔): >>help mystats>mymean mymean Example of a local function. 四、内嵌函数(nested functions ) 内嵌函数:定义在其他函数内部的函数。 内嵌函数可以使用外面那个函数的变量,不需要通过参数传递。 当一个 M文件中存在内嵌函数时,该文件内的所有函数必须以 end 结尾。 function x = A(p1, p2) ... function y = B(p3) ... end ... end 内嵌函数不能定义在程序控制 语句内部,如: if/elseif/else, switch/case, for, while, try/catch. Visibility of Nested Functions Every function has a certain scope, that is, a set of other functions to which it is visible. function A(x, y) % Main function B(x,y); D(y); function B(x,y)% Nested in A C(x); D(y); function C(x)% Nested in B D(x); end end function D(x) % Nested in A E(x); function E(x) % Nested in D disp(x) end end end A nested function is available: From the level immediately above it. ( function A can call B or D, but not C or E.) From a function nested at the same level within the same parent function. (Function B can call D, and D can call B.) From a function at any lower level. (Function C can call B or D, but not E.) 内嵌函数举例 (1) A nested function is a function that is completely contained within a parent function. Any function in a program file can include a nested function. For example, this function named parent contains a nested function named nestedfx: function parent disp('This is the parent function') nestedfx function nestedfx disp('This is the nested function') end end 内嵌函数举例 (2) Sharing Variables Between Parent and Nested Functions both a nested function and a function that contains it can modify the same variable without passing that variable as an argument. For example, in each of these functions, main1 and main2, both the main function and the nested function can access variable x: function main1 x = 5 nestfun1; function nestfun1 x = x + 1 end end function main2 nestfun2; function nestfun2 x = 5 end x = x + 1 end function main nestedfun1; nestedfun2; function nestedfun1 x = 1; end function nestedfun2 x = 2; end end Functions that return output arguments have variables for the outputs in their workspace. However, parent functions only have variables for the output of nested functions if they explicitly request them. For example, this function parentfun does not have variable y in its workspace: function parentfun x = 5; nestfun; function y = nestfun y = x + 1; end end If you modify the code as follows, variable z is in the workspace of parentfun: function parentfun x = 5; z = nestfun; function y = nestfun y = x + 1; end end 内嵌函数举例 (3) Nested functions are useful when subroutines share data, such as GUI applications that pass data between components. function myslider value = 0; f = figure; s = uicontrol(f,'Style','slider','Callback',@slider); e = uicontrol(f,'Style','edit','Callback',@edittext,... 'Position',[100,20,100,20]); function slider(obj,~) value = get(obj,'Value'); set(e,'String',num2str(value)); end function edittext(obj,~) value = str2double(get(obj,'String')); set(s,'Value',value); end end 内嵌函数举例 (4) Using Handles to Store Function Parameters Nested functions can use variables from three sources: Input arguments Variables defined within the nested function Variables defined in a parent function, also called externally scoped variables When you create a function handle for a nested function, that handle stores not only the name of the function, but also the values of externally scoped variables. For example, create a function in a file named makeParabola.m. This function accepts several polynomial coefficients, and returns a handle to a nested function that calculates the value of that polynomial. function p = makeParabola(a,b,c) p = @parabola; function y = parabola(x) y = a*x.^2 + b*x + c; end end The makeParabola function returns a handle to the parabola function that includes values for coefficients a, b, and c. At the command line, call the makeParabola function with coefficient values of 1.3, .2, and 30. Use the returned function handle p to evaluate the polynomial at a particular point: p = makeParabola(1.3,.2,30); Y= X = 25; Y = p(X) 847.5000 Many MATLAB functions accept function handle inputs to evaluate functions over a range of values. For example, plot the parabolic equation from -25 to +25: 900 800 fplot(p,[-25,25]) 700 600 500 400 300 200 100 0 -25 -20 -15 -10 -5 0 5 10 15 20 25 You can create multiple handles to the parabola function that each use different polynomial coefficients: firstp = makeParabola(0.8,1.6,32); secondp = makeParabola(3,4,50); range = [-25,25]; figure hold on fplot(firstp,range) fplot(secondp,range,'r:') hold off 2500 2000 1500 1000 500 0 -25 -20 -15 -10 -5 0 5 10 15 20 25 六、私有函数 Private functions are useful when you want to limit the scope of a function. 私有函数是 MATLAB 中的另一类函数,这类函数位于名为 “private”的子文件夹中,只能被上一级文件夹中的函数或者这 些函数所调用的 M 文件调用。 私有函数只能被其父文件夹中的函数调用,因此,用户可 以开发自己的函数库,函数的名称可以与系统标准 M 函数库名 称相同,而不必担心在函数调用时发生冲突,因为 MATLAB 首 先查找私有函数,再查找标准函数。 私有函数举例 1. For example, within a folder that is on the MATLAB® search path, create a subfolder named private. Do not add private to the path. Within the private folder, create a function in a file named findme.m: function findme % FINDME An example of a private function. disp('You found the private function.') 2. Change to the folder that contains the private folder and create a file named visible.m. 3. Change your current folder to any location and call the visible function. function visible findme >> visible You found the private function. 4. Although you cannot call the private function from the command line or from functions outside the parent of the private folder, you can access its help: >>help private/findme findme An example of a private function. 六、函数句柄 函数句柄(Function handle)是MATLAB的一种数据类型,保 存函数的路径、函数名等信息。函数句柄使得函数也可以成为 输入变量,并且能很方便的调用,提高函数的可用性和独立性。 handlef = @fname handlef = str2func('fname') 这里的fname可以是当前Matlab中可以使用的任意函数, 例如: mysin=@sin 此后mysin就和sin同样地使用。 mysin(pi)和sin(pi)的含义相同. 函数句柄的应用 很多Matlab函数可以用函数句柄作为输入参数。例如 quad()函数(使用Simpson算法求函数的数值积分)。它的一 种调用形式是: quad(fun, a, b) 其中,输入参数 fun 就可以是函数句柄 ,a和b分别是被积区间 的上、下限。考虑积分: 0 先定义M函数,并存盘 x cos xdx 再定义函数句柄,并调用 function y = dfw(x) f = @dfw y = x.*cos(x); y = quad(f,0,pi) 七、函数优先级顺序(Function Precedence Order) 1、Matlab搜索路径(Search Path ) 当用户在Matlab的命令窗口中输入一个命令时,Matlab会 在一些预先设置的路径(文件夹)中查找该命令,然后执行它,这 些预先设置的路径就称为搜索路径。 查看、修改和保存 Matlab的搜索路径 命令:pathtool 菜单:File Set Path 2. This topic explains how MATLAB® determines which function to call when multiple functions in the current scope have the same name. The current scope includes the current file, an optional private subfolder relative to the currently running function, the current folder, and the MATLAB path. MATLAB uses this precedence order: (1) Variables Before assuming that a name matches a function, MATLAB checks for a variable with that name in the current workspace. Note: If you create a variable with the same name as a function, MATLAB cannot run that function until you clear the variable from memory. (2) Imported package functions A package function is associated with a particular folder. When you import a package function using the import function, it has precedence over all other functions with the same name. (3) Nested functions within the current function (4) Local functions within the current file (5) Private functions (6) Object functions An object function accepts a particular class of object in its input argument list. When there are multiple object functions with the same name, MATLAB checks the classes of the input arguments to determine which function to use. (7) Class constructors in @ folders MATLAB uses class constructors to create a variety of objects (such as timeseries or audioplayer), and you can define your own classes using object-oriented programming. For example, if you create a class folder @polynom and a constructor function @polynom/polynom.m, the constructor takes precedence over other functions named polynom.m anywhere on the path. (8) Functions in the current folder (9) Functions elsewhere on the path, in order of appearance 3. When determining the precedence of functions within the same folder, MATLAB considers the file type, in this order: (1) Built-in function (2) MEX-function (3) Simulink® model, with file types in this order: a. SLX file b. MDL file (4) P-file (that is, an encoded program file with a .p extension) (5) Program file with a .m extension For example, if MATLAB finds a .m file and a P-file with the same name in the same folder, it uses the P-file. Because P-files are not automatically regenerated, make sure that you regenerate the P-file whenever you edit the program file. 八、递归函数 直接或间接地调用自身的算法称为递归算法。 用函数自身给出定义的函数称为递归函数。 例:阶乘函数 阶乘函数可递归地定义为: n0 1 n! n(n 1)! n 0 边界条件 递归方程 边界条件与递归方程是递归函数的二个要素,递归函数 只有具备了这两个要素,才能在有限次计算后得出结果。 例:在Matlab中用递归函数实现计算 n! % 函数文件 jc.m function f = jc(n) if (n==0) f = 1; else f = n*jc(n-1); end % main.m % 计算 s=1!+2!+3!+4!+5! % s = 0; for k = 1:5 s = s + jc(k); end disp(s) 练习: Fibonacci数列 无穷数列1,1,2,3,5,8,13,21,34,55,……, 称为Fibonacci数列。它可以递归地定义为: 0 n0 F ( n) 1 n 1 F (n 1) F (n 2) n 1 试用递归函数计算 F(n) 边界条件 递归方程