Atif Penkar
Atif Penkar

Reputation: 11

Fibonacci Recursion Value tracer

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.

Upvotes: 1

Views: 524

Answers (1)

Wolfie
Wolfie

Reputation: 30093

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.

Upvotes: 2

Related Questions