Newton's Divided Differences Function

51 views (last 30 days)
Abiageal
Abiageal on 25 Jan 2024
Edited: Mann Baidi on 25 Jan 2024
I am trying to make a simple code to compute newtons divided differences from an array of x values and an array of y values. I am new to coding so I am not sure if I am doing this right / where my error is and I keep getting a matrix of all zeros as my answer. Here is my coded attached below
function [B] = dividediffs(x,y)
%DIVIDEDDIFFS computes the divided differences of an array of (x,y) points
% INPUT: two arrays of x and corresponding y values OUTPUT: divided differences
n = length(x);
B = zeros(n,n);
if n == 1
B = y(1);
else
for k = 2:n
for i = 1: n-k+1
if (i+k) <= n
B(i,k) = (B(i+1,k-1)-B(i,k-1))/(x(i+k)-x(i));
end
end
end
end

Answers (1)

Mann Baidi
Mann Baidi on 25 Jan 2024
Edited: Mann Baidi on 25 Jan 2024
Hi Abiageal,
As per the information provided in the question, I understand that you are facing issues in implementing 'Newton's Divided Differences Function' as you are getting 'B' a matrix of all zeros.
This is because in the 'Newton's Divided Differences Function' we need to initialize the first row of 'divided differences table'.
You can try initialising the first row with the help of this code.
x=1:10;
y= 11:20;
ans=dividediffs(x,y)
ans = 10×10
11.0000 0.5000 0 0 0 0 0 0 0 0 12.0000 0.5000 0 0 0 0 0 0 0 0 13.0000 0.5000 0 0 0 0 0 0 0 0 14.0000 0.5000 0 0 0 0 0 0 0 0 15.0000 0.5000 0 0 0 0 0 0 0 0 16.0000 0.5000 0 0 0 0 0 0 0 0 17.0000 0.5000 0 0 0 0 0 0 0 0 18.0000 0.5000 0 0 0 0 0 0 0 0 19.0000 0 0 0 0 0 0 0 0 0 20.0000 0 0 0 0 0 0 0 0 0
function [B] = dividediffs(x,y)
%DIVIDEDDIFFS computes the divided differences of an array of (x,y) points
% INPUT: two arrays of x and corresponding y values OUTPUT: divided differences
n = length(x);
B = zeros(n,n);
B(:, 1) = y';
if n == 1
B = y(1);
else
for k = 2:n
for i = 1: n-k+1
if (i+k) <= n
B(i,k) = (B(i+1,k-1)-B(i,k-1))/(x(i+k)-x(i));
end
end
end
end
end
Hope this resolve your query!

Categories

Find more on Loops and Conditional Statements 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!