Advertisement
Guest User

Untitled

a guest
Sep 19th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.43 KB | None | 0 0
  1. function RungeKuttaExample()
  2.     %this function solves the ode dQ/dt = cos(t) - lambda*Q for the initial condition
  3.     %Q = (lambda*cos(t)+sin(t))/(1+lambda^2) at t=0 using a fourth order Runge-Kutta scheme.
  4.  
  5.     lambda = 2;
  6.  
  7.     %timestep to be used
  8.     t_step = 12*pi/300;
  9.  
  10.     %number of timesteps
  11.     n_steps = 301;
  12.  
  13.     %initalise a vector which is the required length
  14.     Q = zeros(1, n_steps);
  15.  
  16.     %set the initial condition
  17.     Q(1) = lambda/(1+lambda^2);
  18.  
  19.     %start at time = 0
  20.     t = 0;
  21.  
  22.     %step through each of the timesteps
  23.     for i = 2:n_steps
  24.         k1 = t_step*func(t, Q(i-1), lambda);
  25.         k2 = t_step*func(t + t_step/2, Q(i-1) + k1/2, lambda);
  26.         k3 = t_step*func(t + t_step/2, Q(i-1) + k2/2, lambda);
  27.         k4 = t_step*func(t + t_step, Q(i-1) + k3, lambda);
  28.  
  29.         %calculate the next step
  30.         Q(i) = Q(i-1) + (k1+2*k2+2*k3+k4)/6;
  31.  
  32.         %move onto next timestep ready for the next loop
  33.         t = t + t_step;
  34.     end
  35.  
  36.     %set the time axis
  37.     t_axis = 0:t_step:(12*pi);
  38.     %plot numerical output
  39.     plot(t_axis, Q, 'k')
  40.    
  41.     %plot analytical solution
  42.     %set the time axis
  43.     t_axis = 0:0.01:(12*pi);
  44.     Q_real = (lambda*cos(t_axis)+sin(t_axis))/(1+lambda^2);
  45.     plot(t_axis, Q_real, 'm*')
  46.    
  47.  
  48. end
  49.  
  50. function [out] = func(t, Q, lambda)
  51.     %this function evaluates the right hand side of the governing equation.
  52.     out = cos(t) - lambda*Q;
  53. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement