1
$\begingroup$

I would like to obtain the coefficients of a general function f in a list. For example, the coefficient list of

testList = {{2 f[2] + 3 f[3]},{2 f[1]}, {Sqrt[2] f[4]}}

should be the list

{{2,3},{2},{Sqrt[2]}}

I've tried the obvious solution

CoefficientList[testList, Variables[testList]]

But this gives me a lot of extra information, plus requires a few more array operations to write it in the correct form. I was wondering if there was a more efficient way to do this, since my lists will be eventually very large?

$\endgroup$
3
$\begingroup$

Cases can be used to extract a value that's part of a pattern:

Cases[#, x_ f[_] -> x, Infinity] & /@ testList

Out:

{{2, 3}, {2}, {Sqrt[2]}}
$\endgroup$
  • $\begingroup$ Since the variable names could change: Cases[#, x_ Alternatives @@ Variables[testList] -> x, Infinity] & /@ testList $\endgroup$ – eldo Jan 11 '16 at 1:30

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.