Search This Blog

Forward Interpolation in MATLAB | M-file

Newton's Forward Interpolation: 1) Construct a forward difference table 2) Extract the logic out of the formula and write it into the code Contracting Forward Difference Table: https://youtu.be/DBbZYbJ60pU Contracting Backward Difference Table: https://youtu.be/RJE7EoYhFyw


Code:

% TAKING ALL THE NECESSARY INPUTS

x1= input('Enter starting value of x:  ');

h= input('Intervel:  ');

x2 = input('Ending value of x:  ');

x = x1:h:x2;

% COUNTING THE NUMBER OF ELEMENTS USING "SIZE" COMMAND

% THE NUMBER OF COLUMNS OF "x" IS THE NUMBER OF ELEMENTS

[c,n] = size(x);

for i=1:n

    y(i,1) = input('Enter corresponding values of y:  ');

end

figure(1)

scatter(x,y,'MarkerEdgeColor',[0 .5 .5],...

                'MarkerFaceColor',[0 .7 .7],...

              'LineWidth',1.5)

hold on

% COMPUTING FORWARD DIFFERENCE TABLE

for j=2:n

    for i=1:n-j+1

    y(i,j)= y(i+1,j-1) - y(i,j-1);    

    end

end

fprintf ('\n***Forward difference table***');

fprintf ('\n\tx\t  y\t     del1\tdel2\tdel3');

for i=1:n

    fprintf ('\n % .f',x(i));

    for j=1:n-i+1

        fprintf ('\t    % .f', y(i,j));

    end

end

% INTERPRETING NEWTON'S FORWARD DIFFERENCE FORMULA

x_reqd = input('\nEnter X for which value of y is to be calculated:');

 

u = (x_reqd-x(1))/h;

ans = y(1);

for i=1:n-1

term=1;

    for j=1:i

        % FINDING THE VALUE OF u TERMS

        term=term*(u-j+1)/j;

    end

    % SUMMING UP THE CALCULATED VALUES MULTIPLIED BY THE DIFFERENCES AND GIVES THE FINAL RESULT

    ans = ans + term*y(1, i+1);

end

 

fprintf('\n\n\n Value of Y at(x = %f) = %.4f',x_reqd,ans);

scatter(x_reqd,ans,'MarkerEdgeColor',[0 .95 .95],...

                'MarkerFaceColor',[0 .99 .99],...

              'LineWidth',.5)

 



Free Codes: youtube.com/castorclasses Free Support: castorclasses2014@gmail.com Live Support: t.me/matlabcastor Like us: https://www.facebook.com/matlabirawen Join us: https://www.facebook.com/groups/MATLA... MATLAB Book for the beginner: https://amzn.to/3fTfmTa

No comments