how to store Fibonacci iteration results?

4 vues (au cours des 30 derniers jours)
engineer
engineer le 2 Sep 2018
Modifié(e) : madhan ravi le 2 Sep 2018
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 commentaire
madhan ravi
madhan ravi le 2 Sep 2018
format your code by clicking the code button

Connectez-vous pour commenter.

Réponse acceptée

Star Strider
Star Strider le 2 Sep 2018
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 commentaires
Star Strider
Star Strider le 2 Sep 2018
@engineer — As always, my pleasure.
@madhan ravi — Thank you.
(I was away for a few minutes.)
madhan ravi
madhan ravi le 2 Sep 2018
Modifié(e) : madhan ravi le 2 Sep 2018
@Star rider your welcome and keep inspiring as always :)
@engineer anytime

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Just for fun dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by