MATLAB中带递归函数的内存错误

时间:2017-06-04 20:25:46

标签: matlab function recursion

我在MATLAB中有以下递归函数,但是一直出现“内存不足”错误。

我应该使用迭代方法吗?如果是这样,我该怎么做呢?

function [Result] = Test(n)
    % Test(0) = 0
    if n > 0
        Result = 1+(31/45)*Test(n-1)+(1/5)*Test(n+2)+(1/9)*Test(n+5);
    else
        Result = 0;
    end
end

这不需要转到无穷大,而只需要足够大的n

1 个答案:

答案 0 :(得分:1)

首先,您应该重写递归函数,如下所示:

T(n) = 1 + (31/45)*T(n-1) + (1/5)*T(n+2) + 1/9*T(n+5)
suppose: i = n + 5 => T(i-5) = 1 + (31/45)*T(i-4) + (1/5)*T(i-3) + 1/9*T(i)
=> T(i) = 9*T(i-5) - (31/5)*T(i-4) - (9/5)*T(i-3) - 9

所以T(1) = T(2) = T(3) = -9, T(4) = 36/5。因此,您可以像下面这样迭代:

function Result = Test(n)
T = zeros(1,n);
T(1) = -9; 
T(2) = -9; 
T(3) = -9;
T(4) =  36/5;
T(5) = 63;
for i = 6 : n
    T(i) = 9*T(i-5) - (31/5)*T(i-4) - (9/5)*T(i-3) - 9; 
end
Result = T(n);