Runge Kutta for system of eqs

2 次查看(过去 30 天)
jojo
jojo 2019-11-24
编辑: jojo 2019-11-26
I would like to approxiamte and plot the following system of equations: { u' = v ; v' = -4*u' - 5 u} using the Runge Kutta method.
I am able to plot it for the second equation, but having difficulties incorporating the u' = v to reflect the full system.
the exact solution I am comparing to is: x(t) = 3.*exp(-2.*t) .* cos(t) + exp(-2.*t) .* sin(t) corresponding to equation: ??′′(??)+4??′(??)+5??(??)=0 with ??(0)=3 and ??′(0)=−5. as initial conditions.
clear all
close all
clc
h = .1; % set the step size
x = 0:h:5; % set the interval of x
y = zeros(1,length(x));
y(1) = 3; % set the intial value for y
n = length(x)-1;
y_dot =@(x,y)(-4*x-5*y); %insert function to be solved
for i = 1:n
k1 = y_dot(x(i),y(i));
k2 = y_dot(x(i)+.5*h,y(i)+.5*k1*h);
k3 = y_dot(x(i)+.5*h,y(i)+.5*k2*h);
k4 = y_dot(x(i)+h,y(i)+k3*h);
y(i+1) = y(i)+((k1+2*k2+2*k3+k4)/6)*h;
end
Please explain the any updates yu make, since I am new to ML and need to conceptually understand the fundamentals.
Thanks.
  3 个评论
jojo
jojo 2019-11-25
Yes. ?′′(?)+4?′(?)+5?(?)=0 this is the full equation.
jojo
jojo 2019-11-25
编辑:jojo 2019-11-25
Just having difficulty breaking it into a system of equations and incorporate it into the code

请先登录,再进行评论。

回答(1 个)

darova
darova 2019-11-25
I wrote function in the way similar to ode45
y_dot = @(x,dx)[dx; -4*dx-5*x]; %insert function to be solved
for i = 1:n
k1 = y_dot(x(i),dx(i));
k2 = y_dot(x(i)+h/2*k1(1), dx(i)+h/2*k1(2));
k3 = y_dot(x(i)+h/2*k2(1), dx(i)+h/2*k2(2));
k4 = y_dot(x(i)+k3(1), dx(i)+k3(2));
u = (k1+2*k2+2*k3+k4)*h/6;
% shorter form
% k1 = h/2*y_dot(x(i),dx(i));
% k2 = h/2*y_dot(x(i)+k1(1), dx(i)+k1(2));
% k3 = h* y_dot(x(i)+k2(1), dx(i)+k2(2));
% k4 = h* y_dot(x(i)+k3(1), dx(i)+k3(2));
% u = (2*k1+4*k2+2*k3+k4)/6;
x(i+1) = x(i) + u(1);
dx(i+1) = dx(i) + u(2);
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by