Advertisement
BOT_Yokel

2018 Practice Test 1

Nov 29th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.37 KB | None | 0 0
  1. %Constants
  2. y0 = 0;
  3. y1 = 1;
  4. n = 2:2:10;
  5. x_range = 0:1/1000:1;
  6.  
  7. %Creates a vector y_correct with the values for the analytical solution,
  8. %using dx = 1/1000
  9. for j = length(x_range)
  10.     y_correct = ones(1, length(x_range));
  11.     y_correct(j) = 1.3888*exp(x_range(j)) + 0.6112*exp(-x_range(j)) - x_range(j)^2 -2;
  12. end
  13.  
  14. for i = n
  15.     BVPsolver(i);
  16. end
  17.  
  18. plot(x_range, y_correct)
  19.  
  20. legend('n=2', 'n=4', 'n=6', 'n=8', 'n=10', 'Analytical')
  21. xlabel('x')
  22. ylabel('y(x)')
  23. title('BVP Problem Solution')
  24.  
  25. function BVPsolver(n)
  26.     %Creating constants for current value of n
  27.     dx = 1/n;
  28.     range = 0:dx:1;
  29.     %Creating matrix b out of a ones array with height of n-1, width 1
  30.     b = ones(n-1, 1);
  31.     %Multiplying all ones in b by dx^4
  32.     b = b.*(dx^4);
  33.     %The pattern found in b, for y(nΔx), b = n^2*Δx^4, so we're just
  34.     %multiplying by n^2 here
  35.     for j = 1:(n-1)
  36.         b(j) = b(j)*j^2;
  37.     end
  38.     %Subtracting y1 from the last value of b
  39.     b(end) = b(end)-1;
  40.     %Constants for the diagonals of matrix A
  41.     k1 = 1;
  42.     k2 = -2-dx^2;
  43.     k3 = 1;
  44.     %Creating a matrix with diagonals of the constants above, and all other
  45.     %values = 0
  46.     A = diag(ones(1, n-2).*k1, 1) + diag(ones(1, n-1).*k2) + diag(ones(1, n-2).*k1, -1);
  47.     y = [0;mldivide(A, b);1];
  48.     plot(range, y, 'DisplayName',strcat('n=',num2str(n)))
  49.     grid on
  50.     hold on
  51. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement