Extracting matrix coefficients from multivariate matrices

Suppose we have a multivariate polynomial matrix $$P(\mathbf x) = \sum_\alpha A_\alpha\mathbf x^\alpha$$ (in multi-index notation) where the $$A_\alpha$$ are constant coefficient matrices.

I am looking for a Mathematica function MatrixCoefficientRules that takes a $$P(\mathbf x)$$ as input and returns the $$A_\alpha$$, as in:

mat = {{1, x}, {y, 0}};
MatrixCoefficientRules[mat, {x, y}]

Out = {
{0, 0} -> {{1, 0}, {0, 0}},
{1, 0} -> {{0, 1}, {0, 0}},
{0, 1} -> {{0, 0}, {1, 0}}
}


How could one go about constructing such a function?

For reference, the native CoefficientRules in my Mathematica 12.1 acts element-wise and returns a matrix of {order -> scalar coefficient} rules (instead of a list of {order -> matrix coefficient} rules):

CoefficientRules[mat, {x, y}]

Out = {
{ {{0, 0} -> 1}, {{1, 0} -> 1} },
{ {{0, 1} -> 1}, {}            }
}


I imagine there might be a quick way to go from this CoefficientRules to my desired MatrixCoefficientRules, but I am struggling to see it. Any help is appreciated!

• fyi, do not name your function starting with UpperCase. These are reserved for Mathematica own use. Always start your function name with lowerCase letter. Commented May 17 at 20:17
• Welcome to the community. The desired matrix can be derived with Coefficient. For example: Coefficient[mat, x, 0] (need some post-processing), Coefficient[mat, x], and Coefficient[mat, y]. Commented May 17 at 22:17

1 Answer

Not sure why you're using C array indices (start at zero) instead of Mma indices (start at one), nor why you ignore one of the matrix entries in the output. If that's not what you're doing, then I've misinterpreted something. (Sorry.)

mat = {{1, x}, {y, 0}};
Flatten[
MapIndexed[
#2 - 1 -> CoefficientList[#, {x, y}, 2] &,
mat, {2}],
1]
(*
{{0, 0} -> {{1, 0}, {0, 0}},
{0, 1} -> {{0, 0}, {1, 0}},
{1, 0} -> {{0, 1}, {0, 0}},
{1, 1} -> {{0, 0}, {0, 0}}}
*)