This is still a work in progress, having trouble setting tolerances but setting the number of iterations seems to work fine.
Harmon Amakobe (2021). Newton's Method (https://www.mathworks.com/matlabcentral/fileexchange/30698-newton-s-method), MATLAB Central File Exchange. Retrieved .
Thank you sir, it help me to pass exams becuase of you. Keep doing good work.
Another submission to this method which my original.
% Newton Method for Finding Solution of equation Numerically
fprintf('THE PROGRAM COMPUTES THE SOLUTION TO AN EQUATION f(x)=0 BASED ON NEWTONS METHOD GIVEN FUNCTION f, Required Accuracy,Number of iterations \n');
prompt = 'input a function: ';
f=input('f(x)='); % input as f
prompt = 'input the starting value of x or x0: ';
x0=input('x0='); % starting number
prompt = 'What is the max tolerance acceptable? ';
toll = input(prompt)% tolerance input
if (toll<=0) %error 1
fprintf( 'You cannot have a negative tolerance!! \n Program will exit now \n')
prompt = 'What is the max iteration? ';
iter = input(prompt)%Error 2
fprintf( 'You cannot have a negative iteration!! \n Program will exit now \n')
disp (f); % input fucntion
disp (f_dir); % deravitive function
y=matlabFunction(f,'file','myfile'); % convert from Symbolic function to Matlab Function and stores in a file
ydir=matlabFunction(f_dir,'file','myfile_1'); % convert from Symbolic derivative to Matlab Function and stores in a file
out(1)=x0; % starting value
fprintf('n| xn | xn+1 | epsilon |\n');
for (i=1:iter) % converging
out(i+1)=out(i)-(myfile(out(i))/myfile_1(out(i))); %Newton Method
fprintf('%i|x%i=%f |x%i=%f |epsilon=(%f) |\n',(i-1),(i-1),out(i),i,out(i+1),abs(out(i+1)-out(i))); %shows the output in each iteration
if (abs((out(i+1)-out(i)))<=toll) % used for the condition to display the output
fprintf('Procedure completed successfully \n The solution converges to %f to 6D \n',(out(i+1)));%displays the final result of the convergence if it converges in 6D
break %Breaks program
fprintf('Failure \n procedure completed unsuccessfully')
fprintf('Please try with a different starting value of x0; Rerun program')
if (((iter-i)<=0)&&(abs((out(i+1)-out(i)))>=toll))%checks for the condition if the tolerance is not met
fprintf('Procedure completed unsuccessfully after N ierations \n Retry with more number of iretations and try a different starting value\n');
fplot(y,[-(x0) (x0)]); % plotting
fplot(ydir,[-(x0) (x0)],'r'); %plots the derivative function
title('Plot of f(x) and f''(x) in red')
% clear all; close all;
"Number of iterations will be increased accordingly in order to meet the set tolerance value" - in other words the "ite" parameter is always ignored. The code never stops if the tolerance is not met.
Note that your m file requires symbolic tool box in order to use the sym function. Another way to do this is to do a numerical differentiation to get f'(x) instead.
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!