1

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 !

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51
etienne
  • 13
  • 4
  • Have a look [here](http://www.math.mcgill.ca/gantumur/math579w10/matlab/rk4.m). – Jeroen Heier Sep 05 '18 at 19:12
  • Thanks Jeroen. I've edited my post taking into consideration your link. As you can see I'm struggling to write the function properly. Cheers. – etienne Sep 07 '18 at 20:52
  • Did you test your integration routine with a simple test example like f(x,y)=x, f(x,y)=y or similar? Show your function f as that is probably where the problem is. – Lutz Lehmann Sep 11 '18 at 08:56
  • Thanks @LutzL. The code is [here](https://1drv.ms/f/s!AlE-fessx_K3gwBIszRrbj81EgNn). The main loop is in _Tacking.m_ and the Runge-Kutta function in _RK4.m_. I know the code has been used in the past, but it's the RK4 function that I'm struggling to write properly. Thanks ! – etienne Sep 13 '18 at 14:00

0 Answers0