# Transform set of linear equations into matrix and two vectors

Consider a list L containing entries dependent on variables x[i] (the i are integer, yet not necessarily consecutive), i.e.

L={23 x + 45 x + 14 x - 21 , 9 x + 6 x - 90}


The entries of L are supposed to equal zero. I would like to reformulate the entries in terms of linear algebra $A\cdot\vec x=\vec b$. So I get vector $\vec b$ from

b = -L/.x[_]->0;


And I can get the terms $A\cdot \vec x$ from

Ax = L-b;


But how can I efficiently disentangle $A$ and $\vec x$? I would like to have a function that does the following:

getMatrixA[Ax]


{ {{23,45,14},{9,0,6}} , {x,x,x} }

Is there such a function in Mathematica? If no, how to implement it efficiently? Also, this example is obviously a toy problem. In practice I would need to do that for a list of several thousand entries with several thousand variables. The resulting matrix will be highly sparse, so it would be nice if the routine produced a sparse array object or something of the sort.

l = {23 x + 45 x + 14 x - 21, 9 x + 6 x - 90}
vars   = Union@Cases[l, x[__], Infinity]
coeffs = Normal@CoefficientArrays[#, vars] & /@ l

(* {x, x, x} *)
(* {{-21, {23, 45, 14}}, {-90, {9, 0, 6}}} *)


I believe that's it. For the format you requested:

{coeffs[[All, 2]], vars}
(* {{{23, 45, 14}, {9, 0, 6}}, {x, x, x}} *)

• Thank you! Wow, the code is surprisingly short! – Kagaratsch Feb 20 '16 at 3:28