maestro252

nlbvpfd2

May 16th, 2017
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.32 KB | None | 0 0
  1. % Program 7.1 Nonlinear Finite Difference Method for BVP
  2. % Uses Multivariate Newton?s Method to solve nonlinear equation
  3. % Inputs: interval inter, boundary values bv, number of steps n
  4. % Output: solution w
  5. % Example usage: W=nlbvpfd([0 1], [1 4], 40)
  6. function w=nlbvpfd2(inter,bv,n)
  7. x = linspace(0, 1, n);
  8. a=inter(1); b=inter(2); ya=bv(1); yb=bv(2);
  9. h=(b-a)/(n+1); % h is step size
  10. w=zeros(n,1); % initialize solution array w
  11. for i=1:20 % loop of Newton step
  12.   w=w-jac(w,inter,bv,n)\f(w,inter,bv,n);
  13. end
  14. plot([a a+(1:n)*h b],[ya w' yb]); % plot w with boundary data
  15.  
  16. function y=f(w,inter,bv,n)
  17. x = linspace(0, 1, n);
  18. y=zeros(n,1);h=(inter(2)-inter(1))/(n+1);
  19. y(1)=w(2)-2*w(1)+x(1)^2*w(2)-2*x(1)^2*w(1)+x(1)^2-2*h*w(2)-2*h-6*w(1);
  20. y(n)=(-4/3)-2*w(n)+w(n-1)+x(n)^2*(-4/3)-2*x(n)^2*w(n)+x(n)^2*w(n-1)-2*h*(-4/3)-2*h*w(n-1)-6*w(n);
  21. for i=2:n-1
  22.   y(i)=w(i+1)-2*w(i)+w(i-1)+x(i)^2*w(i+1)-2*x(i)^2*w(i)+x(i)^2*w(i-1)-2*h*w(i+1)-2*h*w(i-1)-6*w(i);
  23. end
  24.  
  25.  
  26. function a=jac(w,inter,bv,n)
  27. x = linspace(0, 1, n);
  28. a=zeros(n,n);h=(inter(2)-inter(1))/(n+1);
  29. a(n,n) = -2-2*x(n)^2-6;
  30. a(1,1) = -2-2*x(1)^2-6;
  31. for i=2:n-1
  32.   a(i,i)=-2-2*x(i)^2-6;
  33. end
  34. a(1,2) = 1+x(1)^2-2*h;
  35. a(2,1) = 1+x(2)^2-2*h;
  36. a(n-1,n) = 1+x(n-1)^2-2*h;
  37. a(n,n-1) = 1+x(n)^2-2*h;
  38. for i=2:n-2
  39.   a(i,i+1)=1+x(i)^2-2*h;
  40.   a(i+1,i)=1+x(i)^2-2*h;
  41. end
Add Comment
Please, Sign In to add comment