I want to find out the coefficients and functions from an expression and possibly save them in separate files with same order.

I have the following toy example:

func = A1*x[1,0,0] + A2*x[1,0,1] + A3*x[1,1,1] + 
       B1*x[1,0,0] + B2*x[1,0,1] + B3*x[1,1,1];

A priori I don't know the different forms of the functions x but I know it has fixed number of arguments in this case three arguments and there could be repetative x. Using Collect I can group repetative x. However how should I separate them in a file, in the most general way i.e. not knowing the explicit arguments of x.

In[1]:= Collect[func,x[y1_,y2_,y3_]]
Out[1]:= (A1 + B1)*x[1, 0, 0] + (A2 + B2)*x[1, 0, 1] + (A3 + B3)*x[1, 1, 1]

The final output would be two files, one containing the coefficients (A1+B1), (A2+B2), (A3+B3) and the other with corresponding functions x[1,0,0], x[1,0,1], x[1,1,1] in the same orders may be in a single column.


1 Answer 1


Can you adapt this:








which seem to give you the contents you desire in the order you desire.

Now it seems that you just need to write those two results to your two files.

  • $\begingroup$ I tested this and it is giving me correct output. However I have one question in mind. Is it guranteed that it will give both the list in the same order i.e. the first member of coefficient list corresponds to first member of function list and so on? This is important. Although in your solution indeed it is the case. But I just want to be sure. $\endgroup$
    – Boogeyman
    May 25, 2020 at 3:31
  • 1
    $\begingroup$ The reason in both cases that I first replaced Plus with List was to try to keep Mathematica from thinking that it needed to reorder the results into its default preferred order, because Mathematica doesn't reorder lists without being instructed to do so. Thus I think you are safe. But if I wanted to be really really certain I would want to find something in the documentation that said it would never change the order while doing a pattern match and replace. I expect it might be impossible to find that guarantee written anywhere, maybe it is assumed, maybe no one wrote that OR maybe it isn't.. $\endgroup$
    – Bill
    May 25, 2020 at 3:41

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.