Is anything wrong with Eval function? I get value of pn =1 for all x values.
Show older comments
function HW_4_8()
y= @(x)(1/(1+25*x.^2));
%x=linspace(-1,1,41);
for i=0:5
x=cos(i*pi/40);
end
fprintf('Coefficient of the newton interpolation\n\n');
a= Coef(x,y);
for i=1:length(a)
fprintf('%5.0f\t%15.10f\n',i-1,a(i));
end
xp=linspace(-1,1,200);
fprintf('Approximate value of y(x)\n');
fprintf(' n x p(x)');
fprintf( ' y(x) diff\n');
for i=1:length(xp)
p=xp(i);
funval=(1./(1+25*p.^2));
% fplot(funval,[-1,1]);
pn= Eval(x,a,p);
D=abs(funval-pn);
% disp(D);
% fplot(diff,[-1,1]);
fprintf('%5.0f\t%5.10f\t%15.10f\t%15.10f\t%15.10f\n',i,p,pn,funval,D);
end
%fplot(D,[-1,1]);
end
function[a]=Coef(x,y)
mx=length(x);
my=length(y);
% if mx ~= my
% error('must be same lenght');
% end
T=zeros(mx,mx);
T(:,1)=(my)';
for j=2:mx
for i=1:(mx-j+1)
T(i,j)=(T(i+1,j-1)-T(i,j-1))/(x(i+j-1)-x(i));
end
end
a=T(1,:);
end
function pn=Eval(x,a,p)
m=length(a);
sum=0;
for i=1:m
temo=1;
for j=1:i-1
temo=temo*(p-x(j));
end
sum =sum+a(i)*temo;
end
pn=sum;
end
4 Comments
Are Mjaavatten
on 9 Apr 2018
x is not initialized to a vector, as you intend, but to a scalar. Try:
x = zeros(6,1);
for i=0:5
x(i+1)=cos(i*pi/40);
end
Furthermore your y function should use element-wise division:
y= @(x)(1./(1+25*x.^2));
And you should pass the value, not the function, to Coef:
a= Coef(x,y(x));
A more general advice is to split and conquer: Test and debug the subfunctions first. Make sure that they do what you want them to do before incorporating them in the main function.
I also think that you could benefit from a better understanding of Matlab. Take a look at this page . Or search the net for "Matlab tutorial" or Matlab introduction"
Guillaume
on 9 Apr 2018
@Are, this would have been better as an answer (which we could have voted for)
Muhtasim Ahmed
on 9 Apr 2018
Are Mjaavatten
on 9 Apr 2018
Thanks for the feedbacks from both of you.
Guillaume: This started out as a brief comment on the x vector, but it sort of grew as I wrote. I should have considered changing it to it an answer.
Answers (0)
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!