0
$\begingroup$

My input is a product of the variable x with index:

x[1]^2 x[5] x[7]

How do I extract the indices of the above product to get the list {1,1,5,7} as an output? Note 1 appears twice in the list since x[1] is squared.

I would like this code to work for any product of x[j]^n, where both j and n will be given integers.

$\endgroup$
3
  • 1
    $\begingroup$ Cases[expr, x[i_]^p_. :> Table[i, p], {1}] // Flatten $\endgroup$
    – Bob Hanlon
    Commented May 16, 2021 at 0:53
  • $\begingroup$ Thank you @BobHanlon. Your solution is simple -- do you want to submit your comment as an answer? $\endgroup$
    – Camilo
    Commented May 16, 2021 at 1:42
  • $\begingroup$ Just wanted to say: good job avoiding Subscript and using indexed variables instead! This is the way to go! :) $\endgroup$ Commented May 17, 2021 at 7:49

2 Answers 2

2
$\begingroup$
expr = x[1]^2 x[5] x[7];

Use Cases and include Default in the pattern for the exponent.

sol = Cases[expr, x[i_]^p_. :> Table[i, p], {1}] // Flatten

(* {1, 1, 5, 7} *)
$\endgroup$
2
$\begingroup$

Here is one way to achieve it, decomposed step by step:

ClearAll[x];
p = x[1]^2 x[5] x[7];
f = FactorList@p
Table[First@#, Last@#] & /@ Rest[f]
Flatten@%
Block[{x = # &}, %]
(*
{{1, 1}, {x[1], 2}, {x[5], 1}, {x[7], 1}}
{{x[1], x[1]}, {x[5]}, {x[7]}}
{x[1], x[1], x[5], x[7]}
{1, 1, 5, 7}
*)

(there may be a better way of extracting i from x[i]...)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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