《科学计算科学计算 (20).pdf》由会员分享,可在线阅读,更多相关《科学计算科学计算 (20).pdf(8页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。
1、Nested call to a functionRecursive call to a function3.73.7 R Recursive ecursive C Call to a all to a F Functionunction1 1Nested Call to a FunctionNested Call to a FunctionWhen defining a function,if another function is called,then this procedure is called a nested call to a function.fact functionCa
2、ll a functionenda functionCall b functionb function2 2Recursive Call to a FunctionRecursive Call to a FunctionA function call itself is called recursive calls to a function.function f=fact(n)fact(n-1)Recursion is the method of solving a problem by firstly dividing a big problem into smaller sub part
3、s,whose structure should be identical to the structure of former problem.(2)Indirect recursion(1)Direct recursionf functionCall f functionf1 functionf2 functionCall f2 functionCall f1 functionExample 1:Try to find the factorial of n with the strategy of recursion.nnn nn!1,1(1)!,1=The factorial of n
4、itself is defined in a recursive form.The function file fact.m is as follows:Run the script file a.m in the Command Window:aPlease input n=36Call the function file fact.m in the script file a.m,find n.function f=fact(n)if n2)Write recursive function to find item n of Fibonacci sequence,and then call
5、 this function to verify the following properties of Fibonacci sequence:f12+f22+f32+fn2=fnfn+1The first eight terms of Fibonacci sequenceare:1,1,2,3,5,8,13,21.The sum of areas of 8 squares equals the sidelength of the 8th square multiplied by sidelength of the 9th square.First,create a function file ffib.m.function f=ffib(n)if n2f=ffib(n-1)+ffib(n-2);elsef=1;endCreate a script file test.m.F=;for k=1:20F=F,ffib(k)*ffib(k);endsum(F)ffib(20)*ffib(21)The result is:testans=74049690ans=74049690
限制150内