I have a 'list' of the form an expansion: F = (A[1] + A[2])(B[1] + B[2]), such that F[[1]] produces the result


Based on the values that appear in the brackets, I multiply the term with a certain term. I do this for each term in the Expansion of F, i.e. by using the iteration Do[ ... , {i, 1, Length[F], 1}]. However, when I multiply each term in F the ordering of terms change and I end up multiplying the same term more than once.

How could I use the HoldForm even when the list changes - where the change being the multiplication of each term in the list. I would want the order of terms to remain the same as the initial definition of $F$. Namely, I would like to multiply the first term of F by a predefined function that I have Bra[2,0] and so I obtain

A[2]B[1] + A[1]B[2] + A[2]B[2] + A[1]B[1]Bra[2,0],

but since I am iterating over each term (to multiply them) I would like for the outcome to instead read

A[1]B[1]Bra[2,0] + A[2]B[1] + A[1]B[2] + A[2]B[2].

In this way I would be able to change the second term of the 'list' and the whole procedure would be correct - you can see if I tried to change the second term of the list F when its order changes, I will be changing the wrong term.

I have seen similar posts, but not the case which makes use of the HoldForm function for a list changes. Thanks.

  • 1
    $\begingroup$ Something like List @@ Expand [F]? $\endgroup$ – J. M.'s technical difficulties Jun 3 '15 at 10:41
  • $\begingroup$ I have tried to multiply each of the terms in List @@ Expand [F], but the ordering of terms still change. I will make it more clear what I want to achieve. $\endgroup$ – Sid Jun 3 '15 at 10:52
  • 1
    $\begingroup$ @Guesswhoitis, converting the expression to a list does in fact work and I can achieve what I want through this method. However, would it be possible to still HoldForm for a list which changes. $\endgroup$ – Sid Jun 3 '15 at 11:40

One way to use HoldForm is to do something involving Insert like this:

F = (A[1] + A[2]) (B[1] + B[2]);

G = HoldForm[Evaluate@Expand@F];
Do[G = Insert[G, Bra[2, i - 1], {1, i, 3}], {i, 1, Length@Expand@F}]; 
G = ReleaseHold@G
A[1] B[1] Bra[2, 0] + A[2] B[1] Bra[2, 1] + A[1] B[2] Bra[2, 2] + A[2] B[2] Bra[2, 3]

This process is a little simpler with the Fold operation:

G = HoldForm[Evaluate@Expand@F;
G = ReleaseHold@Fold[Insert[#1, Bra[2, #2 - 1], {1, #2, 3}] &, G, Range@Length@Expand@F]
A[1] B[1] Bra[2, 0] + A[2] B[1] Bra[2, 1] + A[1] B[2] Bra[2, 2] + A[2] B[2] Bra[2, 3]

That said, I would still recommend the more natural Mathematica way recommended by Guess who it is:

Total@MapIndexed[#1 Bra[2, First@#2 - 1] &, List @@ Expand@F]
A[1] B[1] Bra[2, 0] + A[2] B[1] Bra[2, 1] + A[1] B[2] Bra[2, 2] + A[2] B[2] Bra[2, 3]
| improve this answer | |

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.