In: Mechanical Engineering
Practice for Matlab. You can create own f(x).
a. Write code to find and plot a root using the modified secant method
b. Find the roots using the roots command - identify and plot root of interest
c. Use polyder and roots to find and plot the minimum value
d. use fminbnd to find and plot minimum value
Thank you!
The matlab code is given below:
Matlab code:
close all; clear all; clc
F = @(x) x^2-10.56*x+5.6; % Define the function
p = [1 -10.56 5.6]; % Define same polynomial function with
coefficients
[x,e] = Modified_Secant_method(F,0.1,0,10,0.1) %
Used Modified Secant method
figure % New figure
title('Using roots')
scatter(real(x),imag(x),'filled','red') % Plot solution from
modified secant method
r = roots(p); % Use roots method
figure % New figure
title('Using roots')
xlabel('x value')
ylabel('Minimum value')
scatter(real(r),imag(r),'filled','red') % Plot solution from
roots
dF = polyder(p); % Polyder to find differential of
equation
rd = roots(dF); % Find the roots of differentiated polynomial
ddF = polyder(dF);
for i = 1:length(rd)
if(polyval(ddF,rd(1)) > 0)
minr = rd;
end
end
figure % New figure
title('Using polyder')
plot(minr,F(minr),'*r')% Plot minimum value
xlabel('x value')
ylabel('Minimum value')
figure
title('Using fminbnd')
xmin = fminbnd(F,0,10); % Find value of x for which the function is
minimum
plot(xmin,F(xmin),'*r')% Plot minimum value
xlabel('x value')
ylabel('Minimum value')
The script that calculates roots using modified secant method is given below:
Modified_Secant_method.m:
function [x,e] = Modified_Secant_method(F,del,x_0,N,err)
x(1) = x_0;
i = 1;
e = 10;
while((i<N) & (e>err))
x(i+1) = x(i)-(F(x(i))*del)/(F(x(i)+del)-F(x(i)));
if (i ~= 1)
e(i) = (abs(x(i+1)-x(i))/x(i+1))*100;
end
i = i+1;
end
end