5

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

L={23 x[10] + 45 x[23] + 14 x[36] - 21 , 9 x[10] + 6 x[36] - 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[10],x[23],x[36]} }

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.

Kagaratsch
  • 11,955
  • 4
  • 25
  • 72

1 Answers1

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

(* {x[10], x[23], x[36]} *)
(* {{-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[10], x[23], x[36]}} *)
Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453