Fibonacci Recursion Value tracer

隐身守侯 提交于 2021-02-11 07:55:15

问题


So I need to write a program which uses a recursive function to store the value of input arguments in the order they were made.

e.g. If my function is [f trace]=fibo_trace(6,[]) it should return

[f trace]=fibo_trace(6,[])
f=
    8
trace=
    6     4     2     3     1     2     5     3     1     2     4     2     3     1     2

With trace being the values with which the recursive call is being initialized and f being the 6th element in the fibonacci series.

Here is my code

function [f,trace] = fibo_trace(n,v)
    
    persistent ptrace;   % must specify persistent
   
    v=n; 
    ptrace=cat(2,ptrace,v);
   
    
    if n <= 2
        f = 1;
    else
        f = fibo_trace(n-2) + fibo_trace(n-1);
    end
    trace=ptrace;
end

But using a persistent variable does not give proper output if multiple conditions are tested. I need to compute this without using a persistent or global variable, can anyone help me out here?

When I don't use a persistent variable only the latest value of n is stored in vector v instead of the entire set of values.


回答1:


First, note that your input v is never used, you always overwrite it with n.

Next, note that your calls to fibo_trace(n-1) and (n-2) could return trace, you're just choosing not to. We can take advantage of the 2nd output to build the trace array.

These two points mean you can get rid of the persistent variable, and simplify the code a bit. We just need to make separate calls to fibo_trace for the two previous iterations.

function [f,trace] = fibo_trace(n)     
    if n <= 2
        % The trace should just be 'n' for the starting elements f=1
        f = 1;
        trace = n;
    else
        % Get previous values and their traces
        [f1, t1] = fibo_trace(n-1);
        [f2, t2] = fibo_trace(n-2);
        % Compute the outputs
        f = f1 + f2;
        trace = [n, t2, t1];
    end
end

Result:

[f, trace] = fibo_trace(6)
f =
     8
trace =
     6     4     2     3     1     2     5     3     1     2     4     2     3     1     2

There's some optimisation to be had here, since fibo_trace(n-1) will itself call fibo_trace(n-1), so computing fibo_trace(n-2) separately is multiplying the computation time.



来源:https://stackoverflow.com/questions/63555236/fibonacci-recursion-value-tracer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!