MATLAB: How to integrate state-space equations in 6DOF with ode45

6dofode45state-space

I have a state-space representation of a system in six degrees of freedom, and have used the forward Euler method to update the state, as seen in the attached script. However, this gave an inaccurate result, so I want to change to the Runge-Kutta method. I have tried to use the ode45 function, but am unsure about the syntax.
Here is my attempt (with the rest of the code unchanged):
[t,x]=ode45(@(t,x) f(t, x, N, u, A, B),t,x0);
for k=1:N-1 % need -1 here so that x(n+1) does not lead to an index>N
for i = 1:1:12
y(i,k+1)=C(i,:)*x(:,k+1)+D(i,:)*u(:,k+1); % y is an output based on x and u, so is not integrated
end
% Calculate new version of A
A=calcA(x(:,k+1));
end
function [t, x]=f(t, x, N, u, A, B)
for k=1:N-1
for i = 1:1:12
x(i,k+1)=A(i,:)*x(:,k)+B(i,:)*u(:,k);
end
end
end
I get the following errors:
Error using odearguments (line 95) @(T,X)F(T,N,X,U,A,B) returns a vector of length 1, but the length of initial conditions vector is 12. The vector returned by @(T,X)F(T,N,X,U,A,B) and the initial conditions vector must have the same number of elements.
Error in ode45 (line 115) odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Error in newsys4 (line 63) [t,x]=ode45(@(t,x) f(t, x, N, u, A, B),t,x0);
I think the correct length is 12, since there are 12 states. How can I make @(T,X)F(T,N,X,U,A,B) return a vector of length 12?

Best Answer

Your derivative function f should only be returning the derivative of x, not t also. I.e., the signature of f should be something like this:
function dx = f(t, x, N, u, A, B)
dx = _______; % Add code here to calculate the derivative of x at time t
end
The way you have it now, ode45 is simply getting as a result of the f call the first returned argument, t, which is a scalar (1 element). Hence the error.