Write a Function function m-file program to compute the maximum of value of a fu
ID: 2325183 • Letter: W
Question
Write a Function function m-file program to compute the maximum of value of a function over a range. The function (equation/formula) itself should be passed along with a range (lower bound and upper bound) and number of equally-spaced points for generation of independent variable vector. You are NOT to use the MATLAB pre-defined function max or the like. You must program to calculate the maximum using if-else, for and while structures, if necessary. Please include MATLAB commands you will use to test your program in the command window for the function f(x) = -x^2 + 5x - 2 for x range from 0 to 10 for 11 points. % funcmax: max function value % fmax = funcmax (f, a, b, n, varargin): % compute maximum of value % of function over a range % input: % f = function to be evaluated % a = lower bound of range % b = upper bound of range % n = number of equally-spaced % value points % varargin = variable length arguments % output: % fmax = maximum of value of functionExplanation / Answer
function fmax = funcmax(f,a,b,n,varargin)
% funcmax: max function value
% fmax = funcmax(f,a,b,n,varagin):
% compute maximum of value of function over range
% input:
% f = functin to be evaluated
% a = lower bound of range
% b = upper bound of range
% n = number of equally spaced value points
% varargin = variable length arguments
% output:
% fmax = maximum of value of function
var = a:(b-a)/n:b;
func = inline(f,'x');
y = feval(func,var); % function evaluation
nmax = length(y);
temp = y(1);
for i = 1:nmax-1
if y(i+1)>y(i)
temp = y(i+1); % swapping
end
end
fmax = temp;
end
OUTPUT:
>> funcmax('-x.^2+5*x-2',0,10,11)
ans =
4.1983
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.