How do I make a graph for newton raphson?
12 views (last 30 days)
Show older comments
Muhamad Danish Iskandar
on 22 Jun 2023
Commented: Muhamad Danish Iskandar
on 22 Jun 2023
% Newton Raphson Method
clc
clear all
close all
N = 30; % NO Iterations
err = 0.005; % Result Accuracy
% Equation to Solve
f = @(x) (9 * exp(-0.7*x) * cos (4*x)) - 3.5;
fdiff = @(x) - (63*cos(4*x)*exp(-(7*x)/10))/10 - 36*sin(4*x)*exp(-(7*x)/10);
%t = 0.1:0.1:1;
%y = f(t);
%figure
%plot(t,y);
x = 0; % Initial Value
xx(1) = x; % X History
fprintf('\n Itr. No.\t \t Xi\t \tf(Xi)\t\tfdiff(Xi)\t Ea\t \n')
for i = 2:N
x = x - f(x) / fdiff (x);
xx(i) = x; ii = i-1;
Err = abs(xx(i) - xx(i-1)); if Err < err, break; end
fprintf('\n \t%.0f\t \t%.4f\t \t%.4f\t \t%.4f\t \t%.2f\t',i,x,f(x),fdiff(x),Err)
end
fprintf('\n\n\t')
disp(['The Root is: ' num2str(x) ' , with accuracy: ' num2str(Err) ' , No. Iterations: ' num2str(ii)])
% Plotting Graph
x = linspace (-5,5);
Y = f(x);
subplot(2,1,1)
plot (x,Y,'linewidth',2)
xlabel ('Time, (s)'); ylabel ('Distance,(y)')
ax=gca;
ax.XAxisLocation = 'origin'
ax.YaxisLocation = 'origin'
box 'off'
0 Comments
Accepted Answer
the cyclist
on 22 Jun 2023
I edited your anonymous functions to use element-wise multiplication (.*) instead of matrix multiplication (*).
% Newton Raphson Method
clc
clear all
close all
N = 30; % NO Iterations
err = 0.005; % Result Accuracy
% Equation to Solve
f = @(x) (9 * exp(-0.7*x) .* cos (4*x)) - 3.5;
fdiff = @(x) - (63*cos(4*x).*exp(-(7*x)/10))/10 - 36*sin(4*x).*exp(-(7*x)/10);
%t = 0.1:0.1:1;
%y = f(t);
%figure
%plot(t,y);
x = 0; % Initial Value
xx(1) = x; % X History
fprintf('\n Itr. No.\t \t Xi\t \tf(Xi)\t\tfdiff(Xi)\t Ea\t \n')
for i = 2:N
x = x - f(x) / fdiff (x);
xx(i) = x; ii = i-1;
Err = abs(xx(i) - xx(i-1)); if Err < err, break; end
fprintf('\n \t%.0f\t \t%.4f\t \t%.4f\t \t%.4f\t \t%.2f\t',i,x,f(x),fdiff(x),Err)
end
fprintf('\n\n\t')
disp(['The Root is: ' num2str(x) ' , with accuracy: ' num2str(Err) ' , No. Iterations: ' num2str(ii)])
% Plotting Graph
x = linspace (-5,5);
Y = f(x);
subplot(2,1,1)
plot (x,Y,'linewidth',2)
xlabel ('Time, (s)'); ylabel ('Distance,(y)')
ax=gca;
ax.XAxisLocation = 'origin'
ax.YaxisLocation = 'origin'
box 'off'
More Answers (0)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!