In: Computer Science
Optimization Technique: Consider one-variable function f(x). Use Newton Method to find minimum/maximum and plot the graph. Use Matlab.
clear;
close all;
clc;
f1 = @(x) exp(2*sin(x))-x; // %function //
x0 = 3; // %initial guess //
maxIter = 1e6; // %max iteration of the function //
epsilon = 10e-6; // %tolerance value //
[xk,i,error,errorVect] = NewtonsMethod(x0,maxIter,epsilon); //% Calling the Newton's Method function //
fprintf('\nThe solution of the function exp(2*sin(x))-x = 0 is %4.5f in %u iteration with %e error.\n', xk,i,error)
xk; // % Printing Newton's Method Results in the console //
ymin = f1(xk);
errorVect;
//% Function for Newton's Method function //
// %Graphing the error vector //
x_axis = 1:1:length(errorVect); // %x-axis values //
semilogy(x_axis,errorVect,'-mo'); // %graph of error vector in logarithmic y-axis //
grid on // %logarithmic grid (y-axis only) //
function[xk,i,error,errorVect] = NewtonsMethod(xk,maxIter,epsilon)
xold = xk;
for i = 1:maxIter
[f1x,df1x,ddf1x]=myfunction(xk);
xk = xk - (df1x/ddf1x);
error = abs(xk-xold);
xold = xk;
errorVect(i) = error;
if (error<epsilon)
break;
end
end
end
//% Function for calling the value and the derivative of the function//
function [f,g,h] = myfunction(x)
f1 = @(z) exp(2*sin(z))-z; // %function //
dx = 0.1;
ff = f1([x-dx, x, x+dx]); // % this is a 3-element vector //
f = ff(2); // % the middle value is f1(x) //
if nargout > 1 // % (not sure why you use this) //
gg = diff(ff)./dx; // % this is a 2-element vector from diff(ff) //
g = gg(1);
h= diff(gg)./dx; // % single value from diff(gg) //
end
end