how to store Fibonacci iteration results?

2 Ansichten (letzte 30 Tage)
engineer
engineer am 2 Sep. 2018
Bearbeitet: madhan ravi am 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

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Just for fun finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by