Segway controller in MATLAB: inverted pendulum and LQR
Segway controller in MATLAB: model of the inverted pendulum on a cart, linearisation, controllability, pole placement and LQR, with a script.
https://www.electronics-engineering.com/en/designing-a-controller-for-an-inverted-pendulum-on-a-cart/

A Segway keeps its balance like an inverted pendulum: to a first approximation it can be modelled as an inverted pendulum on a cart. In this article we see how to write the equations of the system, linearise them around the vertical position, check controllability and design a state-feedback controller in MATLAB, first with pole placement and then with the LQR regulator. At the end you will find a complete script and three videos that explain the same steps.
The model of the inverted pendulum on a cart
The system is a cart of mass \(M\) that moves along a line, pushed by a force \(u\), with a rod hinged on top of it. We use a simple model: mass \(m\) concentrated at the end of a massless rigid rod of length \(L\), no friction. The variables are the position of the cart \(x\) and the angle \(\theta\) of the rod with respect to the vertical (\(\theta=0\) with the pendulum up, positive towards increasing \(x\)). With the Lagrange equations one obtains
\[ (M+m)\,\ddot{x}+mL\,\ddot{\theta}\cos\theta-mL\,\dot{\theta}^2\sin\theta=u \]
\[ L\,\ddot{\theta}+\ddot{x}\cos\theta-g\sin\theta=0 \]
It is a nonlinear, time-invariant system. A real Segway is an inverted pendulum on wheels, with motors that apply a torque to the wheels instead of a force to the cart, but the structure of the problem and the design method are the same.
The first video derives the equations of motion of the classic inverted pendulum.
Linearisation and the state-space model
Around the equilibrium with the pendulum vertical (\(\theta\approx 0\), \(\dot{\theta}\approx 0\)) we set \(\sin\theta\approx\theta\), \(\cos\theta\approx 1\) and neglect \(\dot{\theta}^2\). With the state \(z=[x,\ \dot{x},\ \theta,\ \dot{\theta}]^T\) we obtain the linear model \(\dot{z}=Az+Bu\) with
\[ A=\begin{bmatrix}0 & 1 & 0 & 0\\ 0 & 0 & -\dfrac{mg}{M} & 0\\ 0 & 0 & 0 & 1\\ 0 & 0 & \dfrac{(M+m)g}{ML} & 0\end{bmatrix}, \qquad B=\begin{bmatrix}0\\ \dfrac{1}{M}\\ 0\\ -\dfrac{1}{ML}\end{bmatrix} \]
The eigenvalues of \(A\) are \(0\), \(0\) and \(\pm\sqrt{(M+m)g/(ML)}\): the positive one says that, without control, the pendulum falls. With \(M=5\) kg, \(m=1\) kg, \(L=2\) m and \(g=9{,}81\) m/s² the unstable eigenvalue is about 2.43 s⁻¹.
Controllability
Before designing the controller we must check that the system is controllable, that is that the controllability matrix
\[ \mathcal{C}=\begin{bmatrix}B & AB & A^2B & A^3B\end{bmatrix} \]
has rank 4, equal to the number of states. In MATLAB, rank(ctrb(A,B)) is enough. For the pendulum on a cart the rank is 4 for any positive value of the parameters: with the force on the cart alone both the position and the angle can be controlled.
State feedback
The controller is a state feedback \(u=-K(z-z_{ref})\), where \(z_{ref}\) is the desired equilibrium (for example the cart at rest at \(x=1\) m with the pendulum vertical). The closed-loop system has matrix \(A-BK\) and the design consists in choosing \(K\) so that its eigenvalues all have negative real part.
Pole placement
With place(A,B,p) the closed-loop poles are imposed directly. Poles further to the left give a faster response but require larger forces, and the system becomes more sensitive to sensor noise and to model errors. The second video shows this trade-off.
LQR regulator
The linear quadratic regulator (LQR) chooses \(K\) by minimising the cost
\[ J=\int_0^{\infty}\left(z^TQz+u^TRu\right)dt \]
The matrix \(Q\) weighs the deviations of the state (how much we care that position and angle return to zero quickly), \(R\) weighs the control effort (how much force we are willing to use). Increasing \(Q\) makes the system faster, increasing \(R\) makes it gentler and saves energy. In MATLAB: K = lqr(A,B,Q,R).
Complete MATLAB script
The script builds the linear model, checks stability and controllability, computes the gains with place and with lqr, and simulates the LQR controller on the nonlinear model, starting with the pendulum tilted by 0.2 rad (about 11°) and bringing the cart to \(x=1\) m. Local functions at the end of a script are allowed by MATLAB R2016b onwards.
% Pendolo inverso su carrello: modello, controllabilità, LQR
M = 5; % massa del carrello [kg]
m = 1; % massa del pendolo [kg]
L = 2; % lunghezza dell'asta [m]
g = 9.81; % accelerazione di gravità [m/s^2]
A = [0 1 0 0;
0 0 -m*g/M 0;
0 0 0 1;
0 0 (M+m)*g/(M*L) 0];
B = [0; 1/M; 0; -1/(M*L)];
eig(A) % un autovalore positivo: sistema instabile
rank(ctrb(A,B)) % 4: sistema completamente controllabile
% Allocazione dei poli
p = [-1 -1.5 -2 -2.5];
Kp = place(A,B,p);
% LQR
Q = diag([1 1 10 100]); % pesi su x, dx/dt, theta, dtheta/dt
R = 0.01; % peso sulla forza
K = lqr(A,B,Q,R);
eig(A - B*K) % poli in anello chiuso
% Simulazione sul modello non lineare
z0 = [0; 0; 0.2; 0]; % pendolo inclinato di 0.2 rad
zref = [1; 0; 0; 0]; % carrello fermo in x = 1 m
f = @(t,z) pendolo(z, -K*(z - zref), M, m, L, g);
[t, z] = ode45(f, [0 10], z0);
plot(t, z(:,1), t, z(:,3)); grid on;
legend('x [m]', '\theta [rad]'); xlabel('t [s]');
function dz = pendolo(z, u, M, m, L, g)
th = z(3); w = z(4);
s = sin(th); c = cos(th);
xdd = (u + m*L*w^2*s - m*g*s*c) / (M + m*s^2);
thdd = (g*s - xdd*c) / L;
dz = [z(2); xdd; w; thdd];
endWith these values the closed-loop poles are about −10.7, −0.85 and −0.74 ± 0.73j: the pendulum returns vertical and the cart stops at \(x=1\) m in less than 10 s, with a maximum force of about 60 N. Try changing \(Q\) and \(R\) and observe how the speed and the force required change.
In-depth videos
The three videos below, from the Control Bootcamp series by Steve Brunton (in English), show the same steps in MATLAB: model, pole placement and LQR. The model in the videos also includes friction on the cart, so the matrices are slightly different from those in this article.
Summary
- A Segway is modelled, to a first approximation, as an inverted pendulum on a cart, a nonlinear time-invariant system.
- Linearising around the vertical position gives a state-space model with a positive eigenvalue: the system is unstable.
- The controllability matrix has rank 4, so a state feedback can stabilise it.
- With
placeone chooses the poles; withlqrone chooses the trade-off between speed (\(Q\)) and control effort (\(R\)). - The controller must always be tested on the nonlinear model too.
Questions for practice
- Why does the cart position appear with a zero eigenvalue in the linearised model?
- What happens to the maximum force if \(R\) is reduced from 0.01 to 0.001?
- Does the LQR controller designed on the linear model still work when starting from 0.5 rad? Try it with the script.
- How would the model change if a viscous friction on the cart were added?





Benvenuti nella pagina su «definire un controllore per il segway in Matlab». L'ho scritta pensando a chi studia ingegneria elettronica: se un passaggio non vi torna, un esercizio vi dà un risultato diverso o volete altro materiale sull'argomento, chiedete pure nei commenti e vi risponderò. Un voto con le stelle qui sopra mi aiuta a capire quali pagine migliorare.