Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function RungeKuttaExample()
- %this function solves the ode dQ/dt = cos(t) - lambda*Q for the initial condition
- %Q = (lambda*cos(t)+sin(t))/(1+lambda^2) at t=0 using a fourth order Runge-Kutta scheme.
- lambda = 2;
- %timestep to be used
- t_step = 12*pi/300;
- %number of timesteps
- n_steps = 301;
- %initalise a vector which is the required length
- Q = zeros(1, n_steps);
- %set the initial condition
- Q(1) = lambda/(1+lambda^2);
- %start at time = 0
- t = 0;
- %step through each of the timesteps
- for i = 2:n_steps
- k1 = t_step*func(t, Q(i-1), lambda);
- k2 = t_step*func(t + t_step/2, Q(i-1) + k1/2, lambda);
- k3 = t_step*func(t + t_step/2, Q(i-1) + k2/2, lambda);
- k4 = t_step*func(t + t_step, Q(i-1) + k3, lambda);
- %calculate the next step
- Q(i) = Q(i-1) + (k1+2*k2+2*k3+k4)/6;
- %move onto next timestep ready for the next loop
- t = t + t_step;
- end
- %set the time axis
- t_axis = 0:t_step:(12*pi);
- %plot numerical output
- plot(t_axis, Q, 'k')
- %plot analytical solution
- %set the time axis
- t_axis = 0:0.01:(12*pi);
- Q_real = (lambda*cos(t_axis)+sin(t_axis))/(1+lambda^2);
- plot(t_axis, Q_real, 'm*')
- end
- function [out] = func(t, Q, lambda)
- %this function evaluates the right hand side of the governing equation.
- out = cos(t) - lambda*Q;
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement