How can i solve this problem in MATLAB?
I have this non linear system:
$\frac{dx_1}{dt}=5sin(6t)-x_1$
$\frac{dx_2}{dt}=3x_1x_2-2x_2+1$
$y=x_2$
Initial condition are the following:
$x(0)=[-2,-1.5]^T$
Compute $y(t)$ and $y(t=12)$
How can i solve this problem in MATLAB?
I have this non linear system:
$\frac{dx_1}{dt}=5sin(6t)-x_1$
$\frac{dx_2}{dt}=3x_1x_2-2x_2+1$
$y=x_2$
Initial condition are the following:
$x(0)=[-2,-1.5]^T$
Compute $y(t)$ and $y(t=12)$
On
To solve your system numerically you must first define it as a function that is compatible to the usual solvers:
function dx = nonlinear_system(t, x)
dx = zeros(2, 1);
dx(1) = 5*sin(6*t) - x(1);
dx(2) = 3*x(1)*x(2) - 2*x(2) + 1;
end
Then you can use the usual solvers:
t = linspace(0, 12, 1000);
x0 = [-2; -1.5];
[~, X] = ode45(@nonlinear_system, t, x0);
y = X(:, 2);
plot(t, y);
y(end)
This creates a plot of the trajectory of $y$:
It also displays the computed value of $y(12) \approx 0.5651$ for your initial conditions.
For systems with inputs, it gets a bit more complicated. There are basically two solutions that you can use. Assume your system is now
$$ \begin{align} \dot{x}_1 &= 5 \sin(6 t) - x_1 \\ \dot{x}_2 &= 3 x_1 x_2 - 2 x_2 + 1 + u \end{align} $$
First solution: Implement your input $u$ as a function of time directly in your nonlinear system function. Assume you want a step from $0$ to $0.1$ at $t = 6$. In code, this would look like
function dx = nonlinear_system(t, x)
if t >= 6
u = 0.1;
else
u = 0;
end
dx = zeros(2, 1);
dx(1) = 5*sin(6*t) - x(1);
dx(2) = 3*x(1)*x(2) - 2*x(2) + 1 + u;
end
The calling script does not need to be modified in this case.
This is very easy for "simple" input functions like in this example. Problem is, that it can get very tedious to do for arbitrary $u$. So you can use a different solution instead.
Second solution: Feed $u$ from external into the function and interpolate it within the function. Here is a code sample:
function dx = nonlinear_system(t, x, tvec, uvec)
u = interp1(tvec, uvec, t);
dx = zeros(2, 1);
dx(1) = 5*sin(6*t) - x(1);
dx(2) = 3*x(1)*x(2) - 2*x(2) + 1 + u;
end
In this case you need to modify the calling script:
tvec = linspace(0, 12, 1000);
uvec = zeros(length(tvec), 1);
uvec(t >= 6) = 0.1;
x0 = [-2; -1.5];
nsys = @(t, x)nonlinear_system(t, x, tvec, uvec);
[~, X] = ode45(nsys, tvec, x0);
yvec = X(:, 2);
plot(tvec, yvec);
hold on;
plot(tvec, uvec);
yvec(end)
This is way more flexible but a bit more expensive computationally. You also must take enough intermediate points (here I took 1000) so that the approximation is good.
You can use the IF method as follows $$ \dot x_2+ x_2(2-3x_1) = 1 $$ hence $$ \big( x_2(t)e^{\int 2-3x_1(t) dt} \big)' = e^{\int 2-3x_1(t) dt} $$ from which $$ x_2(t) = x_2(0)e^{-\int_0^t 2-3x_1(s)ds} + \int_0^t e^{\int_0^s 2-3x_1(u)du -\int_0^t 2-3x_1(v)dv} ds$$ follows. The first equation can be written as $$ \big(x_1(t)e^{t}\big)' = 5\sin(6t)e^{t} $$ so $$ x_1(t) = x_1(0)e^{-t} + \int_0^te^{s-t} 5\sin(6s)ds $$