This post shows one way to linearize a nonlinear state equation at a steady state setpoint in MATLAB. It is assumed that a function
ode.m exists in which the state equation is implemented:

ode.m

MATLAB

1

2

3

4

5

6

7

8

9

10

functiondx=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:

steadystate.m

MATLAB

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

closeall

clearvariables

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: .

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

linearization.m

MATLAB

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

% 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',[41]);

u_sym=sym('u',[21]);

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
and the input matrix which could be used in a linear model approximation.

## Leave a Reply