We’d love to hear any feedback or comment from you!

###### Engineering · Computer Science
Question details

Please explain me the code as detailed as possible(MATLAB)

% lecture 10a.m

% this Matlab program computes divided differences

% and builds a Newton Polynomial using the iterative process

% described in lecture

% it also builds the derivative function

% the ‘pause’ in the script pauses the running of the

% program until the user presses a key

clear; close; clc;

x = [3;5;2;1];          % column vector for nodes

y = [7; -1; 14; 11];    % column vector for values

n = length(x);

D = zeros(n)   % build the matrix D

D(:,1) = y      % set y values into column 1 of D

for col=2:n % what is happening here?

for row=1:(n-col+1) % what is happening here?

disp([row, col]) % what is happening here?

numerator = D(row,col-1) - D(row+1,col-1);   % what is happening here?

denominator = x(row) - x(row+col-1); % what is happening here?

D(row,col) = numerator/denominator; % what is happening here?

end

end

D

disp(‘press any key’)

pause

%%%%%%%%%%%%%%%%%%%%%%

% part 2 build p(t) iteratively

d = D(1,:)    % grab row 1 of D

% make our evaluation values of t between x nodes

t = min(x) : 0.01 : max(x) ;   % what is happening here?

% here is the algorithm without a loop

% p0 = d(4)*ones(size(t))

% p1 = d(3)+(t-x(3)).*p0

% p2 = d(2)+(t-x(2)).*p1

% p3 = d(1)+(t-x(1)).*p2

% and so on…..

% here is the algorithm with a loop

p = d(n)*ones(size(t))   % what is happening here?

for k = n-1:-1:1   % what is happening here?

p = d(k) + (t-x(k)).*p % what is happening here?

end

plot (x, y, '*r',t,p); grid on;   % what is happening here? why do we need r t?

disp(‘press any key’)

pause

%%%%%%%%%%%%%%%%%%%

% part 3 build p_deriv while you build p

%%%%%%%%%%%%%%%%%%

p = d(n)*ones(size(t));   % what is happening here?

p_deriv = zeros(size(t));   % what is happening here?

for k = n-1:-1:1   % what is happening here?

% must update p_deriv before you update p

p_deriv = p + (t-x(k)).*p_deriv ; % what is happening here?

p = d(k) + (t-x(k)).*p;   % what is happening here?

end

plot (x, y, '*r',t,p,t,p_deriv); grid on; % what is happening here?

legend('nodes','p(t)','deriv(t)')   % what is happening here?