Programmatically derive a matrix form of quadratic equation

161 Views Asked by At

Is there a way to do that? For example from this equation:

enter image description here

To this matrix form:

enter image description here

We especially would like to get thos matrices circled-red.

This is the code I have at the moment:

from sympy import *
x, y = symbols('x y')
expr = 0.5 * (x**2) + 3*x + 4*y
print(latex(expr))

I welcome suggestion other than Simpy.

At the end of the day I'd like to use it with CVXOPT or Scipy.

2

There are 2 best solutions below

4
On

I don't understand the code but I think the matrix can be derived, just as a straight forward rewritten, no calculations. $$(x,y)(\begin{array}{cc} c_{xx}& c_{xy}\\0& c_{yy}\end{array})(\begin{array}{c} x\\y\end{array})+(c_x, c_y)(\begin{array}{c} x\\y\end{array})$$ where $C_{xx} $ is the coefficient of $x^2$, $C_{xy}$ is the coefficient of $xy$, and so on.

0
On

Separate the expression into its first- and second-order terms. It should be fairly obvious how to derive the row vector of coefficients for the linear part. As for the quadratic part, a common way to represent it is with a symmetric matrix. The diagonal entries are just the coefficients of the squared terms, while the off-diagonal entries are the coefficients of the mixed terms divided by 2. E.g., if you have $ax^2+bxy+cy^2$, the corresponding matrix would be $\small\pmatrix{a & \frac b2 \\ \frac b2 & c}$. An upper-triangular matrix, as in Alexis’ answer, also works. Which is better depends on what you’re going to be doing with it.