In: Advanced Math
a) Write an function that finds the independent variable value at which a mathematical function is maximized over a specified interval. The function must accept a handle to a function, and evaluate that function at values ranging from x1 to x2 with an increment of dx. The value returned is the value of x at which the maximum value of f(x) occurs.
Function syntax: xm = xmax(f,x1,x2,dx);
As was the case in the previous problem, this function does not
find the true value of x that maximizes f(x). It only identifies
the value of x that yields the maximum value of f(x) from among
those values of x at which the function is evaluated. How closely
this approximates the true maximum point of f(x) will depend on the
step size, dx.
Your function should use only basic arithmetic operations and loop
structures. You may not use any built-in MATLAB functions
(e.g., mean.m, sum.m, max.m, min.m, etc.).
Next, you will investigate how the estimated maximum point varies
as a function of dx.
b) Write an m-file, ENGR112_HW6_2.m, in which you define the following as an anonymous function.
?(?)=−?^2+15??+21.843
Define a logarithmically-spaced vector, dx, of 2000 step sizes, from 10-4… 100, at which xmax.m will be used to approximate the maximizing value of f(x) over the interval of 0 ≤ x ≤ 50. Call xmax.m at each value of dx and build a vector of maximizing independent variable values, xm. In
c) Plot the vector of approximate maximizing values as a function of step size using a logarithmic axis for the step size. You should see that the approximation converges as step size gets small enough.
%%Finding maximum value of an array
clear all
close all
%function for finding maximum f(x) for given x
f=@(x) -x.^2+15.*pi.*x+21.843;
x1=0;
x2=50;
%logarithmically spaced vector of 2000 step
dx=logspace(-4,2,2000);
%finding xm values for different dx
for i=1:length(dx)
xm(i) = xmax(f,x1,x2,dx(i));
end
semilogx(dx,xm)
xlabel('step size dx')
ylabel('xmax values')
title('xmax vs. step size plot')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%function for finding maximum value
function [xm] = xmax(f,x1,x2,dx)
%all x values
x=x1:dx:x2;
y=f(x);
%finding maxima for the function
for i=1:length(x)-1
if y(i)>=y(i+1)
t1=y(i);
y(i)=y(i+1);
y(i+1)=t1;
t1=x(i);
x(i)=x(i+1);
x(i+1)=t1;
end
end
xm=x(end);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%