I'm trying to solve a system of equations defined in a function ('f') using a 4th order Runge-Kutta method, taking into account a PD controller on a variable ('c').
Here is how my code looks like so far:
t_f = 100; % simulation end time
h = 0.1; % sample time
K = 1; % controller gain
Td = 10; % controller derivative time
x = [...]; % initial conditions
N = round(t_f/h); % number of samples
xout = zeros(N+1,length(x)+2); % memory allocation
for i=1:N+1
time = (i-1)*h; % simulation time
a = x(1);
if (a<10)
a_ref = 1; % desired 'a' value
c = K*((a-a_ref)+Td); % controller
[x v] = RK4('f',x,[c 0],h,i);
xout(i,:) = [time,x',v]
I'm struggling to write the RK4 function to solve the equations from 'f', also making sure the controller is used.
Any ideas would be very much appreciated.
Many thanks.
EDIT:
Following this link, I've now written a separate function that looks like this:
function [x v] = RK4(f,a,t_f,x,N)
a = 0;
t_f = 100;
h = 0.1;
N = round(t_f/h);
% h = (t_f - a) / N;
halfh = h / 2;
x(1,:) = x;
v(1) = a;
h6 = h/6;
for i = 1 : N
v(i+1) = v(i) + h;
vh2 = v(i) + halfh;
s1 = f(v(i), x(i,:));
s2 = f(vh2, x(i,:) + halfh * s1);
s3 = f(vh2, x(i,:) + halfh * s2);
s4 = f(v(i+1), x(i,:) + h * s3);
x(i+1,:) = x(i,:) + (s1 + s2+s2 + s3+s3 + s4) * h6;
end;
When running the main script this returns the error at line starting with "s1 = ..." in the for loop:
Subscript indices must either be real positive integers or logicals.
Plus, I'm not sure if the controller input needs to be incorporated in this function.
Sorry if this is straightforward, but I'm struggling to get my head around it.
Thanks.
EDIT 2:
The latest version of the code can be found here. The main loop is in Tacking.m (calling other functions) and the Runge-Kutta integration is in RK4.m.
I've tried several formulations but, as you can see, I'm not sure how to write it properly in this case.
Note: all the other functions were previously used, it's the "solver" that I need to get sorted.
Any help would be welcomed. Thanks !