f(x) = x 2 - 10x + 23 Write a MATLAB code with the following requirements: • Set
ID: 3209903 • Letter: F
Question
f(x) = x 2 - 10x + 23
Write a MATLAB code with the following requirements:
• Set the maximum number of iterations to 30 and set the accuracy on the root to 0.01.
• Solve for the root with the specified accuracy.
• Show the number of iterations.
• Include a break statement or use a while loop so when the solution reaches the specified accuracy it will stop.
a) Solve using the secant method and x0 = 1, x1= 2. Plot the function and the root on the same figure.
b) Solve using the Newton-Raphson method and x0 = 2.5. c) Comment on the results. How many iterations did it take for the specified accuracy for each method?
Explanation / Answer
ANSWER;
EXICUTABLE CODE:
%%%%%%%%%% Solution using secant method %%%%%%%%%%%%%%%%%%%
tolerance=0.01;
f=@(x) x^2-10*x+23;
x0=1;
x1=2;
iterations=1;
maximumIterations=30;
c=(x0*f(x1)-x1*f(x0))/(f(x1)-f(x0));
while abs(f(c))>tolerance
x0=x1;
x1=c;
c=(x0*f(x1)-x1*f(x0))/(f(x1)-f(x0));
iterations=iterations+1;
if(iterations==maximumIterations)
break;
end
end
if iterations<maximumIterations
disp(['Root of this Equation = ' num2str(c)]);
fprintf('Number of iterations taken: %d ', iterations);
else
disp('Error! Cannot find Root of this equation.');
end
% plotting
x = -10:0.01:10;
f = x.^2-10.*x+23;
figure;
plot(x,f)
hold on;
plot(c,'r');
grid on
%%%%%%%%%%%%%%%%%%%%%%%%%% Solution using Newton Raphson %%%%%%%%%%%%%%%%%%%
tolerance=0.01;
f=@(x) x^2-10*x+23;
iterations=1;
maximumIterations=30;
d=@(x) 2*x-10;
x(1)=2.5;
error=100;
while error>tolerance
x(iterations+1)=x(iterations)-((f(x(iterations))/d(x(iterations))));
error=abs((x(iterations+1)-x(iterations))/x(iterations));
iterations=iterations+1;
if(iterations==maximumIterations)
break;
end
end
root=x(iterations);
disp(root);
fprintf('Number of iterations taken: %d ', iterations);
%%%%%%%%%%%%% Question c %%%%%%%%%%%%%%%%
% Secant method took 3 iterations whereas newton raphson took 4 iterations.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.