Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.74 KB | None | 0 0
  1. function yInt = NewtonInterpolation(x, y, xx)
  2. % NewtonInterpolation(x, y, xx): Uses an (n-2)order Newton interpolating
  3. % polynomial based on n data points (x,y)
  4. % to determine a value of a dependent variable (yInt)
  5. % at a given value of the independent variable, xx
  6. % input:
  7. % x - independent variable (row matrix)
  8. % y - dependent variable (row matrix)
  9. % xx - value of independent variable at which interpolation is calculated
  10. % output:
  11. % yInt - interpolated value of dependent variable
  12.  
  13. %compute
  14. n = length(x);
  15. if length(y) ~= n
  16.     error('x and y must have the same length');
  17. end
  18. b = zeros(n,n);
  19. %assign dependent variables to the first column of b
  20. b(:,1)=y(:); %ensures that y is a column vector
  21. for j = 2:n
  22.     for i = 1:n-j+1
  23.         b(i,j) = (b(i+1,j-1)-b(i,j-1))/(x(i+j-1)-x(i));
  24.     end
  25. end
  26.  
  27. fprintf('\n\t\t\t\t\t\t\tx\t\t\t\t\t\t\tfx');
  28. for k = 1:n-1
  29.    
  30.     if k==1
  31.         fprintf('%30.fst',k);
  32.     end
  33.     if k==2
  34.        fprintf('%30.fnd',k);
  35.     end
  36.     if k==3
  37.         fprintf('%30.frd',k);
  38.     end
  39.     if k>3
  40.         fprintf('%30.fth',k);
  41.     end
  42.    
  43. end
  44. l = b';
  45. v = [x;l];
  46. result = v';
  47. for k = 1:n
  48.     fprintf('\n');
  49.     fprintf('%30.5f\t',result(k,:));
  50. end
  51.  
  52. %uses the finite divided difference to interpolate
  53. xt = 1;
  54. yInt = b(1,1);
  55.  
  56. fprintf('\n\n\ty =');
  57. fprintf('% 10.5f\t',b(1,1));
  58.  
  59. for j = 1:n-1
  60.     xt = xt*(xx-x(j));
  61.     yInt = yInt + b(1,j+1)*xt;
  62.         fprintf('+');
  63.         fprintf('% 10.5f*(x-%f)',b(1,j+1),x(j));
  64.     if j == 1
  65.         fprintf('\n\t\t\t\t\t');
  66.     end
  67.     if j>1
  68.         k = 1;
  69.         p=j;
  70.         while k<p
  71.             fprintf('*(x-%f)',x(p-1));
  72.             p = p-1;
  73.         end
  74.         if j < n-1
  75.             fprintf('\n\t\t\t\t\t');
  76.         end
  77.     end
  78. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement