I want to solve the following system of differntial equations in matlab with my own runge kutty method:
$\frac{dx_{1}{dt}$ = $x_{2}$
$\frac{dx_{2}{dt}$ = A $x_{1} + B $x_{2}$ + asin(Ct)
I wrote
function xdot = NaszModel(x, aa, bb, AA, BB, CC)
a= aa;
A = AA;
B = BB;
C = CC;
xdot = [ x(2)
A*x(1) - B*x(2) + a*sin(C)];
end
function [x, t] = RK(f, x0, t0, T, h)
t = t0:h:T;
nt = numel(t);
nx = numel(x0);
x = nan(nx, nt);
x(:,1) = x0;
for k = 1:nt-1
k1 = h*f(t(k), x(:,k));
k2 = h*f(t(k) + h/3 , x(:,k) + h/3 );
k3 = h*f(t(k) + (2*h)/3, x(:,k) - k1/3 + k2);
k4 = h*f(t(k) + h, x(:,k) + k1 - k2 + k3);
dx = (k1 + 3*k2 + 3*k3 + k4)/8;
x(:,k+1) = x(:,k) + dx;
end
end
a = 1;
A = 0.1;
B = 0.1;
C = 1;
f = @(t,x) NaszModel(x, a, b, A, B, C);
x0 = [1, 0];
t0 = 0;
T = 100;
h = 1;
[x, t] = RK(f, x0, t0, T, h);
plot(t,x);
legend('x', 'v');
plot(x(1,:), x(2,:));
xlabel('x');
ylabel('v(x)');
Everything works fine, but when im trying to add t to sin, i mean: i have in my solution asin(C), but i have to solve eqution with asin(C*t). `
how it should be written to make it works also for asin(Ct)?
You need to pass t
also to the model function, then you can also use it in the ODE. This means that you need to change the interface of the function.
function xdot = NaszModel(t, x, a, b, A, B, C)
xdot = [ x(2)
A*x(1) - B*x(2) + a*sin(C*t)];
end
f = @(t,x) NaszModel(t, x, a, b, A, B, C);