Skip to content
XeveAbout code and problems

Linearize nonlinear state space equation in MATLAB at steady state setpoint

July 30, 2018 1 comment Article Uncategorized nspo

This post shows one way to linearize a nonlinear state equation \dot{x} = f(x,u) at a steady state setpoint (x_0, u_0) in MATLAB. It is assumed that a function ode.m exists in which the state equation is implemented:

function dx = ode(t, x, u)
    % example ODE
    dx1 = tan(x(4)) * x(2) + 2*u(2) - 1;
    dx2 = x(1) - sin(x(2));
    dx3 = 13 * x(4) + u(1) + 1;
    dx4 = 2*x(1);

    dx = [dx1; dx2; dx3; dx4];
end

If the desired setpoint is not known, a steady state setpoint could be calculated with a desired objective function J in CasADi like this:

close all
clear variables
clc

import casadi.*;
ocp = casadi.Opti();

nx = 4;
nu = 2;

X = ocp.variable(nx);
U = ocp.variable(nu);


% dynamics
ocp.subject_to([0;0;0;0] == ode(0, X, U));

% add cost function to minimize input
J = U(1,1)^2 + U(2,1)^2;
ocp.minimize( J );

% specify solver
ocp.solver( 'ipopt' );

% solve OCP 
sol = ocp.solve();

x_ss = sol.value(X);
u_ss = sol.value(U);

The example yields the following setpoint: x_0 = [0, 0, 0, -0.0769]^\mathrm{T}, u_0 = [0, 0.5]^\mathrm{T}.

Now we can linearize the model at the setpoint using the MATLAB Symbolic Math Toolbox:

% setpoint
t = 0;
x=[0; 0; 0; -0.0769]; % state
u=[0;0.5]; % control input

% for eval later
x1 = x(1); x2 = x(2); x3 = x(3); x4 = x(4);
u1 = u(1); u2 = u(2);

% symbolic vars
x_sym = sym('x', [4 1]);
u_sym = sym('u', [2 1]);
ode_sym = ode(t,x_sym,u_sym);

% calculate system and input matrices
Jac_x = jacobian(ode_sym, x_sym);
A = eval(subs(Jac_x));

Jac_u = jacobian(ode_sym, u_sym);
B = eval(subs(Jac_u));

This linearization yields the system matrix A = \begin{bmatrix}  0& -0.0771& 0& 0 \\  1& -1& 0& 0 \\  0& 0& 0& 13 \\  2& 0& 0& 0  \end{bmatrix}
and the input matrix B = \begin{bmatrix}  0& 2\\  0& 0\\  1& 0\\  0& 0  \end{bmatrix} which could be used in a linear model approximation.

Tags: CasADi, linearization, matlab, state space

1 comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Calendar

July 2018
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
3031  
« May   Apr »

Archives

  • January 2021
  • May 2020
  • April 2020
  • July 2018
  • May 2018
  • April 2018
  • March 2018
  • September 2015
  • August 2015
  • June 2015
  • March 2015
  • February 2015
  • September 2014
  • March 2013

Categories

  • Uncategorized

Copyright Xeve 2022 | Theme by ThemeinProgress | Proudly powered by WordPress