Runge-Kutta 2
4 views (last 30 days)
Show older comments
Nagy Csaba Norbert
on 21 Apr 2021
Commented: Nagy Csaba Norbert
on 22 Apr 2021
Hi, i have a homwork for school including the Runge-Kutta 2.
I have to do it in symbolic, i would be very greatfull if someone can help me in this taks.
intervalmin = 0;
intervalmax = 1;
h1 = 0.1;
g = 0.02;
X0 = [0, 0];
[t1, x1] = fuggveny(intervalmin, X0(1), X0(2), h1, intervalmax);
[t2, x2] = fuggveny(intervalmin, X0(1), X0(2), g, intervalmax);
syms x(t);
dz = diff(x,t);
ode = diff(x,t,2) + 5.*diff(x,t,1) + 4.*x(t) == 3 - 2.*t - t.^2;
cond1 = x(0) == 1;
cond2 = dz(0) == 1;
RK2(t) = dsolve(ode,cond1,cond2);
plot(t1, x1, '-y');
hold on;
plot(t2, x2, '--r');
hold on;
fplot(RK2,'-*b');
hold on
legend('h=0.1','h=0.02','ode')
ax = gca;
ax.XAxisLocation = 'origin';
ax.YAxisLocation = 'origin';
grid on;
function dX = f(t, x1, x2)
X1 = x2;
X2 = -5.*x2 + 4.*x1 + 3 - 2.*t - t.^2;
dX = [X1, X2];
end
function [t, x] = fuggveny(intervalmin, X0_1, X0_2, h, intervalmax)
t = (intervalmin:h:intervalmax);
X1 = zeros(size(t));
X2 = zeros(size(t));
X1(1) = X0_1;
X2(1) = X0_2;
for i = 1:1:length(t) - 1
k1 = f(t(i), X1(i), X2(i));
k2 = f(t(i) + h/2, X1(i) + h/2 * k1(1), X2(i) + h/2 * k1(2));
k3 = f(t(i) + h, X1(i) - h*k1(1) + 2*h*k2(1), X2(i) - h*k1(2) + 2*h*k2(2));
X1(i + 1) = X1(i) + h/6 * (k1(1) + 4*k2(1) + k3(1));
X2(i + 1) = X2(i) + h/6 * (k1(2) + 4*k2(2) + k3(2));
end
x = X1;
end
0 Comments
Accepted Answer
James Tursa
on 21 Apr 2021
Edited: James Tursa
on 21 Apr 2021
The + 4.*x1 should be - 4.*x1 in your derivative function. Also, using both X1 and x1 and X2 and x2, even though MATLAB is case sensitive and these are different variables, is confusing to read. Suggest using different names such as x1dot and x2dot, or even just form the derivative vector directly. E.g.,
function dX = f(t, x1, x2)
dX = [x2; -5.*x2 - 4.*x1 + 3 - 2.*t - t.^2];
end
Also, just to clarify, you are asked to solve this both symbolically and numerically?
Not sure why the assignment says Runge-Kutta II when it looks like you are using a 3rd order method.
3 Comments
More Answers (0)
See Also
Categories
Find more on Assumptions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!