2

I would like to transform a set of symbolic linear equations in to a form like: {0} = [M]*{v} where {0} is vector of zeros, [M] is the matrix of variables and {v} is the vector of coefficients.

Just for the sake of presenting you my problem, I would like if anyone could help me to write my example in the desired form:

from sympy import*
init_printing()

a_0, a_1, a_2, x  = symbols('a_0, a_1, a_2, x')

a_0 + a_1*x + a_2 * x**2

NOTE: I use LaTeX form, so in case you haven't got LaTeX installed, you should remove the init_printing().

So what I would like is to make a form like:

                   {a_0
{0} = [1 x x^2] *   a_1
                    a_2}

In my case there will be a set of similar linear equations, but I would like to learn the idea or the functions that would allow me to transform a set of linear equations in to matrix form.

mcluka
  • 285
  • 1
  • 7
  • 17
  • A few remarks: tags belong in tags, not in title; thanks/regards don't belong anywhere on Stack Overflow; a better focus would also help: "my goal is this but my question is this" is confusing. –  May 01 '16 at 23:39
  • 1
    Check the sympy function `linear_eq_to_matrix` – Stelios May 02 '16 at 08:07

2 Answers2

3

A simple trick to factor out the x terms is to take the Jacobian

In [40]: eq = a_0 + a_1*x + a_2 * x**2

In [41]: Matrix([eq]).jacobian(Matrix([a_0, a_1, a_2]))
Out[41]:
⎡       2⎤
⎣1  x  x ⎦

Another function that may be useful to you here is collect:

In [45]: collect(eq, x, evaluate=False)
Out[45]:
⎧               2    ⎫
⎨1: a₀, x: a₁, x : a₂⎬
⎩                    ⎭
asmeurer
  • 86,894
  • 26
  • 169
  • 240
1

The following sample demonstrates: creation of a polynomial, creation of a matrix with powers of x; creation of a matrix of coefficients; multiplication of matrices; extraction of an element of a matrix.

References: Polynomials Manipulation, Matrices.

from sympy import *
a_0, a_1, a_2, x  = symbols('a_0, a_1, a_2, x')
p = Poly( a_0 + a_1*x + a_2 * x**2, x)
powers = Matrix([[x**k for k in range(p.degree()+1)]])
c = p.all_coeffs()
c.reverse()
coefficients = Matrix(c)
print(powers, coefficients, (powers*coefficients)[0,0])