# using pattern matching to separate coefficients and functions

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:= Collect[func,x[y1_,y2_,y3_]]
Out:= (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.

(A1+B1)*x[1,0,0]+(A2+B2)*x[1,0,1]+(A3+B3)*x[1,1,1]/.{Plus->List,_*x[p_,q_,r_]->x[p,q,r]}


returns

{x[1,0,0],x[1,0,1],x[1,1,1]}


and

(A1+B1)*x[1,0,0]+(A2+B2)*x[1,0,1]+(A3+B3)*x[1,1,1]/.{Plus->List,a_*x[_,_,_]->a}


returns

{A1+B1,A2+B2,A3+B3}


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.

• 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. – Boogeyman May 25 at 3:31
• 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.. – Bill May 25 at 3:41