Create the following function in matlab fx x2 05ex 4 Eval
Solution
func.m (This function evaluates the value of the given function at a value of x)
function f = func(x)
f = power(x,2) + exp(-1*x) - 4; %returning the value of the function
script.m (This file is where everything happens)
fun = @func; %imports func as fun
fs = zeros(81); %creates an array to store the values of function at different xs between -2 and 6
xs = zeros(81);
min = 1000000; %initialization of minimum
for i = -2:0.1:6 %looping through -2 to 6 with an interval of 0.1
f = func(i);
fs(int32((i+2)*10+1)) = f;
xs(int32((i+2)*10+1)) = i;
if (i>=-1 & i<=5 & f<min)
min = f; %updating minimum
end
end
x0 = [-1 2];
plot(xs, fs); %plotting xs and fs at various values
zeros = fzero(fun, x0); %finding zeros of the function
disp(zeros); %dispplaying zeros
disp(min); %displaying minimum
