Skip to content

Commit

Permalink
Replace manual matrix inversion with solve() (#590)
Browse files Browse the repository at this point in the history
  • Loading branch information
calcmogul authored Jul 5, 2024
1 parent 9d0b509 commit d4c6e98
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,6 @@ def cart_pole_dynamics_double(x, u):
]
)

detM = M[0, 0] * M[1, 1] - M[0, 1] * M[1, 0]
Minv = np.array(
[[M[1, 1] / detM, -M[0, 1] / detM], [-M[1, 0] / detM, M[0, 0] / detM]]
)

# [0 −m_p lθ̇ sinθ]
# C(q, q̇) = [0 0 ]
C = np.array([[0.0, -m_p * l * thetadot * math.sin(theta)], [0.0, 0.0]])
Expand All @@ -83,7 +78,7 @@ def cart_pole_dynamics_double(x, u):
# q̈ = M⁻¹(q)(τ_g(q) − C(q, q̇)q̇ + Bu)
qddot = np.empty((4, 1))
qddot[:2, :] = qdot
qddot[2:, :] = Minv @ (tau_g - C @ qdot + B @ u)
qddot[2:, :] = np.linalg.solve(M, tau_g - C @ qdot + B @ u)
return qddot


Expand Down
8 changes: 3 additions & 5 deletions test/src/CartPoleUtil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

#include "CartPoleUtil.hpp"

#include <Eigen/QR>

// https://underactuated.mit.edu/acrobot.html#cart_pole
//
// θ is CCW+ measured from negative y-axis.
Expand Down Expand Up @@ -44,10 +46,6 @@ Eigen::Vector<double, 4> CartPoleDynamicsDouble(
{m_c + m_p, m_p * l * cos(theta)}, // NOLINT
{m_p * l * cos(theta), m_p * std::pow(l, 2)}}; // NOLINT

double detM = M(0, 0) * M(1, 1) - M(0, 1) * M(1, 0);
Eigen::Matrix<double, 2, 2> Minv{{M(1, 1) / detM, -M(0, 1) / detM},
{-M(1, 0) / detM, M(0, 0) / detM}};

// [0 −m_p lθ̇ sinθ]
// C(q, q̇) = [0 0 ]
Eigen::Matrix<double, 2, 2> C{
Expand All @@ -65,7 +63,7 @@ Eigen::Vector<double, 4> CartPoleDynamicsDouble(
// q̈ = M⁻¹(q)(τ_g(q) − C(q, q̇)q̇ + Bu)
Eigen::Vector<double, 4> qddot;
qddot.segment(0, 2) = qdot;
qddot.segment(2, 2) = Minv * (tau_g - C * qdot + B * u);
qddot.segment(2, 2) = M.householderQr().solve(tau_g - C * qdot + B * u);
return qddot;
}

Expand Down

0 comments on commit d4c6e98

Please sign in to comment.