image thumbnail

Comparing different methods to solve an Inverted Pendulum problem

by

 

A simple reporting tool that shows how you can model an inverted pendulum in a few methods.

example_syms.m
%% Using symbolic math to solve inverted pendulum:
syms t th(t) m
rho = 1;    % Pendulum length
g = 9.81;   % Gravity
% Basic symbolic calculations:
x = rho*cos(th(t));
y = rho*sin(th(t));
V_x = diff(x,t);
V_y = diff(y,t);

%% Calculate inertia of rod, and move from CM to connection:
Icm = m*rho^2/12;
Izz = Icm + m*(rho/2)^2;
% Define derivatives of Theta:
D2th(t) = diff(th(t),2);
Dth(t) = diff(th);

%% Try to solve symbolically - Is it possible?
th_sol(t) = dsolve(D2th == -m*g*cos(th(t))*rho/2/Izz,th(0)==pi/4, Dth(0)==0);

%% Can't solve symbolically, solve numerically using MATLAB Functions:
V = odeToVectorField(D2th == -m*g*cos(th(t))*rho/2/Izz,th(0)==pi/4, Dth(0)==0);
M = matlabFunction(V,'vars', {'t','Y'});
sol = ode45(M, [0 5], [pi/4 0]); % Solve for t = 0..5, theta(0) = pi/4
% Plot solution:
x = linspace(0, 5, 100);
y = deval(sol,x);
plot(x,y);
title('\theta and \theta'' vs. Time');
legend('\theta','\theta'''); 
xlabel('Time [sec]');

Contact us