Advertisement
BOT_Yokel

2018 Practice Test 2 - IVP with Regular EM

Nov 29th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.43 KB | None | 0 0
  1. A = [0, 1; (-19/4) (-10)];
  2. n = [50, 75, 100, 250, 500];
  3. x_range = 0:10/10000:10;
  4. y_correct = ones(1, length(x_range));
  5.  
  6. %Creates a vector y_correct with the values for the analytical solution,
  7. %using dx = 1/1000
  8. for j = 1:length(x_range)
  9.     y_correct(j) = (-1*(19/2)*exp(-1*x_range(j)/2)) + 0.5*exp((-19/2)*x_range(j));
  10. end
  11.  
  12. for i = 1:length(n)
  13.     EM(n(i))
  14.     xlabel('Time')
  15.     ylabel('y(t)')
  16.     title('Solving an IVP for y(t) using varying n')
  17. end
  18.  
  19. plot(x_range, y_correct, 'DisplayName', 'Analytical Solution')
  20. legend Show
  21.  
  22.  
  23. function EM(n)
  24.     dt = 10/n;
  25.     %Range of values, xi
  26.     t_range = 0:dt:10;
  27.     %Creates an array of zeros 2 high, and n+1 wide
  28.     y = zeros(2, n+1);
  29.     %Assigns the initial values to the matrix, representing the intial
  30.     %values for y(t) and y'(t)
  31.     y(:, 1) = [-9, 0];
  32.     %Creating matrix A
  33.     A = [0, 1; (-19/4) (-10)];
  34.     %Applying the transformation A to [y; y'], which is [y'; y'']
  35.     %When multiplied by dt, this allows us to find our next value of y(t)
  36.     %and y'(t) respectively, when added to y(t-1) and y'(t-1) respectively
  37.     for j = 2:length(t_range)
  38.         y(:, j) = y(:, j-1) + dt.*(A*y(:, j-1));
  39.     end
  40.     plot(t_range, y(1, 1:n+1),'DisplayName',strcat('n=',num2str(n)))
  41.     grid on
  42.     hold on
  43. end
  44. %I recommend using n = 100, as it reproduces the analytical solution with a
  45. %similar shape and nearly identical values, if not for a deviation of a few
  46. %tenths
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement