我已经写了以下代码,但没有得到正确的x值。然而,我们从第2行中删除了分号,似乎我得到了正确的答案。但输出并不正确。
function [f, x]=fibo_trace(n,sak)
trace=tracker(n)
x=trace;
if n<=2
f=1;
else
f=fibo_trace(n-2)+fibo_trace(n-1);
end
end
function sak=tracker(n)
persistent i;
persistent k;
if isempty(i) || isempty(k)
i=1;
k=[];
end
k(i)=n;
sak=k;
i=i+1;
end
我不确定你喜欢跟踪什么,但我建议你总是通过并返回x.
如果你想跟踪递归函数的计算输入(n(,你可以编写这样的代码:
function [f, x]=fibo_trace(n)
i = 0;
x = [];
[f, x] = fibo_trace_rec(n, x);
function [f, x] = fibo_trace_rec(n, x)
i=i+1;
x(i) = n;
if n<=2
f = 1;
else
[f2, x] = fibo_trace_rec(n-1, x);
[f1, x] = fibo_trace_rec(n-2, x);
f = f1+f2;
end
end
end
结果是:
>> [f x] = fibo_trace(6)
f =
8
x =
6 5 4 3 2 1 2 3 2 1 4 3 2 1 2
或者,如果你喜欢在x中使用fibonacci序列,例如:
function [f, x]=fibo_trace(n)
x = [];
[f, x] = fibo_trace_rec(n, x);
function [f, x] = fibo_trace_rec(n, x)
if n<=2
f = 1;
x(1) = 1; % set x for n == 1 because, for n==2, n==1 is never called!
else
[f2, x] = fibo_trace_rec(n-1, x);
[f1, x] = fibo_trace_rec(n-2, x);
f = f1+f2;
end
x(n) = f;
end
end
结果是:
>> [f x] = fibo_trace(6)
f =
8
x =
1 1 2 3 5 8