Hi I want this code to spit out F = 10 when w = 0 at the maximum using the golden search method as shown by eliminating each w value until maximum is achieved. The starting upper and lower values are -1 and 1.
My trouble is Matlab does not understand 2*sin(5*w)/w = 2 when w = 0 not NaN Therefore my code is infinitely looping.
Can someone please help me solve this issue??
Below is the Code.
%Plots fourier transform. a=5; w=-a:a/100:a; F=2*sin(a*w)./w; plot(w,F)
r = 0.5*(sqrt(5)-1);% Lower and upper limits
wlower = -1;wupper = 1;% Answer from golden-section search method
wgs = 0.5*(wlower + wupper);% Error in result
werr = wupper - wlower;% Values of x to be used to find minima
w1 = wlower + r*werr;w2 = wlower + r^2*werr;% Evaluate function at critical locations
F1 = 2*sin(a*wlower)./wlower;F2 = 2*sin(a*wupper)./wupper;% Relative error for stopping
err_rel = 1e-4;% Absolute error for stopping
err_abs = 1e-8;
while (werr > wgs*err_rel && werr > err_abs) % Check which half of range the root is located
if F1 < F2 % Located in lower half, so reject upper half
wupper = w1ower; % Error in result werr = wupper - wlower; w1 = w2; F1 = F2; w2 = wlower + r^2*werr; F2 = 2*sin(a*wupper)./wupper; else % Located in upper half, so reject lower half
wlower = w2; % Error in result werr = wupper - wlower; w2 = w1; F2 = F1; w1 = wlower + r*werr; F1 = 2*sin(a*wlower)./wlower; end wgs = 0.5*(wlower + wupper);end
Best Answer