How to plot the error of two numerical methods on the same graph?
이전 댓글 표시
I'm trying to plot the error of two methods, but I got the following error
Index exceeds the number of array elements (3)
Also, How can I plot the error of the two methods on the same graph?
function xnew = newtonmethod(f,df,x0,tol,n)
%% Given data
f=@(x) 8-4.5*(x-sin(x));
df=@(x) -4.5*(1-cos(x));
x0=1;
tol=0.0001;
n=50;
%% Newton code
disp('No Itr Solution Error ')
Error=[];
for i=1:n
xnew=x0-(f(x0)/df(x0));
err=abs(xnew-x0);
fprintf('%3i %11.4f %11.4f %11.4f\n',i,x0,err);
if (err<tol)
break
end
x0=xnew;
Error=[Error;err];
end
%% Graph
plot(1:i,Error(1:i),'r-','Linewidth',02)
xlabel('No of Iteration','Interpreter','latex','FontSize',12)
ylabel('Error=$|x_{n+1}-n_n|$','Interpreter','latex','FontSize',12)
title('Error Decay','Interpreter','latex','FontSize',12)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 2nd method
function xnewh = Hmethod(f,df,ddf,x0,tol,n)
%% Given data
f=@(x) 8-4.5*(x-sin(x));
df=@(x) -4.5*(1-cos(x));
ddf=@(x) -4.5*sin(x);
x0=1;
tol=0.0001;
n=50;
%% code
disp('No Itr Solution Errorh')
Errorh=[];
for i=1:n
xnewh=x0- (2*f(x0).*df(x0)) ./ (2*(df(x0)).^2-ddf(x0).*f(x0));
errh=abs(xnewh-x0);
fprintf('%3i %11.4f %11.4f\n',i,x0,errh);
if (errh<tol)
break
end
x0=xnewh;
Errorh=[Errorh;errh];
end
%% Graph
plot(1:i,Errorh(1:i),'b-','Linewidth',02)
xlabel('No of Iteration','Interpreter','latex','FontSize',12)
ylabel('Error=$|x_{n+1}-n_n|$','Interpreter','latex','FontSize',12)
title('Error Decay','Interpreter','latex','FontSize',12)
%
채택된 답변
추가 답변 (1개)
%% Given data
f=@(x) 8-4.5*(x-sin(x));
df=@(x) -4.5*(1-cos(x));
x0=1;
tol=0.0001;
n=50;
[x_newton,i_newton,Error_newton]=newtonmethod(f,df,x0,tol,n);
ddf=@(x) -4.5*sin(x);
[x_Hmethod,i_Hmethod,Error_Hmethod]=Hmethod(f,df,ddf,x0,tol,n);
%Plot results
hold on
plot(1:i_newton,Error_newton,'r-','Linewidth',02)
plot(1:i_Hmethod,Error_Hmethod,'b-','Linewidth',02)
hold off
xlabel('No of Iteration','Interpreter','latex','FontSize',12)
ylabel('Error=$|x_{n+1}-n_n|$','Interpreter','latex','FontSize',12)
title('Error Decay','Interpreter','latex','FontSize',12)
function [xnew,i,Error] = newtonmethod(f,df,x0,tol,n)
%% Newton code
disp('No Itr Solution Error ')
Error=[];
for i=1:n
xnew=x0-(f(x0)/df(x0));
err=abs(xnew-x0);
Error=[Error;err];
fprintf('%3i %11.4f %11.4f\n',i,x0,err);
if (err<tol)
break
end
x0=xnew;
end
end
%% 2nd method
function [xnewh,i,Errorh] = Hmethod(f,df,ddf,x0,tol,n)
%% code
disp('No Itr Solution Errorh')
Errorh=[];
for i=1:n
xnewh=x0- (2*f(x0).*df(x0)) ./ (2*(df(x0)).^2-ddf(x0).*f(x0));
errh=abs(xnewh-x0);
Errorh=[Errorh;errh];
fprintf('%3i %11.4f %11.4f\n',i,x0,errh);
if (errh<tol)
break
end
x0=xnewh;
end
end
카테고리
도움말 센터 및 File Exchange에서 MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



