3
$\begingroup$

I have a long list and one element in that list is:

U[1, 3] U[1, 4] U[1, 5] U[2, 2] U[3, 1]

All entries of the list have the same structure of products of U[i,j]'s. In the current instance this is a product of 5 terms but it could be a product of n terms.

Is there a way to extract from the "monomial" U[1, 3]U[1, 4]U[1, 5]U[2, 2]U[3, 1] the first entries (1,1,1,2,3) and the second entries (3,4,5,2,1) of each factor of the monomial?

$\endgroup$

3 Answers 3

4
$\begingroup$

Oh dear... I was working too hard. This will do it.

vars = Variables[U[1, 3] U[1, 4] U[1, 5] U[2, 2] U[3, 1]];
firstindex = Table[vars[[q]][[1]], {q, 1,Length[vars]}];
secondindex = Table[vars[[q]][[2]], {q, 1, Length[vars]}]
$\endgroup$
2
  • 9
    $\begingroup$ firstindex = vars[[All, 1]] is even simpler. $\endgroup$ Commented May 22 at 14:55
  • $\begingroup$ @SjoerdSmit yeah even simpler. Thanks. $\endgroup$ Commented May 23 at 1:08
4
$\begingroup$

For

expr = U[1, 3] U[1, 4] U[1, 5] U[2, 2] U[3, 1];

you can do

{firstindex, secondindex} = Transpose[List @@@ List @@ expr]

or

{firstindex, secondindex} = expr /. {Times -> List, U -> List} // Transpose
$\endgroup$
3
$\begingroup$

Given,

expression = U[1, 3]  U[1, 4]  U[1, 5]  U[2, 2]  U[3, 1]

you could use Cases:

Cases[expression, U[a_, b_] :> {a, b}]
(* {{1, 3}, {1, 4}, {1, 5}, {2, 2}, {3, 1}} *)

or

Cases[expression, mono_U :> List @@ mono]
(* {{1, 3}, {1, 4}, {1, 5}, {2, 2}, {3, 1}} *)

That gives you both idices simultaneously, but it should be obvious how to adapt that to just one or the other if that's really what you want.

$\endgroup$
1
  • $\begingroup$ thanks. I can see how this would be very useful. $\endgroup$ Commented May 23 at 9:52

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.