4
$\begingroup$

I'm working with a finite list of linear equations in some amount of variables. Say,

{2kx-3y,3y+2kz-x,2x+2y+2z,ky}

Is it possible for Mathematica to take this list and output a list of pairs where the elements of the ordered pairs correspond to the coefficients of the variables in my formula? So in the list above, 2kx-3y corresponds to (2k,-3,0), 3y+2kz-x corresponds to (-1,3,2k), etc., so that the output list should be the following

{(2k,-3,0),(-1,3,2k),(2,2,2),(0,k,0)}

This is not homework, I just am building a program in python and it needs this output list as input.

$\endgroup$
8
$\begingroup$
lst = {2 k x - 3 y, 3 y + 2 k z - x, 2 x + 2 y + 2 z, k y};

You can use Coefficient as follows:

Flatten[Coefficient[#, {x, y, z}]] & /@ lst

{{2 k, -3, 0}, {-1, 3, 2 k}, {2, 2, 2}, {0, k, 0}}

$\endgroup$
0
$\begingroup$

One can also use CoefficientArrays[] (after post-processing with Normal[], because sparse arrays are produced by default):

Normal[Last[CoefficientArrays[{2 k x - 3 y, 3 y + 2 k z - x, 2 x + 2 y + 2 z, k y},
                              {x, y, z}]]]
   {{2 k, -3, 0}, {-1, 3, 2 k}, {2, 2, 2}, {0, k, 0}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.