Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Matlab Script Write a user-defined function with function call [opt,k]=opt_finde

ID: 3796633 • Letter: M

Question

Matlab Script

Write a user-defined function with function call [opt,k]=opt_finder(fp,x0,kmax,tol) where fp is the derivative (as an inline function) of a given function f , x0 is a specified value, kmax is the maximum number of iterations, and tol is a specified tolerance. The function sets x1=x0 , calculates abs[fp( x1 )] , and if it is less than the tolerance, then x1 approximates the critical point opt at which the derivative is near zero. If not, it will increment x1 by 0.1 to obtain x2 , repeat the procedure, and so on. The process terminates as soon as abs[fp ( xk )] < tol for some k . The outputs are the approximate optimal point and the number of iterations it took to find it. Execute the function for f(x) = x + (x - 2)^(2), x0=1, kmax= 50, tol=10^(-2) .

Explanation / Answer

Matlab function opt_finder.m

function [opt,k] = opt_finder(fp,x0,kmax,tol)
k = 0; % Initially k set to zero No iterations
x1 = x0; %copy the content of X0 to x1
while (abs(fp(x1)) > tol&& k<kmax) % iterate until f(x1) <= tol or k reach kmax
      x1 = x1 + 0.1; % increment the value of x1
      k = k+1; % increment the value of iteration
end
if (k>=kmax) % maximum number of iterations reached
      error('maximum number of iterations reached');
else
      opt = x1; % loop exit if x1 is the optimal point
end
end

Testing the function

>> fp = @(x) 1+2*(x-2); % derivative of the function f
>> x0 = 1;
>> kmax = 50;
>> tol = 10^(-2);
>> [opt,k] = opt_finder(fp,x0,kmax,tol)

opt =

    1.5000


k =

     5

>>