Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- A = [0, 1; (-19/4) (-10)];
- n = [50, 75, 100, 250, 500];
- x_range = 0:10/10000:10;
- y_correct = ones(1, length(x_range));
- %Creates a vector y_correct with the values for the analytical solution,
- %using dx = 1/1000
- for j = 1:length(x_range)
- y_correct(j) = (-1*(19/2)*exp(-1*x_range(j)/2)) + 0.5*exp((-19/2)*x_range(j));
- end
- for i = 1:length(n)
- EM(n(i))
- xlabel('Time')
- ylabel('y(t)')
- title('Solving an IVP for y(t) using varying n')
- end
- plot(x_range, y_correct, 'DisplayName', 'Analytical Solution')
- legend Show
- function EM(n)
- dt = 10/n;
- %Range of values, xi
- t_range = 0:dt:10;
- %Creates an array of zeros 2 high, and n+1 wide
- y = zeros(2, n+1);
- %Assigns the initial values to the matrix, representing the intial
- %values for y(t) and y'(t)
- y(:, 1) = [-9, 0];
- %Creating matrix A
- A = [0, 1; (-19/4) (-10)];
- %Applying the transformation A to [y; y'], which is [y'; y'']
- %When multiplied by dt, this allows us to find our next value of y(t)
- %and y'(t) respectively, when added to y(t-1) and y'(t-1) respectively
- for j = 2:length(t_range)
- y(:, j) = y(:, j-1) + dt.*(A*y(:, j-1));
- end
- plot(t_range, y(1, 1:n+1),'DisplayName',strcat('n=',num2str(n)))
- grid on
- hold on
- end
- %I recommend using n = 100, as it reproduces the analytical solution with a
- %similar shape and nearly identical values, if not for a deviation of a few
- %tenths
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement