# Parsing an expression for coefficients and more

I have many expressions of this form:

expression = 1/96 (-26 I + 15 Sqrt[3]) c[1] - c[1]^3/(8 Sqrt[3]) +
1/120 I c[1]^5 + 5/96 (-5 I + 2 Sqrt[3]) c[3] +
1/480 (11 I + 135 Sqrt[3]) c[5]


For each c[a]^b term, I want to form a tuple with the coefficient to c[a]^b, argument of c[a]^b which is a, and power of c[a]^b which is b. I want a list of all these tuples.

So for this example, I want a function of expression that returns {{1/96 (-26 I + 15 Sqrt[3]), 1,1},{1/(8 Sqrt[3]),1,3},...}

How do I do this with Mathematica?

• Try CoefficientRules[expression, Array[c, 5]]. The format of the output is a bit different what you asked for. But maybe it suits your needs. Jun 3, 2022 at 19:17

expression =
1/96 (-26 I + 15 Sqrt[3]) c[1] - c[1]^3/(8 Sqrt[3]) +
1/120 I c[1]^5 + 5/96 (-5 I + 2 Sqrt[3]) c[3] +
1/480 (11 I + 135 Sqrt[3]) c[5];

Cases[expression, coef_. * c[a_]^b_. :> {coef, a, b}, 1]

(* {{1/96 (-26 I + 15 Sqrt[3]), 1, 1},
{-(1/(8 Sqrt[3])), 1, 3},
{I/120, 1, 5},
{5/96 (-5 I + 2 Sqrt[3]), 3, 1},
{1/480 (11 I + 135 Sqrt[3]), 5, 1}} *)


EDIT: See the documentation for Default: "_. represents an argument that can be omitted" In this case, coef_. defaults to 1; b_. also defaults to 1

Default[Times]

(* 1 *)

Default[Power, 2]

(* 1 *)


EDIT 2: The example in your latest comment fails because the target is the whole expression rather than a part.

expr = 2 I c[1] Sin[Pi/7];

Cases[expr, coef_. * c[a_]^b_. :> {coef, a, b}, 1]

(* {{1, 1, 1}} *)


Since any result won't be affected by adding an arbitrary constant (say 1), do that for any input.

Cases[1 + expr, coef_. * c[a_]^b_. :> {coef, a, b}, 1]

(* {{2 I Sin[π/7], 1, 1}} *)

• Beautiful, thank you! Jun 3, 2022 at 19:16
• what's the dot do? eg b_. ? Jun 3, 2022 at 19:29
• Also, I dont think this answer is fully right - it doesn't work for instance with 1/4 Sqrt[3] c[1] - 1/6 I c[1]^3 + 1/12 (8 I + 3 Sqrt[3]) c[3], where I would have expected 3 tuples to be present, instead of just 2 Jun 3, 2022 at 19:41
• @MondoDuke coef_// FullForm gives Pattern[coef, Blank[]], coef_. // FullForm gives Optional[Pattern[coef, Blank[]]] Jun 3, 2022 at 19:43
• Your second example works fine for me. I get {{Sqrt[3]/4, 1, 1}, {-(I/6), 1, 3}, {1/12 (8 I + 3 Sqrt[3]), 3, 1}} Jun 3, 2022 at 19:47
1/96 (-26 I + 15 Sqrt[3]) c[1] - c[1]^3/(8 Sqrt[3]) +
1/120 I c[1]^5 + 5/96 (-5 I + 2 Sqrt[3]) c[3] +
1/480 (11 I + 135 Sqrt[3]) c[5] //
Apply[List]//
Map[Replace[coef_. * c[a_]^b_. :> {coef, a, b}]]


{{(-26*I + 15*Sqrt[3])/96, 1, 1}, {-1/(8*Sqrt[3]), 1, 3}, {I/120, 1, 5}, {(5*(-5*I + 2*Sqrt[3]))/96, 3, 1}, {(11*I + 135*Sqrt[3])/480, 5, 1}}

also

1/4 Sqrt[3] c[1] - 1/6 I c[1]^3 + 1/12 (8 I + 3 Sqrt[3]) c[3]//
Apply[List]//
Map[Replace[coef_. * c[a_]^b_. :> {coef, a, b}]]


{{Sqrt[3]/4, 1, 1}, {-I/6, 1, 3}, {(8*I + 3*Sqrt[3])/12, 3, 1}}

first = Function[t,FirstPosition[t , _?(# != 0 &)] ];

{{-I/6, 1, 3}, {Sqrt[3]/4, 1, 1}, {(2*I)/3 + Sqrt[3]/4, 3, 1}}