In: Electrical Engineering
Implement in MATLAB the Newton-Raphson method to find the roots of the following functions.
(a) f(x) = x 3 + 3x 2 – 5x + 2
(b) f(x) = x2 – exp(0.5x)
Define these functions and their derivatives using the @ symbol. For example, the function of part (a) should be f=@(x)x^3 + 3*x.^2 - 5*x + 2, and its derivative should be f_prime=@(x)3*x.^2 + 6*x - 5.
For each function, use three initial values for x (choose between -10 and 10), so that you can find more than a single root, if possible. Each time you run the algorithm, keep the values of x for each iteration, and plot them with respect to the iteration number.
Plot each function for x between -10 and 10 (e.g., x=-10:0.1:10;) to confirm visually that the roots that you found are where they are supposed to be. You may zoom in as you see fit to get a clearer picture about where the roots are.
function root=newton(x0)
count=0;
error=1;
tol=10^(-7);
max=50;
f=@(x)x^3 + 3*x.^2 - 5*x + 2;
f_prime=@(x)3*x.^2 + 6*x - 5;
while(error>tol & count<max)
fx=f(x0);
dfx=f_prime(x0);
x1=x0-fx/dfx;
if dfx==0
disp('derivative is zero');
return
end
count=count+1;
error=abs(x1-x0);
x0=x1;
iteration=[x1 error count];
x0=x1;
end
ezplot(f,[-10 10])
grid on
hold on
plot(x1,f(x1),'ro')
root=x1;
end
Command Wndow
There should be three roots but through newton raphson coding only one root can be found out. I have actually removed the if condition so that I get atleast two roots which you can see on the plot.
-----------------------------------------------------------------------------------------------------------------------------
function root=newton(x0)
count=0;
error=1;
tol=10^(-7);
max=50;
f=@(x)x^2 - exp(0.5*x);
f_prime=@(x)2*x - 0.5*exp(0.5*x);
while(error>tol & count<max)
fx=f(x0);
dfx=f_prime(x0);
x1=x0-fx/dfx;
if dfx==0
disp('derivative is zero');
return
end
count=count+1;
error=abs(x1-x0);
x0=x1;
iteration=[x1 error count];
x0=x1;
end
ezplot(f,[-10 10])
grid on
hold on
plot(x1,f(x1),'ro')
root=x1;
end
Command Window
Here I have managed to get three roots.