1
$\begingroup$

Suppose I define a vector/list like this: v = {x + 3 y, z - x}

It can be expressed as a matrix vector multiplication m.vars:

vars = {x, y, z};
m = {
  {1, 3, 0},
  {-1, 0, 1}
};
v == m.vars (* True *)

Is there a built-in function to get this matrix m? I guess I wish there was a function like GetVarMatrix[v, {x, y, z}] that returns m. The closest thing I can do is the following:

M = Table[Mij[i, j], {i, 1, 2}, {j, 1, 3}];
Solve[M.{x, y, z} == {x + 3 y, z - x}, Flatten@M]

But it doesn't quite work as expected, since it displays the error message Equations may not give solutions for all "solve" variables., which makes sense, but I'd like it to find some particular matrix, preferrably a constant matrix. Is there a concise way to do it in Mathematica?

EDIT: It would also be nice if it was possible to specify that I expect a sparse matrix, which happens often in many applications.

$\endgroup$
1
$\begingroup$

You could use CoefficientArrays, and take the second part which gives the linear part:

CoefficientArrays[{x+3 y,z-x},{x,y,z}][[2]]

SparseArray[Automatic, {2, 3}, 0, { 1, {{0, 2, 4}, {{1}, {2}, {1}, {3}}}, {1, 3, -1, 1}}]

$\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.