Plotting Newton Interpolating Polynomial

17 views (last 30 days)
Zayd Islam
Zayd Islam on 19 Mar 2021
Commented: Zayd Islam on 19 Mar 2021
Currently I have these values for x & y and the calculated coefficients (z). Of a newton polynomial
I have attached an image of the function i want to calculate, can someone help me put this function in a nested loop format. And then that function can be plotted aswell. also this loop and function cretaed should be feasible and therefore useable for any degree polynomial
In the image y1 y21 y321 y4321 and y54321 is the same as z(1) z(2) z(3) z(4) z(5) and in the image x is just x-axis on graph
also in the image x1 x2 x3 x4 corresponds to x(1) x(2) x(3) & x(4).
Thank You for your help
x = [-1.9021 -1.1756 0 1.1756 1.9021]
y = [0.0268 0.2362 0.5 0.2362 0.0268]
z = [0.0268 0.2882 -0.0335 -0.0511 0.0269]

Answers (2)

Alan Stevens
Alan Stevens on 19 Mar 2021
Do you mean something like this?
xconsts = [-1.9021 -1.1756 0 1.1756 1.9021];
y = [0.0268 0.2362 0.5 0.2362 0.0268];
yconsts = [0.0268 0.2882 -0.0335 -0.0511 0.0269];
x = linspace(-1.9021,1.9021,5);
ypoly = zeros(1,numel(x));
for j = 1:numel(x)
ypoly(j) = npoly(x(j),xconsts,yconsts);
end
disp(ypoly)
subplot(2,1,1)
plot(x,ypoly,'o-'),grid
xlabel('x'),ylabel('y from polynomial')
subplot(2,1,2)
plot(x,ypoly-y,'*-'),grid
xlabel('x'),ylabel('y-ypoly')
function y = npoly(x,xconsts,yconsts)
xi = 1;
y = yconsts(1);
for i = 1:(numel(xconsts)-1)
xi = xi*(x-xconsts(i));
y = y + yconsts(i+1)*xi;
end
end
  2 Comments
Zayd Islam
Zayd Islam on 19 Mar 2021
not entirely Alan anychance you could join a meeting on zoom or teams with me?
this is for my coursework project by the way
Alan Stevens
Alan Stevens on 19 Mar 2021
Can you explain why this isn't what you were looking for?

Sign in to comment.


Zayd Islam
Zayd Islam on 19 Mar 2021
Hi Alan basically what i was looking for was a function to take in my X and Y values and the newton coefficients (Z) and of course the degree of the polynomial which is 1 less the number of data points so in this case it was degree 4. I would like the function to return a polynomial with a function handle so like this. Hope you understand what i mean :)
%o is just any letter
yourpolynomial_is = @(o) z(1) + z(2)*(o-x(1)) etc etc etc etc
  2 Comments
Alan Stevens
Alan Stevens on 19 Mar 2021
I've not written the function as an anonymous function, but it might still work the way you want I think.
If I understand you correctly, you want a symbolic expression returned. If you define your o as syms o, the function I've written might produce what you want. Unfortunately, I don't have the symbolic toolbox, so I can't check that.

Sign in to comment.

Categories

Find more on Polynomials in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!