how to store Fibonacci iteration results?

1 回表示 (過去 30 日間)
engineer
engineer 2018 年 9 月 2 日
編集済み: madhan ravi 2018 年 9 月 2 日
Hello everybody
I would like to store the result of each iteration of the Fibonacci search algorithm.
if true
function x=fibosearch(fhandle,a,b,npoints)
x = [-50:10:20];
a1 = 0.2661;
b1 = -18.24;
c1 = 21.62;
a2 = 1.135e+09;
b2 = 1.174e+04;
c2 = 2555;
fhandle = @(x)a1*exp(-((x-b1)/c1).^2) + a2*exp(-((x-b2)/c2).^2);
a=-50;
b=20;
npoints=100;
nfibo=22;
fibo=[1,1,zeros(1,nfibo-2)];
for k=1:nfibo-2
fibo(k+2)=fibo(k+1)+fibo(k);
end
fiboindex=3;
while fibo(fiboindex)<npoints
fiboindex=fiboindex+1;
end
for k=1:fiboindex-2
if k==1
x1 = a+fibo(fiboindex-k-1)/fibo(fiboindex-k+1)*(b-a);
x2 = b-fibo(fiboindex-k-1)/fibo(fiboindex-k+1)*(b-a);
fx1 = fhandle(x1);
fx2 = fhandle(x2);
end
if fx1<fx2
a=x1;
x1=x2; fx1=fx2;
x2=b-fibo(fiboindex-k-1)/fibo(fiboindex-k+1)*(b-a);
fx2=fhandle(x2);
else
b=x2;
x2=x1; fx2=fx1;
x1=a+fibo(fiboindex-k-1)/fibo(fiboindex-k+1)*(b-a);
fx1=fhandle(x1);
end
end
if fx1<fx2
x=x2;
else
x=x1;
end
disp(fiboindex-2)
end
end
The result of the final iteration is -16.0501624147 which is x. However, I would like to see the result of each iteration. How can I plot iteration number vs result of iteration?
Any help is highly appreciated.
Thanks
  1 件のコメント
madhan ravi
madhan ravi 2018 年 9 月 2 日
format your code by clicking the code button

サインインしてコメントする。

採用された回答

Star Strider
Star Strider 2018 年 9 月 2 日
In your ‘k’ loop, add a line saving the appropriate value of ‘x1’ or ‘x2’ (or both, as I do here) along with the iteration number:
for k=1:fiboindex-2
if k==1
x1 = a+fibo(fiboindex-k-1)/fibo(fiboindex-k+1)*(b-a);
x2 = b-fibo(fiboindex-k-1)/fibo(fiboindex-k+1)*(b-a);
fx1 = fhandle(x1);
fx2 = fhandle(x2);
end
if fx1<fx2
a=x1;
x1=x2; fx1=fx2;
x2=b-fibo(fiboindex-k-1)/fibo(fiboindex-k+1)*(b-a);
fx2=fhandle(x2);
else
b=x2;
x2=x1; fx2=fx1;
x1=a+fibo(fiboindex-k-1)/fibo(fiboindex-k+1)*(b-a);
fx1=fhandle(x1);
end
xv(k,:) = [k x1 x2]; % <— Add This Line
end
That saves all of them to a matrix to work with later. (You will have to add that to the outputs of ‘fibosearch’ if you want to return it as an output.)
  5 件のコメント
Star Strider
Star Strider 2018 年 9 月 2 日
@engineer — As always, my pleasure.
@madhan ravi — Thank you.
(I was away for a few minutes.)
madhan ravi
madhan ravi 2018 年 9 月 2 日
編集済み: madhan ravi 2018 年 9 月 2 日
@Star rider your welcome and keep inspiring as always :)
@engineer anytime

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by