Matlab';s的返回控件在递归函数中的行为?
它将返回递归函数还是返回调用递归函数的函数 在我看来,它将首先返回递归函数 一个小测试: 函数Matlab';s的返回控件在递归函数中的行为?,matlab,recursion,return,Matlab,Recursion,Return,它将返回递归函数还是返回调用递归函数的函数 在我看来,它将首先返回递归函数 一个小测试: 函数accu.m: function [AN] = accu(num,an) disp(['recursive function with num = ' num2str(num)]) if (num==0) AN=an; return end AN=accu(num-1,an+num); disp(['recursive function with num =
accu.m
:
function [AN] = accu(num,an)
disp(['recursive function with num = ' num2str(num)])
if (num==0)
AN=an;
return
end
AN=accu(num-1,an+num);
disp(['recursive function with num = ' num2str(num) '.'])
end
当我们调用accu(5,0)
时,它将返回:
recursive function with num = 5
recursive function with num = 4
recursive function with num = 3
recursive function with num = 2
recursive function with num = 1
recursive function with num = 0
recursive function with num = 1.
recursive function with num = 2.
recursive function with num = 3.
recursive function with num = 4.
recursive function with num = 5.
ans =
15
您试过了吗?:return强制MATLAB在调用函数到达函数末尾之前将控制返回给调用函数。调用函数是调用脚本或包含返回调用的函数的函数。在对函数的第一次调用中,它返回。之后,调用递归函数的函数就是递归函数本身。